Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. eg:

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

Is there a way to achieve the following ordering:

1, 2, 3, 4, NULL, NULL, NULL. 
like image 340
JonB Avatar asked Jan 12 '10 19:01

JonB


People also ask

How do I sort by NULLs last in SQL?

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.

How are NULL values sorted in a regular ORDER BY clause?

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.

IS NULL values are displayed last in ascending sequences?

1 Answer. The correct answer is, option (a): Null values are displayed last in the ascending sequences.

How do you use NULLs last?

If the null ordering is not specified then the handling of the null values is: - NULLS LAST if the sort is ASC - NULLS FIRST if the sort is DESC - If neither ascending nor descending order is specified, and the null ordering is also not specified, then both defaults are used and thus the order will be ascending with ...


2 Answers

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 here http://troels.arvin.dk/db/rdbms#select-order_by

like image 88
Jarred Avatar answered Sep 25 '22 20:09

Jarred


I found this to be a good solution for the most part:

SELECT * FROM table ORDER BY ISNULL(field), field ASC; 
like image 41
d-_-b Avatar answered Sep 24 '22 20:09

d-_-b