1

Table has a nullable ContactDate field. I want to sort these records so that non-null values come first in ascending order and then null values are sorted after non-nullable values.

Select * from myTable Order by ContactDate ASC

returns following

NULL
NULL
NULL
NULL
2015-07-27 10:00:00.000
2015-07-29 10:00:00.000

then,

Select * from myTable Order by ContactDate DESC

returns following

2015-07-29 10:00:00.000
2015-07-27 10:00:00.000
NULL
NULL
NULL
NULL

But I need it like this:

2015-07-27 10:00:00.000 -- asc
2015-07-29 10:00:00.000 -- asc
NULL
NULL
NULL
NULL

Using MS SQL Server 2012

ilija veselica
  • 9,414
  • 39
  • 93
  • 147

2 Answers2

5

Use a case statement in order by.

Query

select * from myTable
order by case when ContactDate is null then 1
else 0 end,ContactDate;

Fiddle demo

Ullas
  • 11,450
  • 4
  • 33
  • 50
0

You could use ISNULL() to convert the NULL values to 9999-12-31 and then order by ContactDate:

SELECT * FROM myTable
ORDER BY ISNULL(CONVERT(VARCHAR, ContactDate), '9999-12-31') ASC
fez
  • 1,726
  • 3
  • 21
  • 31