NULL Functions

Updated · 7 min read
easyPostgreSQL 18sqlcoalescenullifnullifnullnvlinterview

COALESCE returns the first value in its list that isn't NULL, and NULLIF turns a value into NULL when it equals another. Missing data is everywhere in real tables. Advitha has no email, Navika has neither email nor phone, and one payment has no method. Reports still need something sensible in those cells: "Unknown", a phone number when there's no email, or 0 for a total that's empty. This lesson covers COALESCE and NULLIF, the classic divide-by-zero fix, and the names each database uses for the same ideas.

In One Minute

  • coalesce(a, b, c) returns the first non-NULL argument, or NULL if all are NULL.
  • Use it to fill gaps: coalesce(method, 'Unknown'), or to fall back: coalesce(email, phone, 'no contact').
  • nullif(a, b) returns NULL if a = b, otherwise a.
  • x / nullif(y, 0) turns divide-by-zero errors into NULL.
  • COALESCE is standard; MySQL's IFNULL, SQL Server's ISNULL and Oracle's NVL take exactly two arguments.

COALESCE

SQL
coalesce(value_1, value_2, ..., value_n)

A label for every payment method, including the missing one:

SQL▶ Try it
SELECT payment_id, coalesce(method, 'Unknown') AS method
FROM payments
ORDER BY payment_id;
Output
 payment_id | method
------------+---------
          1 | card
          2 | card
          3 | check
          4 | card
          5 | Unknown
          6 | card
          7 | check
(7 rows)

For payment 5, method is NULL, so coalesce moved on to 'Unknown'. For the others, method has a value, which is returned as it is.

With more arguments, COALESCE is a fallback chain. The best way to contact each student:

SQL▶ Try it
SELECT first_name, coalesce(email, phone, 'no contact') AS contact
FROM students
ORDER BY student_id;
Output
 first_name |            contact
------------+--------------------------------
 Srihitha   | srihitha.anamaneni@example.com
 Advitha    | (415) 555-0178
 Navika     | no contact
(3 rows)

Srihitha has an email, so that's used. Advitha has no email but has a phone. Navika has neither, so she gets the final text. The arguments are checked left to right, and checking stops at the first value that exists.

For each student, email, then phone, then 'no contact': the first non-NULL wins

All arguments must have compatible types: coalesce(phone, 0) fails with COALESCE types character varying and integer cannot be matched, because a phone is text. Use coalesce(phone, '(none)').

NULLIF

SQL
nullif(value, value_that_means_missing)

NULLIF is the opposite of COALESCE: it turns a value into NULL. It returns NULL when its two arguments are equal, and the first argument otherwise:

SQL▶ Try it
SELECT nullif(5, 5) AS same, nullif(5, 3) AS different;
Output
 same | different
------+-----------
 NULL |         5
(1 row)

It's useful when data uses a placeholder for "missing", such as an empty string '' or 0: nullif(phone, '') makes empty phones real NULLs, which aggregates and COALESCE then handle correctly.

Avoiding Division by Zero

Dividing by zero is an error, and NULLIF turns it into NULL instead.

SQL▶ Try it
SELECT 10 / 0;
Output
ERROR:  division by zero

What does each course earn per enrolled student? Git Basics has no students, so a plain division would fail for it and stop the whole query. With nullif(students, 0), dividing by zero becomes dividing by NULL, which gives NULL:

SQL▶ Try it
SELECT c.title, c.fee_usd, count(e.student_id) AS students,
       round(c.fee_usd / nullif(count(e.student_id), 0), 2) AS fee_per_student
FROM courses AS c
LEFT JOIN enrollments AS e ON e.course_id = c.course_id
GROUP BY c.course_id, c.title, c.fee_usd
ORDER BY c.course_id;
Output
       title       | fee_usd | students | fee_per_student
-------------------+---------+----------+-----------------
 Java Basics       |  450.00 |        2 |          225.00
 Java OOP          |  500.00 |        1 |          500.00
 Java Collections  |  550.00 |        1 |          550.00
 SQL Basics        |  400.00 |        2 |          200.00
 JavaScript Basics |  450.00 |        1 |          450.00
 Git Basics        |  250.00 |        0 |            NULL
(6 rows)

Every course gets a value except Git Basics, which gets NULL, meaning "not applicable", instead of an error. Wrap the whole thing in coalesce(..., 0) if the report should show 0.

Git Basics has 0 students; nullif(0, 0) is NULL, so the division gives NULL instead of an error

The Same Ideas in Other Databases

DatabaseTwo-argument fillStandard version
PostgreSQLcoalesce(a, b)coalesce
MySQLIFNULL(a, b)coalesce also works
SQL ServerISNULL(a, b)coalesce also works
OracleNVL(a, b)coalesce also works
AccessNz(a, b), and IsNull(a) to testIIf(IsNull(a), b, a)

COALESCE and NULLIF work in all of them, so they're the portable choice. One trap: SQL Server's ISNULL(a, b) is a fill function, but MySQL's ISNULL(a) is a test that returns 1 or 0. Same name, different jobs. Tabs showing each database's version are coming to this course.

COALESCE everywhere, plus IFNULL, ISNULL, NVL and Nz

Common Mistakes

Mixing types in COALESCE. coalesce(phone, 0) fails. Make the fallback the same type.

Using = NULL instead of COALESCE or IS NULL. method = NULL is never true.

Dividing without protection. One zero divisor stops the query. Use nullif(divisor, 0).

Assuming ISNULL means the same everywhere. SQL Server fills; MySQL tests.

Interview Corner

What does COALESCE do?

It returns the first non-NULL argument from its list, or NULL if all are NULL. It's standard SQL and works in every major database.

How do you avoid a divide-by-zero error in SQL?

Wrap the divisor in NULLIF(divisor, 0), so a zero becomes NULL and the result is NULL instead of an error. Optionally wrap the result in COALESCE(..., 0).

What's the difference between COALESCE and ISNULL in SQL Server?

COALESCE is standard and takes any number of arguments; ISNULL is SQL Server's two-argument version, and it uses the first argument's type for the result.

Practice

Challenge: Show each student's first name and phone number, with '(none)' when there's no phone, sorted by student_id.

Show solution
SQL▶ Try it
SELECT first_name, coalesce(phone, '(none)') AS phone
FROM students
ORDER BY student_id;
Output
 first_name |     phone
------------+----------------
 Srihitha   | (415) 555-0142
 Advitha    | (415) 555-0178
 Navika     | (none)
(3 rows)

Navika has no phone, so she gets (none). The fallback is text, matching the phone column's type.

Quick check: NULL functions

3 questions
1Advitha has no email but has a phone. What does coalesce(email, phone, 'no contact') return for her?
2What does nullif(0, 0) return?
3Which is the safe way to divide fee_usd by students?

Key Takeaways

You want toWrite
Fill a gapcoalesce(method, 'Unknown')
Fall back through columnscoalesce(email, phone, 'no contact')
Clear a placeholdernullif(phone, '')
Divide safelyfee_usd / nullif(students, 0)

Was this tutorial helpful?

Lesson 50 of 115