ORDER BY NULL in MySQL

后端 未结 5 578
独厮守ぢ
独厮守ぢ 2020-12-23 17:09

What is ORDER BY NULL in MySQL?

Does it decrease the query speed?

5条回答
  •  我在风中等你
    2020-12-23 17:30

    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 specified ORDER BY col1, col2, ... in the query as well. If you include an explicit ORDER BY clause that contains the same column list, MySQL optimizes it away without any speed penalty, although the sorting still occurs. If a query includes GROUP BY but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying ORDER 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.

提交回复
热议问题