Monday, 18 January 2010

TSQL: Order by Null OR zero first

The snippet below will order your values with any values as NULL or Zero first.

SELECT event_ID, event_title, event_date
FROM table_events
ORDER BY case when event_date is null or event_date = 0 then 1 else 2 end, event_date DESC

If you use union, you'll need to wrap your union statement within another SELECT before you can use the ORDER BY CASE statement above.

For example:

SELECT *
FROM
(
SELECT A, B, C
FROM Table1
UNION
SELECT X, Y, Z
FROM Table2
) X
ORDER BY A, B, C

No comments: