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

后端 未结 4 1172
逝去的感伤
逝去的感伤 2021-01-02 08:24

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

相关标签:
4条回答
  • 2021-01-02 09:09
    ORDER BY 
        CASE 
        WHEN Name IS NULL THEN 1 
        WHEN Name = ''    THEN 2 
        ELSE 3 
        END DESC, 
        Name ASC
    
    0 讨论(0)
  • 2021-01-02 09:12

    You can do it like this:

    ORDER BY CASE WHEN Name IS NULL then 3 WHEN Name = '' THEN 2 ELSE 1 END, Name
    

    It will order with by the number in the case first and afterwords by the Name.

    0 讨论(0)
  • 2021-01-02 09:19

    ORDER BY (CASE WHEN Name IS NULL THEN 1 WHEN Name IS NULL THEN 2 ELSE 3 END) DESC

    0 讨论(0)
  • 2021-01-02 09:20
    ORDER BY 
    CASE 
        WHEN Name IS NULL THEN 1 
        WHEN Name = '' THEN 2 
        ELSE 3
    END DESC,
    Name ASC
    
    0 讨论(0)
提交回复
热议问题