Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MySql, can I sort a column but have 0 come last?

I want to sort by an column of ints ascending, but I want 0 to come last. Is there anyway to do this in MySql?

like image 555
Roland Rabien Avatar asked Jun 28 '10 05:06

Roland Rabien


People also ask

How do I ORDER BY NULL last?

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 do I sort by NULLs last in SQL?

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.

When data is sorted in ascending order NULL values appear first in the list?

SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.

Does MySQL column order matter?

Yes, column order does matter.


2 Answers

You may want to try the following:

SELECT * FROM your_table ORDER BY your_field = 0, your_field; 

Test case:

CREATE TABLE list (a int);  INSERT INTO list VALUES (0); INSERT INTO list VALUES (0); INSERT INTO list VALUES (0); INSERT INTO list VALUES (1); INSERT INTO list VALUES (2); INSERT INTO list VALUES (3); INSERT INTO list VALUES (4); INSERT INTO list VALUES (5); 

Result:

SELECT * FROM list ORDER BY a = 0, a;  +------+ | a    | +------+ |    1 | |    2 | |    3 | |    4 | |    5 | |    0 | |    0 | |    0 | +------+ 8 rows in set (0.00 sec) 
like image 155
Daniel Vassallo Avatar answered Sep 25 '22 18:09

Daniel Vassallo


You can do the following:

SELECT value, IF (value = 0, NULL, value) as sort_order FROM table ORDER BY sort_order DESC 

Null values will be down of the list.

like image 28
perfectio Avatar answered Sep 23 '22 18:09

perfectio