SQL Sort Order with Null values last SQL Sort Order with Null values last sql-server sql-server

SQL Sort Order with Null values last


One way is to sort it like this:

ORDER BY (CASE WHEN Foo IS NULL THEN 1 ELSE 0 END), Foo

Or: First sort by null, then sort by the Foo contents.


You can also do

SELECT * FROM #Foo ORDER BY COALESCE(Foo, 2147483647)

which will replace NULL with the largest possible int for the purposes of sorting only (so leaving the retured values alone) and so shunt it to the back of any order.