TSQL ORDER BY with nulls first or last (at bottom or top)

后端 未结 4 1293
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 06:58

I have a date column which has some NULL. I want to order by the date column ASC, but I need the NULL s to be at the bottom. How to do it on

4条回答
  •  萌比男神i
    2020-12-24 07:15

    In standard SQL you can specify where to put nulls:

    order by col asc nulls first
    order by col asc nulls last
    order by col desc nulls first
    order by col desc nulls last
    

    but T-SQL doesn't comply with the standard here. The order of NULLs depends on whether you sort ascending or descending in T-SQL:

    order by col asc -- implies nulls first
    order by col desc -- implies nulls last
    

    With integers you could simply sort by the negatives:

    order by -col asc -- sorts by +col desc, implies nulls first
    order by -col desc -- sorts by +col asc, implies nulls last
    

    But this is not possible with dates (or strings for that matter), so you must first sort by is null / is not null and only then by your column:

    order by case when col is null then 1 else 2 end, col asc|desc -- i.e. nulls first
    order by case when col is null then 2 else 1 end, col asc|desc -- i.e. nulls last
    

提交回复
热议问题