Full answer
These three functions convert between NULL and real values.
COALESCE walks its arguments left to right and returns the first non-NULL one. A contact table where people may give a mobile, a home phone or neither:
CREATE TABLE contacts (name TEXT, mobile TEXT, home TEXT);
INSERT INTO contacts VALUES ('Ana','555-0101',NULL),('Ben',NULL,'555-0199'),('Chen',NULL,''),('Dara',NULL,NULL);SELECT name, COALESCE(mobile, home, 'no phone') AS best_phone FROM contacts ORDER BY name;| name | best_phone |
|---|---|
| Ana | 555-0101 |
| Ben | 555-0199 |
| Chen | '' |
| Dara | no phone |
IFNULL(a, b) is a two-argument shortcut in SQLite and MySQL, the same as COALESCE(a, b). SQL Server's version is ISNULL(a, b), and Oracle's is NVL(a, b). Prefer COALESCE in portable code.
SELECT name, IFNULL(mobile, 'no mobile') AS mobile FROM contacts ORDER BY name;| name | mobile |
|---|---|
| Ana | 555-0101 |
| Ben | no mobile |
| Chen | no mobile |
| Dara | no mobile |
NULLIF(a, b) goes the other way. If a = b it returns NULL, otherwise it returns a. Its classic use is cleaning values that mean "nothing" but were stored as something:
SELECT name,
COALESCE(mobile, home, 'no phone') AS without_nullif,
COALESCE(mobile, NULLIF(home, ''), 'no phone') AS with_nullif
FROM contacts
ORDER BY name;| name | without_nullif | with_nullif |
|---|---|---|
| Ana | 555-0101 | 555-0101 |
| Ben | 555-0199 | 555-0199 |
| Chen | '' | no phone |
| Dara | no phone | no phone |
Chen's empty home phone became NULL, so COALESCE could skip it. Without NULLIF, COALESCE('', 'no phone') returns the empty string, since an empty string is a value, not a NULL.
Another everyday use of NULLIF is guarding a division: total / NULLIF(count, 0) gives NULL instead of a division error when count is zero.
CREATE TABLE contacts (name TEXT, mobile TEXT, home TEXT);
INSERT INTO contacts VALUES ('Ana','555-0101',NULL),('Ben',NULL,'555-0199'),('Chen',NULL,''),('Dara',NULL,NULL);
SELECT name, COALESCE(mobile, home, 'no phone') AS best_phone FROM contacts ORDER BY name;
SELECT name, IFNULL(mobile, 'no mobile') AS mobile FROM contacts ORDER BY name;
SELECT name,
COALESCE(mobile, home, 'no phone') AS without_nullif,
COALESCE(mobile, NULLIF(home, ''), 'no phone') AS with_nullif
FROM contacts
ORDER BY name;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- COALESCE returns the first non-NULL argument and takes any number of arguments
- IFNULL, ISNULL and NVL are two-argument vendor versions
- NULLIF(a, b) returns NULL when a = b
- NULLIF(x, '') then COALESCE handles empty strings
Common mistakes
- Expecting COALESCE to skip empty strings
- Using vendor-specific ISNULL or NVL in code meant to be portable
Follow-ups
- How would you protect a percentage calculation from division by zero?
- Does COALESCE evaluate every argument?
Tips
- Pair NULLIF with COALESCE in your example to show both directions