Difference between MySQL (SQL) SUBSTR - ORDER BY statements
Please help me understand the difference between the following 2 SQL statements, where the difference is in the way ORDER BY
using SUBSTR
is performed:
Query 1:
SELECT * FROM countrylanguage
ORDER BY SUBSTR(Language,-3,3)
LIMIT 10;
Query 2:
SELECT * FROM countrylanguage
ORDER BY Language LIKE '%___'
LIMIT 10;
Solution 1:
ORDER BY substr(language, -3, 3)
order the results lexicographically by the last three characters of the values of the column language
, if the values is at least three characters long. For all rows where the value is shorter than three characters, substr(language, -3, 3)
will yield the empty string, so these rows go to the top.
As LIKE '%___'
matches all strings with at least three characters -- the '%'
wildcard means any character an arbitrary number of times (also zero times) and '_'
any character exactly one time -- ORDER BY language LIKE '%___'
puts the rows where the value of language
is less than three characters long at the top, the ones where the values is at least three characters long at the bottom.
Rows where language
is NULL
are put atop in both cases.