SQL NULLS FIRST
Forces NULL values to the top of the sort, overriding the default placement.
What & Why
By default in Postgres, ORDER BY ... ASC puts NULLs last (NULLs are treated as larger than any real value). NULLS FIRST overrides that, forcing them to the top regardless of sort direction.
See How It Works
BUSINESS QUESTION
Sort product feedback by nps_score and deliberately place missing scores first.
| 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 ASC NULLS FIRST;RESULT — NULLs first
| id | user_id | nps_score |
|---|---|---|
| 2 | 102 | NULL |
| 4 | 104 | NULL |
| 3 | 103 | 7 |
| 1 | 101 | 9 |
NULLS FIRST moves missing scores before known numeric values.
Now You Try
Practice this concept
Product wants features without a deprecation timestamp at the top of a lifecycle review.
Available schema
productPrefix tables with product.table_name.
nameteamdeprecated_atproduct.features| Column | Type |
|---|---|
| id | integer |
| name | text |
| description | text |
| team | text |
| released_at | timestamp with time zone |
| deprecated_at | timestamp with time zone |
| internal_priority | integer |
query.sql
Sign up free to try it on a real business scenario