# NULLIF() in SQL: turn a value into NULL

Source: https://sqlstreak.com/sql/functions/nullif · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**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

- PostgreSQL: `NULLIF(value, value_to_treat_as_null)` (Yes)
- SQLite: `NULLIF(value, value_to_treat_as_null)` (Yes)

## Examples

### Blank phone numbers become NULL

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

Result (both engines):

| id | raw | phone |
| --- | --- | --- |
| 1 | 555-0101 | 555-0101 |
| 2 |  | NULL |
| 3 | NULL | NULL |
| 4 | 555-0104 | 555-0104 |
| 5 | 555-0105 | 555-0105 |
| 6 |  | NULL |

### Then COUNT can skip them

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

Result (both engines):

| counted_raw | real_phones |
| --- | --- |
| 10 | 7 |

### Safe division

```sql
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 (both engines):

| source | users | conversion |
| --- | --- | --- |
| ad | 57 | 0.316 |
| friend | 91 | 0.429 |
| podcast | 55 | 0.255 |
| search | 97 | 0.299 |

## Edge cases, measured on both engines

| Case | PostgreSQL | SQLite |
| --- | --- | --- |
| Equal: NULL | NULL | NULL |
| Not equal: the first value | 5 | 5 |
| Blank text | NULL | NULL |
| Dividing by NULLIF(0, 0) | NULL | NULL |
| Case matters | 'a' | 'a' |
| NULL first | NULL | NULL |
| Number vs text | NULL | 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.
