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?
+16
A:
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
2010-06-28 05:18:35
Perfect, so simple!
FigBug
2010-06-28 05:23:11
can you put any boolean condition with the ORDER BY ?
JSmaga
2010-06-28 05:28:07
@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
2010-06-28 05:29:10
+1
A:
The following query should do the trick.
(SELECT * FROM table WHERE num!=0 ORDER BY num) UNION (SELECT * FROM table WHERE num=0)
JSmaga
2010-06-28 05:22:16