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.
Before this NULL Semantics and IS NULL, CASE WHEN Expressions
Builds toward NULL Handling in Joins and Aggregates, FIRST_VALUE, LAST_VALUE, NTH_VALUE
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 productsSQL 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 customersIf 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 ordersIf 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_summaryIf 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 ENDBoth 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.
You write NULLIF(quantity, 0) and the quantity column contains the value 0. What does NULLIF return?
9 COALESCE and NULLIF practice problems
Write a query to return each customer's name and a display value for their city.
Write a query to return each employee's name and a display value for their supervisor ID.
Write a query to return each order's ID and its export status.
Write a query to return each customer's name and their best-available location label.
Write a query to return each product's name and its per-unit inventory cost.
Write a query to return each session's ID, user ID, start time, and effective end time.
Write a query to return each user's name and their display plan label.
Write a query to return each user's name and their plan status label.
Write a query to return the name and price-per-unit-in-stock of every qualifying product.
These problems are part of the COALESCE and NULLIF lesson in SQLMaxx, with instant grading and a worked solution on each.
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.
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.
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.
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.
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 freeNo account, no credit card. Start solving in under a minute.