← Back to PostgreSQL, page 1

postgresql-0004 · Easy fresher

How do NULLs behave in comparisons, and how do COALESCE, NULLIF and IS DISTINCT FROM help?

Any comparison with NULL using = or <> yields NULL, so WHERE treats it as false. IS NULL and IS DISTINCT FROM compare NULL safely. COALESCE returns the first non-null argument, and NULLIF(a, b) returns NULL when a equals b, which is handy to avoid division by zero.

Full answer

Schema and sample rows:

sql
CREATE TABLE contacts (name text, phone text, discount int, orders int);
INSERT INTO contacts VALUES
  ('Asha', '98450', 10, 4),
  ('Ben',  NULL,    NULL, 0),
  ('Chen', '',      0, 2);
sql
SELECT name FROM contacts WHERE phone <> '98450' ORDER BY name;

Result:

text
 name
------
 Chen
(1 row)
sql
SELECT name FROM contacts WHERE phone IS DISTINCT FROM '98450' ORDER BY name;

Output:

text
 name
------
 Ben
 Chen
(2 rows)
sql
SELECT name, COALESCE(NULLIF(phone, ''), 'no phone') AS phone, COALESCE(discount, 0) AS discount, 100 / NULLIF(orders, 0) AS per_order FROM contacts ORDER BY name;

PostgreSQL returns:

text
 name |  phone   | discount | per_order
------+----------+----------+-----------
 Asha | 98450    | 10       | 25
 Ben  | no phone | 0        | NULL
 Chen | no phone | 0        | 50
(3 rows)

The first query misses Ben, because NULL <> '98450' is NULL rather than true. IS DISTINCT FROM treats NULL as a comparable value and returns both Ben and Chen. In the last query, NULLIF turns Chen's empty string into NULL so COALESCE can supply a label for both missing phones, and NULLIF(orders, 0) makes Ben's division return NULL instead of raising 'division by zero'. Storing either NULL or empty strings for missing values, not both, avoids needing the NULLIF in the first place.

sql
CREATE TABLE contacts (name text, phone text, discount int, orders int);
INSERT INTO contacts VALUES
  ('Asha', '98450', 10, 4),
  ('Ben',  NULL,    NULL, 0),
  ('Chen', '',      0, 2);

SELECT name FROM contacts WHERE phone <> '98450' ORDER BY name;

SELECT name FROM contacts WHERE phone IS DISTINCT FROM '98450' ORDER BY name;

SELECT name, COALESCE(NULLIF(phone, ''), 'no phone') AS phone, COALESCE(discount, 0) AS discount, 100 / NULLIF(orders, 0) AS per_order FROM contacts ORDER BY name;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • = and <> with NULL give NULL
  • WHERE drops NULL results
  • IS DISTINCT FROM is null-safe
  • COALESCE supplies defaults
  • NULLIF avoids division by zero

Common mistakes

  • Writing = NULL
  • Mixing empty strings and NULL for missing data

Follow-ups

  • How do NULLs sort by default in PostgreSQL?
  • How does COUNT(col) treat NULLs?

Tips

  • Show the missing row