SQL how to make null values come last when sorting ascending

David Božjak picture David Božjak · Sep 30, 2009 · Viewed 259.1k times · Source

I have a SQL table with a datetime field. The field in question can be null. I have a query and I want the results sorted ascendingly by the datetime field, however I want rows where the datetime field is null at the end of the list, not at the beginning.

Is there a simple way to accomplish that?

Answer

D'Arcy Rittich picture D'Arcy Rittich · Sep 30, 2009
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate