SQL Sorting Hacks: Prioritize or Push Null Dates Back in Results
Sorting with NULL Dates in SQL: Putting Nulls at the End
Using CASE expression:
This method uses a CASE
expression to assign a value depending on whether the date is null or not. We then sort by this assigned value first (in descending order) and then by the actual date (also in descending order).
SELECT *
FROM your_table
ORDER BY CASE WHEN your_date_field IS NULL THEN 1 ELSE 0 END DESC,
your_date_field DESC;
Explanation:
CASE
: This checks if theyour_date_field
is null.- If null, it assigns
1
.
- If null, it assigns
ORDER BY
:- We first sort by the result of the
CASE
expression in descending order (DESC). This places null values (assigned1
) at the top. - Then, we sort by the actual
your_date_field
also in descending order, ensuring proper date sorting within non-null values.
- We first sort by the result of the
Using COALESCE function:
This method utilizes the COALESCE
function, which replaces null values with a specified value. We use '9999-12-31'
(a very late date) as a placeholder for nulls.
SELECT *
FROM your_table
ORDER BY COALESCE(your_date_field, '9999-12-31') DESC;
COALESCE(your_date_field, '9999-12-31')
: This replaces null values inyour_date_field
with the string'9999-12-31'
.ORDER BY
: We sort by the result of theCOALESCE
function in descending order. Since null values are replaced with a very late date, they effectively appear at the end.
Related Issues:
- Database-specific functions: Some databases offer functions like
ISNULL
for null checks. However, it's recommended to useCASE
orCOALESCE
for wider compatibility across different SQL dialects. - Performance: The
CASE
andCOALESCE
methods might have slightly different performance implications depending on the database and data size. Benchmarking might be necessary for large datasets.
sql mysql