Tier 3 · Intermediate

COALESCE and NULLIF in SQL

By Owen Middleton · Updated September 2026 · Examples run on PostgreSQL 17

What are COALESCE and NULLIF in SQL?

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.

How do you replace NULL with a default in SQL?

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:

SELECT COALESCE(NULL, NULL, 'third option') AS result

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 and unequal, because the leftmost one always wins.

Should you wrap SUM in COALESCE to get zero?

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.

What does NULLIF do in SQL?

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.

How do you avoid a division by zero error in SQL?

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.

Can NULLIF test anything other than equality?

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 COALESCE and NULLIF in SQL

Practice · easy ecommerce · Brightlane

Brightlane's customer success team is preparing a regional outreach list and needs every customer to have a displayable city.

Write a query to return each customer's name and a display value for their city.

Assumptions:

  • The customers table has one row per customer with a name and a city.
  • Some customers have a missing city value because they registered without entering one.
  • A customer with a missing city should appear as 'Not on File'; all other customers should show their recorded city.

Output:

  • One row per customer, with columns name and city.
Schema · ecommerce5 tables? = nullable
categories
idinteger
nametext
parent_id?integer
products
idinteger
nametext
category_id?integer
pricenumeric
stock_qtyinteger
attributes?jsonb
order_items
idinteger
order_id?integer
product_id?integer
quantityinteger
unit_pricenumeric
customers
idinteger
nametext
emailtext
city?text
countrytext
created_attimestamptz
is_activeboolean
orders
idinteger
customer_id?integer
ordered_attimestamptz
statustext
total_amountnumeric

Run previews · Check grades

Write a query, then run it to see results here.

Worked solution

The full breakdown walks through the shape, each clause, why this approach beats the alternatives, and the trap to avoid.

See the full worked solution

9 COALESCE and NULLIF practice problems

Start learning to practice all 9 COALESCE and NULLIF problems, with instant grading and mastery tracking.

Deeper guides on COALESCE and NULLIF

Common questions about COALESCE and NULLIF

How many arguments can COALESCE take?

As many as you need. It works through them left to right and returns the first that is not NULL, so a chain of fallbacks ending in a literal guarantees the result is never NULL.

Does the order of COALESCE arguments matter?

Yes, and it decides the answer whenever more than one is populated. The leftmost non-NULL value always wins, so putting a nickname before a first name gives a different result from the other way round.

What type does COALESCE return when its arguments differ?

A single type that all of them fit. An integer beside a decimal resolves to numeric, and types that cannot be reconciled are an error rather than a silent conversion. The result has one type however many branches you give it.

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.