Skip to content

Beginner: asking questions · Functions, CASE and NULL · topic 15 of 62 · 30 min

NULL: the missing value

Explanation

NULL marks a value that is missing or unknown. Arithmetic and text joins with NULL give NULL, and comparisons with NULL are unknown, so rows with NULL quietly drop out of filters. COALESCE replaces NULL with a fallback (IFNULL in SQLite and MySQL, ISNULL in SQL Server), and NULLIF turns a value into NULL, which avoids dividing by zero.

What NULL means

NULL is not zero, not an empty text, and not the word "NULL". It is a marker that says "we do not know this value" or "there is no value". Priya Nair has no email in SHOP; Sneha Patil was absent, so her marks are NULL. Zero marks would mean she wrote the exam and scored nothing, which is a very different fact.

Module 2 showed the three-valued logic: a comparison with NULL is neither true nor false but unknown, so = NULL never matches and you test with IS NULL. This topic is about living with NULL in calculations, and replacing it when you need a value.

NULL spreads

ExpressionResult
NULL + 5, NULL * 0NULL
'Priya' || NULLNULL
UPPER(NULL), LENGTH(NULL)NULL
NULL = NULL, NULL <> 1NULL (unknown)
'' IS NULLfalse: an empty text is a value
sql
SELECT name || ' <' || email || '>' AS label FROM customers WHERE id IN (2, 3);
-- Ravi Kumar <ravi@example.com>
-- NULL                            <- Priya's whole label vanished

COALESCE: the first value that is not NULL

COALESCE(a, b, c, ...) checks its arguments from left to right and returns the first one that is not NULL. With two arguments it means "use a, or b if a is missing". It is standard SQL and works in every major database.

sql
SELECT name, COALESCE(email, 'not given') AS email FROM customers;
-- Asha Verma  | asha@example.com
-- Priya Nair  | not given
-- Arjun Reddy | not given   ... 6 rows
sql
SELECT name, marks, marks + 5 AS with_grace, COALESCE(marks, 0) + 5 AS grace_or_zero
FROM students WHERE id IN (4, 5);
-- Imran Khan  | 58   | 63   | 63
-- Sneha Patil | NULL | NULL | 5
Choose the fallback with care: treating "absent" as 0 marks may or may not be right for the report.
DatabaseTwo-argument shortcutNote
SQLite, MySQLIFNULL(x, fallback)Same as COALESCE(x, fallback)
SQL ServerISNULL(x, fallback)In MySQL, ISNULL(x) is different: it only tests and returns 1 or 0
OracleNVL(x, fallback)
All of themCOALESCE(x, fallback, ...)Standard; prefer it
Tip: Keep the fallback the same type as the column. COALESCE(manager_id, 'none') mixes a number and text; SQLite allows it, but PostgreSQL raises an error.

NULLIF: make a value NULL on purpose

NULLIF(a, b) returns NULL when a equals b, otherwise a. Its main use is safe division. A campaign with 0 clicks cannot have a cost per click, and dividing by 0 is an error in PostgreSQL ("division by zero") and SQL Server ("Divide by zero error encountered"). NULLIF(clicks, 0) turns the 0 into NULL, and anything divided by NULL is NULL, so the query runs and that row shows "no value".

sql
SELECT name, ROUND(spend * 1.0 / NULLIF(clicks, 0), 2) AS cost_per_click
FROM campaigns;
-- Diwali Sale    | 20.83
-- Monsoon Offer  | 26.67
-- New Year Kurta | NULL      <- 0 clicks, no crash
-- Holi Colours   | 17.78

SQLite and MySQL (with default settings) already return NULL for x / 0 instead of failing, so you will not see the error here. Write NULLIF anyway: the query then behaves the same on every database, and it tells the reader you thought about zero.

NULL in sorting, DISTINCT and comparisons

  • Sorting: SQLite and MySQL put NULLs first in ascending order, PostgreSQL last. Use NULLS LAST, or sort by COALESCE(marks, -1), to control it (module 2).
  • DISTINCT treats all NULLs as one group, so SELECT DISTINCT dept_id shows a single NULL.
  • Filters: WHERE dept_id <> 1 skips Deepak, whose dept_id is NULL. To include him, write WHERE dept_id IS DISTINCT FROM 1 (standard SQL, PostgreSQL, SQLite 3.39+, SQL Server 2022) or SQLite's shorter dept_id IS NOT 1.
  • Counting: COUNT(*) counts rows, COUNT(marks) counts only rows where marks is not NULL. Module 4 builds on this.

