mysqlsql-order-by

MySQL Orderby a number, Nulls last


Currently, I am doing a very basic OrderBy in my statement.

SELECT * FROM tablename WHERE visible=1 ORDER BY position ASC, id DESC

The problem with this is that NULL entries for 'position' are treated as 0. Therefore, all entries with position as NULL appear before those with 1,2,3,4. For example,

NULL, NULL, NULL, 1, 2, 3, 4

Is there a way to achieve the following ordering?

1, 2, 3, 4, NULL, NULL, NULL.

Solution

  • MySQL has an undocumented syntax to sort nulls last. Place a minus sign (-) before the column name and switch the ASC to DESC:

    SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC
    

    It is essentially the inverse of position DESC placing the NULL values last but otherwise the same as position ASC.

    A good reference is Comparison of different SQL implementations, Ordering result sets.