Sql Server equivalent to Oracle's NULLS FIRST?
Put NULL
values at the top of your sort result in SQL Server using CASE
in your ORDER BY
:
This command promotes NULL
values by assigning a lower sort precedence (0
) than non-nulls (1
). So, voila! NULL
values get VIP access in the ascending sort order.
Handling reverse gear - descending order
In the wild wild west of data manipulation, sometimes you need your data in a good old descending order. But, oh my SQL! You still want NULL
values to show up first (on top). Just déja-vu the numeric priority and you're good to go.
So you see, NULL
s still gatecrash the party before your actual data, which then follows in descending order. Just like fashionably late celebs! 😎
Other sorts of funny business
The magical ISNULL function
If CASE
isn't your thing, ISNULL()
can be your knight-in-shining-armor and sort in your favor:
A word of advice: pick 'AReallyLowValue' that falls before your actual values (like picking a good movie seat - you know, prioritizing the view).
Specific non-date values
If you're sorting non-date columns, use this:
And for date columns, this should do the trick:
A pro-tip here: we use '19000101' (sort of a "Ye Olde Date") to treat NULL
dates as prehistoric artifacts!
Customizing the CASE
statement
SQL Server's natural disposition
In default mode, NULL
values are treated as the least valuable in an ascending sort and the most valuable in a descending order (SQL Server's mood swings!). Override this capricious behavior with a CASE
:
Your call! Ascending or Descending order
SQL isn't bossy. It lets you choose the sort - ascending or descending. Just tweak the CASE WHEN
logic and your wish is SQL's command.
Custom orders
As SQL Server doesn't offer in-built NULLS FIRST | LAST
syntax like Oracle, CASE WHEN
is your swiss army knife for crafting custom sorts.
Data context is key
Think data context when choosing between CASE
and ISNULL
- what makes sense considering the uniqueness, integrity, and readability of your data.
Was this article helpful?