sqlstreak

SQL function

NULLIF() in SQL: turn a value into NULL

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

NULLIF(a, b) returns NULL when a equals b, and a otherwise. Its two everyday uses: NULLIF(phone, '') turns blanks into real NULLs, and x / NULLIF(y, 0) gives NULL instead of a division-by-zero error.

Syntax and availability

PostgreSQLSQLite
AvailableYesYes
SyntaxNULLIF(value, value_to_treat_as_null)NULLIF(value, value_to_treat_as_null)

Examples

Blank phone numbers become NULL

SELECT id, phone AS raw, NULLIF(TRIM(phone), '') AS phone
FROM adoption_requests
ORDER BY id
LIMIT 6;

Result (PostgreSQL and SQLite, identical): 6 rows

idrawphone
1555-0101555-0101
2NULL
3NULLNULL
4555-0104555-0104
5555-0105555-0105
6NULL

Try it: PostgreSQL playground · SQLite playground

Then COUNT can skip them

SELECT COUNT(phone) AS counted_raw,
       COUNT(NULLIF(TRIM(phone), '')) AS real_phones
FROM adoption_requests;

Result (PostgreSQL and SQLite, identical): 1 row

counted_rawreal_phones
107

Try it: PostgreSQL playground · SQLite playground

Safe division

SELECT source,
       COUNT(*) AS users,
       ROUND(1.0 * SUM(CASE WHEN u.id IN (SELECT user_id FROM subscriptions) THEN 1 ELSE 0 END)
             / NULLIF(COUNT(*), 0), 3) AS conversion
FROM users u
GROUP BY source
ORDER BY source;

Result (PostgreSQL and SQLite, identical): 4 rows

sourceusersconversion
ad570.316
friend910.429
podcast550.255
search970.299

Try it: PostgreSQL playground · SQLite playground

How it behaves: edge cases, measured

Each expression was run as SELECT … on PostgreSQL 18.6 and SQLite 3.54.1 when this page was built. Nothing here is typed by hand.

CasePostgreSQLSQLite
Equal: NULLNULLIF(5, 5)NULLNULLIF(5, 5)NULL
Not equal: the first valueNULLIF(5, 0)5NULLIF(5, 0)5
Blank textNULLIF('', '')NULLNULLIF('', '')NULL
Dividing by NULLIF(0, 0)10 / NULLIF(0, 0)NULL10 / NULLIF(0, 0)NULL
Case mattersNULLIF('a', 'A')'a'NULLIF('a', 'A')'a'
NULL firstNULLIF(NULL, 1)NULLNULLIF(NULL, 1)NULL
Number vs textNULLIF(1, '1')NULLNULLIF(1, '1')1

Common mistakes

  • Swapping the arguments: NULLIF('', phone) returns '' or NULL, never the phone.

  • Forgetting TRIM: NULLIF(phone, '') leaves ' ' alone.

  • Expecting NULLIF to replace NULLs: that's COALESCE's job; the two are often used together.

PostgreSQL and SQLite

Standard and the same in both for same-type values. With a number and text, SQLite compares them as different types and keeps the number, while PostgreSQL first converts the text to a number (see the matrix).

Official documentation

Go deeper

Make it stick in five minutes a day

“Empty, NULL and defaults” teaches this step by step on a real database, with instant feedback. Part of sqlstreak Pro; the first lessons are free.

Start free