Thursday, February 5, 2015

[MySQL][SQL][Example] ORDER BY column and nulls value at last

If you want to order the MySQL records with a column and in ascending order, by default, null values is smaller than the numbers, and would makes the rows with null values placed at the beginning of your returned results.

An Example:
SELECT c.section_id, c.url_name, c.lineage, c.url, c.sorting
FROM tbl_ccc as c
ORDER BY c.sorting ASC
 


=====================================
The "syntax NULLS LAST" may not works for MySQL old version, and you may try the solution provided by Luksurious at stackoverflow to make Null values to last, that works for me:

Select *
from some_table
order by some_column DESC NULLS LAST
Apply that to an real case:
SELECT c.section_id, c.url_name, c.lineage, c.url, c.sorting
FROM tbl_ccc as c
ORDER BY c.sorting IS NULL, c.sorting ASC


Reference:
http://stackoverflow.com/questions/1498648/sql-how-to-make-null-values-come-last-when-sorting-ascending
http://stackoverflow.com/questions/5826210/rails-order-with-nulls-last/7055259#7055259

No comments :

Post a Comment