Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How can I order null and empty entries to the front in an orderby?

If I have the following entries in my database:

ID Name
1 [null]
2 [empty string]
3 Alpha
4 Bravo
5 Charlie

..then how can I order the rows with names to the front when using ORDER BY?

If I use ORDER BY Name, I get the list above, but I actually want:

3 Alpha
4 Bravo
5 Charlie
1 [null]
2 ''

like image 220
NickG Avatar asked Jan 26 '12 16:01

NickG


1 Answers

ORDER BY 
    CASE 
    WHEN Name IS NULL THEN 1 
    WHEN Name = ''    THEN 2 
    ELSE 3 
    END DESC, 
    Name ASC
like image 80
JNK Avatar answered Sep 22 '22 20:09

JNK