Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 TSQL?

like image 205
Myurathan Kajendran Avatar asked Mar 23 '17 20:03

Myurathan Kajendran


People also ask

What happens to the NULLs in the ORDER BY?

If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.

When data is sorted in ascending order NULL values appear first in the list?

SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.

Does ORDER BY or WHERE come first SQL?

The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query. Use ASC or DESC to specify the sorting order after the column name.


2 Answers

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 
like image 89
Thorsten Kettner Avatar answered Sep 19 '22 15:09

Thorsten Kettner


Select *  From  YourTable  Order By case when DateCol is null then 0 else 1 end          ,DateCol 

Or even Order By IsNull(DateCol,'2525-12-31')

like image 21
John Cappelletti Avatar answered Sep 16 '22 15:09

John Cappelletti