What is ORDER BY NULL
in MySQL?
Does it decrease the query speed?
If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.
using ORDER BY NULL is a workaround that satifies the syntax requirement but does not actually change the order of the data. In effect it is an instruction to not order at all. N.B.: some (myself included) prefer to use SELECT 1 instead of SELECT NULL but there is no difference in effect.
If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.
Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values. Because the result of any arithmetic comparison with NULL is also NULL , you cannot obtain any meaningful results from such comparisons. In MySQL, 0 or NULL means false and anything else means true.
It's for performance; adding ORDER BY NULL
after a GROUP BY
clause will make your query faster.
An explanation, from the manual:
By default, MySQL sorts all
GROUP BY col1, col2, ...
queries as if you specifiedORDER BY col1, col2, ...
in the query as well. If you include an explicitORDER BY
clause that contains the same column list, MySQL optimizes it away without any speed penalty, although the sorting still occurs. If a query includesGROUP BY
but you want to avoid the overhead of sorting the result, you can suppress sorting by specifyingORDER BY NULL
. For example:INSERT INTO foo SELECT a, COUNT(*) FROM bar GROUP BY a ORDER BY NULL;
This article describes the author successfully optimising a slow query by exploiting this trick, complete with the relevant parts of the EXPLAIN
output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With