Tuesday, May 8, 2012

MySQL: Sort by column with NULLs on top

Common task, when you need to sort table data by a column, that may have null values and you want to put nulls to the top.

Example table

id | name | salary
---|------|-------
 1 | John | 1000
 2 | Mary | 500
 3 | Paul | null

The following SQL request sorts the table by salary putting the nulls on top:

SELECT * FROM table ORDER BY IFNULL(salary, 0)

Using IFNULL(column, 0) we simply substitute null with zero, so it gets to the top.

Result:

id | name | salary
---|------|-------
 3 | Paul | null
 2 | Mary | 500 
 1 | John | 1000


No comments:

Post a Comment