Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 27/ 160
02. Aggregations, Functions & Data Manipulation

NULL Handling Functions (COALESCE, NULLIF, IFNULL)

Replace, compare, and neutralize NULLs with COALESCE, NULLIF, and dialect helpers.

BeginnerCOALESCE · NULLIF3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

COALESCE picks the first value that isn't empty. NULLIF turns a value you don't want, like 0 or '', into empty.

Think of it like…

COALESCE is a list of contacts to try in order: call the mobile, and if there's no answer, the office, then the home number. NULLIF is a rule like "treat a blank form field as not filled in".

Where you’ve seen it

Conversion rate per campaign without division-by-zero errors: SELECT campaign, COALESCE(signups, 0) AS signups, signups::numeric / NULLIF(visits, 0) AS conversion FROM campaign_stats;. Campaigns with no visits get a NULL rate instead of an error.

Words you’ll hear

COALESCE
First non-NULL argument; standard SQL; any number of arguments.
NULLIF(a, b)
NULL if a = b, otherwise a.
IFNULL / ISNULL / NVL
Two-argument dialect versions of COALESCE.
Type compatibility
All COALESCE arguments must share a compatible type.

Visual diagram

Loading interactive diagram

Theory & example queries

COALESCE and its dialect cousins

COALESCE evaluates its arguments left to right and returns the first that isn't NULL, or NULL if they all are. It accepts any number of arguments and works in every major database, so prefer it over IFNULL, ISNULL or NVL in portable code.

All arguments must be of compatible types. COALESCE(quantity, 'n/a') mixes an integer with text and fails in PostgreSQL; cast explicitly with COALESCE(quantity::text, 'n/a'). SQL Server's ISNULL also takes the type of its first argument, which can silently truncate the fallback value.

Display name with fallbacksQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  COALESCE(3    display_name,4    first_name || ' ' || last_name,5    email6  ) AS name7FROM8  users;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative display names3 sample rows
Representative display names
name
Asha
Ravi Kumar
nina@example.com

Note: The sample uses one user with display_name, one with only first_name/last_name, and one with only email; rows whose three sources are NULL would also return NULL.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: COALESCE: first non-NULL, standard, keep the types consistent.

NULLIF for safe division and cleaning data

Dividing by zero is an error in most databases. a / NULLIF(b, 0) turns a zero divisor into NULL, and anything divided by NULL is NULL, so the query keeps running. Wrap the result in COALESCE if the report needs 0 instead of blank. Cast to numeric first to avoid integer division.

NULLIF also normalises placeholder values: NULLIF(TRIM(phone), '') treats empty strings as missing, and NULLIF(score, -1) handles a legacy "-1 means unknown" convention, so aggregates and COUNT(col) treat them correctly.

Average order value per day, never failingQuery example
1Input dataStart from the source rows or state that the statement sees.
daily_stats
2 rows
daily_stats sample rows
dayrevenueorders
2026-11-201001
2026-11-216003
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  DAY,3  revenue::numeric / NULLIF(orders, 0) AS aov4FROM5  daily_stats;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative daily averages3 sample rows
Representative daily averages
dayaov
2026-11-18800
2026-11-19625
2026-11-20NULL

Note: Sample data assumes revenue/orders of 2400/3, 2500/4 and 0/0. NULLIF makes the zero-order division return NULL rather than fail.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Divide by NULLIF(denominator, 0); clean sentinels with NULLIF.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Semantics

Decide what NULL should mean

Is a missing value really zero, unknown, or "not applicable"? Only replace it when the replacement is true for the business.

Focus at this step

missing discount = 0? missing rating ≠ 0

What to watch at this step
Ask
is the fallback true?
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

COALESCE(a, b, c, …) returns the first argument that isn't NULL, so it's the standard way to supply a fallback value. NULLIF(a, b) does the reverse: it returns NULL when a equals b, and a otherwise. Dialects add two-argument shortcuts: IFNULL (MySQL, SQLite), ISNULL (SQL Server) and NVL (Oracle).

Why it matters: Reports need 0 instead of blank, names need a fallback when a field is missing, and ratios must not crash on division by zero. These two functions handle all of that, and x / NULLIF(y, 0) is a pattern interviewers expect you to know.

When to reach for it

  • Showing 0 instead of NULL for totals in reports
  • Fallback names, labels and contact details
  • Ratios and rates where the denominator can be zero

When to avoid or be careful

  • Replacing NULL with 0 when missing doesn't mean zero (ratings, temperatures)
  • COALESCE around indexed columns in WHERE
  • Mixing types in COALESCE without casting

COALESCE vs IFNULL / ISNULL / NVL vs CASE

COALESCE
Best for: Portable fallbacks with one or more alternatives

Strengths: Standard SQL, any number of arguments.

Watch out: Arguments must have compatible types.

IFNULL / ISNULL / NVL
Best for: Short two-argument fallbacks in one specific database

Strengths: Familiar to people who use that dialect.

Watch out: Not portable; SQL Server's ISNULL can truncate to the first argument's type.

CASE WHEN … IS NULL
Best for: Fallbacks with extra conditions

Strengths: Full control over the logic.

Watch out: Verbose for a simple fallback.

Interview signals & numbers to know

When this topic comes up

  • “Show 0 instead of NULL”
  • "division by zero" error
  • Conversion rate or ratio queries
  • Empty strings stored instead of NULL
  • COALESCE vs ISNULL

Benchmarks & rules of thumb

1st non-NULL -
what COALESCE returns
NULLIF(x, 0) -
the standard divide-by-zero guard
2 -
arguments allowed by IFNULL / ISNULL / NVL

Common mistakes & follow-ups

Common interview mistakes

  • Dividing by a column that can be 0 and getting a runtime error in production.
  • Writing COALESCE(int_column, 'none') and getting a type error.
  • Wrapping a filtered column in COALESCE and turning an index lookup into a full scan.

Likely interviewer follow-ups

  • How would you calculate a conversion rate safely when some campaigns have zero visits?
  • What's the difference between COALESCE and ISNULL in SQL Server?
  • How would you treat empty strings and NULLs the same in a report?
Interview tip: Show numerator::numeric / NULLIF(denominator, 0) whenever a question involves a rate. It handles both integer division and division by zero, and interviewers notice.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply NULL Handling Functions (COALESCE, NULLIF, IFNULL) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Pivoting Data Using Conditional Aggregation (SUM(CASE WHEN ...))
Next topic
String Functions (CONCAT, SUBSTRING, TRIM, UPPER, LOWER, REPLACE)