So Oracle has NULLS FIRST, which I can use to have null values sorted at the top followed by my column value in descending order:
ORDER BY date_sent NULLS FI
ORDER BY
COALESCE(POSTING_DATE,'1900-01-01 00:00:00.000')
,OTHER_FIELDS
You can't control this, to my knowledge. And it looks like you have the correct approach with ISNULL
.
With strings, I've used ISNULL(field, '')
for the same purpose.
You can do some trick:
ORDER BY (CASE WHEN [Order] IS NULL THEN 0 ELSE 1 END), [Order]
Use Case/When statement, for example:
ORDER BY (case WHEN ColINT IS NULL THEN {maxIntValue} ELSE ColINT END) DESC
ORDER BY (case WHEN ColVChar IS NULL THEN {maxVCharValue} ELSE ColVChar END) DESC
ORDER BY (case WHEN ColDateT IS NULL THEN {maxDateTValue} ELSE ColDateT END) DESC
...and so on.
or even better as you don't care what is your column type and the max value.
ORDER BY (case WHEN ColAnyType IS NULL THEN 1 ELSE 0 END) DESC, ColAnyType DESC
The quick answer is this: the best solution for changing the ordering of nulls in the necessary cases is the accepted one. But you only have to use it, or a variation of it in the necessary cases:
DESC + NULLS FIRST:
ORDER BY (CASE WHEN [Order] IS NULL THEN 0 ELSE 1 END), [Order] DESC
ASC + NULLS LAST:
ORDER BY (CASE WHEN [Order] IS NULL THEN 1 ELSE 0 END), [Order] ASC
ASC + NULLS FIRST: it works fine by default
DESC + NULLS LAST: it works fine by default
Let's see why:
If you check the ORDER BY Clause (Transact-SQL) MSDN docs, and scroll down to ASC | DESC
, you can read this:
ASC | DESC
Specifies that the values in the specified column should be sorted in ascending or descending order. ASC sorts from the lowest value to highest value. DESC sorts from highest value to lowest value. ASC is the default sort order. Null values are treated as the lowest possible values.
So, by default if you specify ASC
order, it works like NULLS FIRST
. And, if you specify DESC
, it works like NULLS LAST
.
So you only need to do change the behavior for NULLS FIRST
in DESC
order, and for NULLS LAST
in ASC
order.
IMHO, the best solution for changing the ordering of nulls in the necessary cases is the accepted one, but I've included it adapted to the different cases in the beginning of my answer.
This is an alternative way when you want to adjust how nulls appear in the sort order. Negate the column and reverse your sort order. Unfortunately you would need to CAST dateTime columns.
ORDER BY -CAST(date_sent as int) ASC