N028 Tier 3 · Intermediate

COALESCE and NULLIF in SQL

`COALESCE` and `NULLIF` are two scalar functions that convert between NULL and non-NULL values. `COALESCE` replaces NULL with a fallback; `NULLIF` produces NULL when a condition is met.

COALESCE gives you a fallback when a column is NULL. NULLIF does the opposite: it converts a specific value into NULL when you want SQL to treat it as missing.

You're building a product revenue report. Some products haven't had any sales yet, so the revenue column is NULL for those rows. Aggregate functions like SUM and AVG skip NULL values entirely, which is often fine for calculations. But when you display totals in a report, a NULL looks like a gap in the data, and you'd rather show zero. COALESCE is what you reach for.

COALESCE accepts any number of arguments and returns the first one that is not NULL:

SELECT product_name, COALESCE(revenue, 0) AS revenue
FROM products

SQL checks each row's revenue value. If it is not NULL, that value comes through. If it is NULL, SQL returns 0 instead. The output column is always filled.

You can chain as many fallbacks as you need:

SQL works through the list left to right, and the first non-NULL value wins. This is useful when a table has multiple columns that might carry the same piece of information and you want the best available one:

SELECT COALESCE(nickname, first_name, 'Unknown') AS display_name
FROM customers

If nickname exists, use it. If not, try first_name. If that too is NULL, return 'Unknown'. Order matters: COALESCE(a, b) and COALESCE(b, a) produce different results whenever both are non-NULL, because the leftmost one always wins.

One common application: wrapping an aggregate. SUM returns NULL when every row in a group is NULL. Wrapping it gives you a usable zero: COALESCE(SUM(revenue), 0). A NULL total and a zero total mean different things. NULL means no data existed for that group. Zero means data existed and summed to nothing. Replacing one with the other is a deliberate presentational choice, not a free cleanup.

NULLIF takes exactly two arguments and returns NULL if they are equal, or the first argument if they are not:

SELECT NULLIF(status, 'N/A') AS status
FROM orders

If status is 'N/A', NULLIF converts it to NULL. If status is anything else, it passes through unchanged. This is useful when a column holds a placeholder string standing in for a missing value — converting it to a true NULL lets NULL-aware logic handle it correctly.

The other classic use is protecting against division by zero:

SELECT revenue / NULLIF(num_orders, 0) AS avg_order_value
FROM monthly_summary

If num_orders is zero, NULLIF returns NULL, and dividing by NULL produces NULL instead of an error. If num_orders is anything else, the division runs normally.

The one thing that trips people up: NULLIF only tests equality between its two arguments.

You cannot use it to suppress a value based on a range or a more complex condition. For anything beyond simple equality, use CASE WHEN:

CASE WHEN score < 0 THEN NULL ELSE score END

Both COALESCE and NULLIF are shorthand for CASE WHEN expressions. COALESCE(a, b) is equivalent to CASE WHEN a IS NOT NULL THEN a ELSE b END. They follow the same NULL rules as CASE WHEN, which is why they handle NULL correctly where a naive = check would not.

Check your understanding

You write NULLIF(quantity, 0) and the quantity column contains the value 0. What does NULLIF return?

Practice

9 COALESCE and NULLIF practice problems

These problems are part of the COALESCE and NULLIF lesson in SQLMaxx, with instant grading and a worked solution on each.

How you actually get good at SQL

Reading explains SQL. Writing it, over and over with instant feedback, is what makes you fluent.

That's the whole SQLMaxx loop: 600+ real problems, instant AI feedback, mastery you can actually see, and spaced review that won't let you forget.

A stack of SQL practice problem cards, the top card showing an employees table.
615 problems · 66 concepts

Real problems. Not toy examples.

615 hand-built problems spanning all 66 concepts, from basic SELECTs to window functions, built on real schemas and real business questions, the kind you'll actually get asked on the job. Enough reps to make SQL automatic.

A retro computer showing a SQL query marked correct with a green checkmark.
Instant AI feedback

Write a query. Know if it's right in one second.

No copying an answer and hoping it clicked. The AI grader checks your real query against real data, catches exactly what's wrong, and explains the fix in plain English, like a senior analyst reading over your shoulder on every problem.

A circular mastery progress dial filling from blue to green, the SQLMaxx diamond at its center.
Mastery tracking

Stop guessing whether you actually know it.

SQLMaxx tracks every concept and shows you what you've mastered and what's still shaky. Your skills fill in one concept at a time, so 'I think I get joins' becomes something you can prove.

A SQL query editor circled by a blue return arrow with a clock, scheduled to come back for review.
Spaced review

Learn it once. Keep it for good.

Most of what you learn this week fades by next week. So when a concept comes due for review, SQLMaxx hands you a fresh problem to solve from a blank editor, not a flashcard to re-read. A research-backed spaced-repetition algorithm (FSRS) times each return for right before you'd forget, so your SQL is still there months later, when the interview or the job actually needs it.

Practice, feedback, mastery, review. That's the loop that turns reading into real skill.

Start free

No account, no credit card. Start solving in under a minute.