Sort Values Ascending But NULLS Last
From Wiki
You want to sort the column in ascending order but don't want the NULLS at the beginning. Oracle has this syntax: ORDER BY ColumnName NULLS LAST; SQL Server does not have this. But there are 2 ways to do this. The first one is by using case and the second one by using COALESCE and the maximum value for the data type in the order by clause.
The 2 approaches with a datetime data type
- DECLARE @Temp TABLE(Col DATETIME)
- INSERT INTO @Temp VALUES(GETDATE())
- INSERT INTO @Temp VALUES('2007-10-19 09:54:03.730')
- INSERT INTO @Temp VALUES('2006-10-19 09:54:03.730')
- INSERT INTO @Temp VALUES('2005-10-19 09:54:03.730')
- INSERT INTO @Temp VALUES('2006-10-19 09:54:03.730')
- INSERT INTO @Temp VALUES('2004-10-19 09:54:03.730')
- INSERT INTO @Temp VALUES(NULL)
- INSERT INTO @Temp VALUES(NULL)
- SELECT *
- FROM @Temp
- ORDER BY COALESCE(Col,'9999-12-31 23:59:59.997')
- SELECT *
- FROM @Temp
- ORDER BY CASE WHEN Col IS NULL THEN 1 ELSE 0 END, Col
The 2 approaches with an integer data type
- DECLARE @Temp TABLE(Col INT)
- INSERT INTO @Temp VALUES(1)
- INSERT INTO @Temp VALUES(555)
- INSERT INTO @Temp VALUES(444)
- INSERT INTO @Temp VALUES(333)
- INSERT INTO @Temp VALUES(5656565)
- INSERT INTO @Temp VALUES(3)
- INSERT INTO @Temp VALUES(NULL)
- INSERT INTO @Temp VALUES(NULL)
- SELECT *
- FROM @Temp
- ORDER BY COALESCE(Col,2147483647)
- SELECT *
- FROM @Temp
- ORDER BY CASE WHEN Col IS NULL THEN 1 ELSE 0 END, Col
Contributed by: --SQLDenis 02:53, 31 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Handy tricks


