SQL & Databases·Reshaping results

NULLs and COALESCE

Treat missing data deliberately instead of letting it break comparisons.

Beginner 12 min read Lesson 9 of 480 Challenge included
What you will be able to do
  • Test for NULL with IS NULL
  • Replace missing values with COALESCE
  • Avoid NOT IN surprises

NULL means unknown or not applicable. It is not zero and not an empty string. Any comparison with NULL produces unknown, which filters the row out.

nulls.sqlSQL
SELECT c.title, l.title AS lesson
FROM courses c
LEFT JOIN lessons l
  ON l.course_slug = c.slug AND l.minutes > 15
ORDER BY c.title, l.title;

SELECT c.title,
       COALESCE(l.title, 'no long lesson') AS longest
FROM courses c
LEFT JOIN lessons l
  ON l.course_slug = c.slug AND l.minutes > 15
ORDER BY c.title;
ExpressionResult
NULL = NULLUnknown, not true
IS NULLTrue when the value is missing
COALESCE(a, b)First non-NULL argument
NULLIF(a, b)NULL when a equals b
Your turn

Total minutes with a zero fallback

Medium

Return every course title and its total lesson minutes, showing 0 when a course has no lessons.

SQL · starter
SELECT c.title,
       SUM(l.minutes) AS minutes
FROM courses c
LEFT JOIN lessons l ON l.course_slug = c.slug
GROUP BY c.id, c.title
Check your understanding before moving on.
Knowledge checkQuestion 1

Which predicate tests for a missing value?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: CASE expressions
Lesson 9 of 480 · 0% of course