tags:

views:

629

answers:

2

Hello!

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?

+7  A: 
order by coalesce(date-time-field,large date in future)
Gratzy
While this will generally work, it should be noted this answer has a few issues: large date in future may collide with or be less than actual data, resulting in an imperfect sort. Also, it is a "magic number" solution that is not self-documenting.
RedFilter
+6  A: 
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
RedFilter
This will make all of the not null date fields equal as "0" and the null fields "1" so the nulls will come after the not nulls but the not nulls won't be sorted.
Gratzy
@Gratzy: The null dates are ordered with a value *higher* than those that are **not null**, so the null values will appear at the end - it is a valid, correct answer.
OMG Ponies
@Gratzy: Note the second sort clause: the NOT NULL dates will come first as they all will get sorted by 0. Then, the second sort clause takes effect and they will all get ordered by MyDate.
RedFilter
@OrbMan I apologize I didn't see the second order by my bad
Gratzy
+1 Nifty trick (and just what I need) :-).
sleske