Updated on 2022-11-18 GMT+08:00

ORDER BY

ORDER BY

The ORDER BY clause is used to sort the result set by one or more output expressions.

ORDER BY expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...]

Each expression can consist of output columns or you can select the sequence number of an output column by position.

The ORDER BY clause is executed after the GROUP BY or HAVING clause and before the OFFSET, LIMIT, or FETCH FIRST clause.

Complying with the SQL specification, the ORDER BY clause affects only the row order of the query that immediately contains this clause. HetuEngine complies with this specification and deletes redundant usage of the clause to avoid negative impact on performance.

Tables in SQL statements are essentially unordered. In this case, the ORDER BY clause does not cause any difference, but has a negative impact on the performance of the entire INSERT statement. Therefore, HetuEngine skips the sorting operation.

  • ORDER BY applies only to the SELECT clause.
    INSERT INTO some_table
    SELECT * FROM another_table
    ORDER BY field;
  • The example of ORDER BY redundancy is nested query, which does not affect the result of the entire statement.
    SELECT *
    FROM some_table
    JOIN (SELECT * FROM another_table ORDER BY field) u
    ON some_table.key = u.key;