Skip to content
Advertisement

SQL Server : Order By 2 Columns (get ColumnX > Null First and then Id > Order By DESC)

I want to retrieve records from MSSQL Server according to 2 column values: ColumnX and Id.

First I want to retrieve null records of ColumnX (at the top) and then order by Id desc (I just need to order null records of ColumnX at the top of the list). Is it possible to make this? When I try this query, I retrieve null values of ColumnX, but then retrieve according to ColumnX values. However I want to order by Id column DESC after null values of ColumnX. Any idea?

SELECT Id, ColumnX 
FROM Table
ORDER BY ColumnX , Id DESC

Advertisement

Answer

You can include multiple expressions in the order by:

order by (case when x is null then 1 else 2 end),  -- put null values first
         id desc
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement