Learn SQL/Intermediate/NULL Handling/SQL COALESCE (NULL Handling)

SQL COALESCE (NULL Handling)

Returns the first non-NULL value from a list — the standard tool for substituting a fallback value wherever NULL shows up.

What & Why

COALESCE(a, b, c, ...) evaluates each argument in order and returns the first one that isn't NULL. With two arguments — COALESCE(column, fallback) — this reads as "use the column's value, or this fallback if it's NULL."

See How It Works

BUSINESS QUESTION

Product wants feedback comments to show a clear fallback when no comment exists.

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 AS feedback_id,
  COALESCE(NULLIF(TRIM(comment), ''), 'No comment') AS feedback_text
FROM product.feedback
ORDER BY feedback_id;
RESULT — exact output from the displayed Queryflo rows
feedback_idfeedback_text
1Clear and useful
2Export worked well
3Helpful setup flow
4Needs clearer timing

All displayed comments are present, so COALESCE returns their stored text.

Now You Try

Practice this concept

Product wants feedback comments to show a clear fallback when no comment exists.

Available schema
product

Prefix tables with product.table_name.

feedback_idfeedback_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