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?
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.
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.
SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.
Yes, column order does matter.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With