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?
Asked
Active
Viewed 2.4k times
4 Answers
132
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)

Daniel Vassallo
- 337,827
- 72
- 505
- 443
-
3can you put any boolean condition with the ORDER BY ? – SRKX Jun 28 '10 at 05:28
-
2@JSmaga: You can use any expression. See the `ORDER BY` [syntax here](http://dev.mysql.com/doc/refman/5.1/en/select.html): `[ORDER BY {col_name | expr | position}` – Daniel Vassallo Jun 28 '10 at 05:29
-
Thanks alot. Superb – Phoenix Aug 18 '16 at 06:01
-
How to get this result in MS SQL query? – Dharmesh Goswami Aug 09 '17 at 11:11
-
1@Daniel Vassallo It's nice. But what it says? and How it works? – Siva S Sep 14 '17 at 04:46
-
1@DanielVassallo This sure does work. But what is the principle behind this working ? – mjs Mar 28 '18 at 05:53
-
@DanielVassallo it's work. But how it work with limit? – Surya prakash Patel Aug 11 '18 at 10:01
3
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.

perfectio
- 69
- 3
0
The following query should do the trick.
(SELECT * FROM table WHERE num!=0 ORDER BY num) UNION (SELECT * FROM table WHERE num=0)

SRKX
- 1,806
- 1
- 21
- 42