NULL Handling Functions (COALESCE, NULLIF, IFNULL)
Replace, compare, and neutralize NULLs with COALESCE, NULLIF, and dialect helpers.
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
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.
| id | country | city | signup_date |
|---|---|---|---|
| 1 | IN | Pune | 2026-10-01 |
| 2 | IN | Delhi | 2026-10-02 |
| 3 | NULL | Mumbai | 2026-10-03 |
SELECT COALESCE( display_name, first_name || ' ' || last_name, email ) AS nameFROM users;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative display names3 sample rows
| 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.
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.
| day | revenue | orders |
|---|---|---|
| 2026-11-20 | 100 | 1 |
| 2026-11-21 | 600 | 3 |
SELECT DAY, revenue::numeric / NULLIF(orders, 0) AS aovFROM daily_stats;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative daily averages3 sample rows
| day | aov |
|---|---|
| 2026-11-18 | 800 |
| 2026-11-19 | 625 |
| 2026-11-20 | NULL |
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.
Key takeaway: Divide by NULLIF(denominator, 0); clean sentinels with NULLIF.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
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.
missing discount = 0? missing rating ≠ 0
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
Strengths: Standard SQL, any number of arguments.
Watch out: Arguments must have compatible types.
Strengths: Familiar to people who use that dialect.
Watch out: Not portable; SQL Server's ISNULL can truncate to the first argument's type.
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?
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
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.