Conditional ORDER BY based on NULL values in the column
-
24-01-2021 - |
Question
I have a table like this. table(student_name nvarchar(20) not NULL, grades int). When I write
select * from table
order by grades asc
It shows this
student_name | grades
---------------------
Ann | NULL
Bob | NULL
Bob | 10
Jane | 25
Nelly | 30
when select * from table
order by grades desc
student_name | grades
---------------------
Nelly | 30
Jane | 25
Bob | 10
Ann | NULL
Bob | NULL
But I need to order by like this. NULLs in the end but those who have grades order by ascending order, like
student_name | grades
---------------------
Bob | 10
Jane | 25
Nelly | 30
Ann | NULL
Bob | NULL
How it is possible to do a conditional order by like this? How to specify NULL values to be at the end?
Solution
You could add a case when check to the order by to give the NULL's a lower priority and then filter on grades
SELECT *
FROM table
ORDER BY CASE WHEN grades IS NULL
THEN 2 ELSE 1 END ASC, grades ASC;
Since you are using integers you can also do this, which should be more performant
SELECT *
FROM table
ORDER BY -grades DESC;
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange