SQL NULLS LAST
Forces NULL values to the bottom — already the default for ASC, but not for DESC.
What & Why
NULLS LAST forces NULLs to the end of the sort. This already happens automatically with ASC in Postgres — but DESC's default is actually the opposite (NULLS FIRST), so this keyword matters most when sorting descending and still wanting NULLs at the bottom.
See How It Works
BUSINESS QUESTION
Sort product feedback from highest NPS score to lowest and keep missing scores at the bottom.
| id | user_id | feature_id | rating | nps_score | comment | created_at |
|---|---|---|---|---|---|---|
| 1 | 101 | 1 | 5 | 9 | Clear and useful | 2024-01-25 12:15:00+00 |
| 2 | 102 | 2 | 4 | NULL | Export worked well | 2024-02-20 15:40:00+00 |
| 3 | 103 | 1 | 4 | 7 | Helpful setup flow | 2024-03-18 09:05:00+00 |
| 4 | 104 | 3 | 3 | NULL | Needs clearer timing | 2024-04-08 17:30:00+00 |
EXAMPLE QUERY
SELECT id, user_id, nps_score FROM product.feedback
ORDER BY nps_score DESC NULLS LAST;RESULT — NULLs last
| id | user_id | nps_score |
|---|---|---|
| 1 | 101 | 9 |
| 3 | 103 | 7 |
| 2 | 102 | NULL |
| 4 | 104 | NULL |
DESC sorts known scores high to low; NULLS LAST keeps missing values at the bottom.
Sign up free to try it on a real business scenario