In SQL Server, I have a column such as ID containing integers in descending order with one null value
ex.
ID
====
20
19
18
...
2
1
null
select id from mytable order by id desc
I need this to be ordered descending but null on top:
ID
====
null
20
19
18
...
2
1
The null is a result of a prior
union all
and needs to be there.
I had a few ideas, such as create an artificial large number.
Just want to see what your guys can come up with.
Have fun!
Use a
CASEin yourORDER BYto force theNULLs first. This is supported by SQL Server.It works by deriving a “column” on which to sort that holds a 0 for
NULLand 1 for everything else. The 0 sorts ahead of the 1. Then, we add the rest of theORDER BYcolumn chain to continue sorting, so addingid DESCforces the remaining rows (those with our derived 1) to sort in descending order by id.