Common mistakes

  • Testing with = NULL. Use IS NULL / IS NOT NULL.
  • Replacing NULL with 0 everywhere. An unknown amount is not a zero amount; averages and totals change. Decide per report.
  • Joining text pieces with || when one can be NULL, and losing the whole value. Wrap each optional piece in COALESCE.
  • Dividing by a column that can be 0. Use NULLIF(column, 0).
  • Using ISNULL(x, 0) in MySQL. There ISNULL takes one argument; use IFNULL or COALESCE.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

NULL: the missing value · 1/7

NULL: the missing value

NULL means missing or unknown. It is not zero, and it is not an empty text.

Prefer a video by a teacher? Find free videos on “sql null coalesce nullif ifnull isnull tutorial” on YouTube ↗

In real life: Ad reports in a marketing dashboard

Marketing dashboards show cost per click and conversion rate for each campaign. A brand-new campaign may have zero clicks, and an old one may have no order data. Analysts use NULLIF so a zero never crashes the report and COALESCE so blanks show a clear label, instead of letting one odd row break the whole dashboard.

sql
SELECT name,
       ROUND(spend * 1.0 / NULLIF(clicks, 0), 2)          AS cost_per_click,
       ROUND(orders * 100.0 / NULLIF(clicks, 0), 1)       AS conversion_pct,
       COALESCE(orders, 0)                                AS orders_shown
FROM campaigns;
Diwali Sale: 20.83, 5% and 120 orders. New Year Kurta: NULL, NULL and 0. Holi Colours: 17.78, NULL and 0.

Practice (0/4 done)

Task 1 · Code · SQL

From customers, return name and email, but show 'not given' when the email is missing. Name the second column email.

Task 2 · Code · SQL

From campaigns, return name and the cost per click (spend divided by clicks) rounded to 2 decimal places, named cost_per_click. Use NULLIF so a campaign with 0 clicks gives NULL instead of an error on other databases, and avoid integer division.

Task 3 · Code · SQL

How many students have no marks recorded? Return one column named missing_marks.

Task 4 · Code · SQL

List everyone who is NOT in department 1, including people with no department. Return name and dept_id from employees (COMPANY).

Quick quiz

Question 1

1.What does COALESCE(NULL, NULL, 'Pune', 'Delhi') return?

Question 2

2.What does NULLIF(0, 0) return?

Question 3

3.Which is the SQL Server function for "use x, or 0 when x is NULL"?

Question 4

4.Why write spend / NULLIF(clicks, 0) instead of spend / clicks?

Question 5

5.Sneha has NULL marks. Which statement is true?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does COALESCE(NULL, NULL, 'Pune', 'Delhi') return?

Answer: 'Pune'

COALESCE returns the first argument that is not NULL.

What does NULLIF(0, 0) return?

Answer: NULL

NULLIF gives NULL when the two values are equal.

Which is the SQL Server function for "use x, or 0 when x is NULL"?

Answer: ISNULL(x, 0)

SQL Server has ISNULL(x, 0); COALESCE(x, 0) also works there and everywhere else.

Why write spend / NULLIF(clicks, 0) instead of spend / clicks?

Answer: Dividing by 0 is an error in PostgreSQL and SQL Server; NULLIF makes it NULL instead

Anything divided by NULL is NULL, so the query keeps running.

Sneha has NULL marks. Which statement is true?

Answer: marks + 5 for her is NULL

Arithmetic with NULL gives NULL; use IS NULL to find her, and NULL sorting differs between databases.

Why does WHERE email = NULL return no rows?Related

Answer: Comparing with NULL gives unknown, and WHERE keeps only true rows

Use IS NULL to test for missing values.

From IN, BETWEEN, LIKE and NULL

How do you find rows where email is missing?Related

Answer: WHERE email IS NULL

NULL is not equal to anything, so = NULL never matches. Use IS NULL.

From SELECT and WHERE: finding rows

Deepak has dept_id NULL. Does WHERE dept_id <> 1 return him?Related

Answer: No, because the comparison gives unknown, and WHERE keeps only true

Any comparison with NULL gives unknown; use IS NULL to find such rows.

From WHERE: comparison and logic

What is marks + 5 when marks is NULL?Related

Answer: NULL

Arithmetic with NULL gives NULL.

From SELECT, columns, aliases and expressions

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Functions, CASE and NULL”. The module exam comes next.
  2. Module 3 exam: Functions, CASE and NULL · 15 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Aggregation: GROUP BY and HAVING. 62 topics left in the course before the final exam.

← Previous: CASE expressions