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

Viewed 246

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
2 Answers

Try this :

SELECT ID, ColumnX 
FROM Table 
order by (case when ColumnX is null then 1 else 2 end),  
         ID DESC

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
Related