SQL COALESCE

Returns the first non-NULL value from a list — the standard way to supply a fallback for missing data, without writing a full CASE expression.

What & Why

COALESCE(value1, value2, ..., valueN) checks each argument in order and returns the first one that isn't NULL. If every argument is NULL, the whole expression returns NULL too. It's functionally equivalent to writing CASE WHEN value1 IS NOT NULL THEN value1 WHEN value2 IS NOT NULL THEN value2 ... ELSE NULL END — but far more compact for this specific, extremely common job.

See How It Works

BUSINESS QUESTION

Product wants every feedback row to show its NPS score or a readable fallback when no score was submitted.

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
Watch COALESCE choose the first known valueExample 1 of 4
COALESCE(nps_score::text, 'No score')
idnps_scorefeedback_text
199
2NULL?
37?
4NULL?

The score is known, so COALESCE stops at its first argument.

EXAMPLE QUERY
SELECT
  id AS feedback_id,
  nps_score,
  COALESCE(nps_score::text, 'No score') AS feedback_text
FROM product.feedback
ORDER BY feedback_id
LIMIT 20;
Now You Try

Practice this concept

Product wants every feedback row to show its NPS score or a readable fallback when no score was submitted.

Available schema
product

Prefix tables with product.table_name.

feedback_idnps_scorefeedback_text
product.feedback
ColumnType
idinteger
user_idinteger
feature_idinteger
ratinginteger
nps_scoreinteger
commenttext
created_attimestamp with time zone
moderation_buckettext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario