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.

iduser_idfeature_idratingnps_scorecommentcreated_at
1101159Clear and useful2024-01-25 12:15:00+00
210224NULLExport worked well2024-02-20 15:40:00+00
3103147Helpful setup flow2024-03-18 09:05:00+00
410433NULLNeeds clearer timing2024-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
iduser_idnps_score
2102NULL
4104NULL
31037
11019

NULLS FIRST moves missing scores before known numeric values.

Beginner business practice

Sign up free to try it on a real business scenario