Full answer
A sync job compares the city stored in two systems to find changed rows. Some cities are missing in both.
CREATE TABLE city_sync (id INTEGER PRIMARY KEY, old_city TEXT, new_city TEXT);
INSERT INTO city_sync VALUES (1,'Pune','Pune'),(2,'Pune','Delhi'),(3,NULL,'Leeds'),(4,NULL,NULL);SELECT id, old_city, new_city, old_city <> new_city AS changed_plain
FROM city_sync ORDER BY id;| id | old_city | new_city | changed_plain |
|---|---|---|---|
| 1 | Pune | Pune | 0 |
| 2 | Pune | Delhi | 1 |
| 3 | NULL | Leeds | NULL |
| 4 | NULL | NULL | NULL |
With <>, a pair where one side is NULL produces UNKNOWN, so the change from NULL to 'Leeds' is not reported. A pair where both are NULL is also UNKNOWN rather than "same".
The null-safe operator fixes both cases:
SELECT id, old_city, new_city,
old_city IS DISTINCT FROM new_city AS changed
FROM city_sync ORDER BY id;| id | old_city | new_city | changed |
|---|---|---|---|
| 1 | Pune | Pune | 0 |
| 2 | Pune | Delhi | 1 |
| 3 | NULL | Leeds | 1 |
| 4 | NULL | NULL | 0 |
IS DISTINCT FROM returns TRUE when the values differ (including NULL versus a value) and FALSE when they are the same (including NULL versus NULL). It never returns UNKNOWN. PostgreSQL supports it, and SQLite has accepted it since 3.39. SQLite's own shorter form a IS NOT b means the same thing.
PostgreSQL agrees:
SELECT id, old_city IS DISTINCT FROM new_city AS changed FROM city_sync ORDER BY id;| id | changed |
|---|---|
| 1 | false |
| 2 | true |
| 3 | true |
| 4 | false |
MySQL spells null-safe equality as a <=> b (from its documentation, not run here).
A caution for joins: on PostgreSQL, IS NOT DISTINCT FROM as a join condition generally cannot use a plain B-tree index the way = can. For change detection over a whole table that rarely matters; for joins on large tables, check the plan.
CREATE TABLE city_sync (id INTEGER PRIMARY KEY, old_city TEXT, new_city TEXT);
INSERT INTO city_sync VALUES (1,'Pune','Pune'),(2,'Pune','Delhi'),(3,NULL,'Leeds'),(4,NULL,NULL);
SELECT id, old_city, new_city, old_city <> new_city AS changed_plain
FROM city_sync ORDER BY id;
SELECT id, old_city, new_city,
old_city IS DISTINCT FROM new_city AS changed
FROM city_sync ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- = and <> return UNKNOWN when either side is NULL
- IS DISTINCT FROM treats NULL as a comparable value
- SQLite also has IS and IS NOT; MySQL has <=>
- Useful for change detection between nullable columns
Common mistakes
- Missing a change from NULL to a value because <> returned UNKNOWN
- Writing (a <> b OR a IS NULL OR b IS NULL), which reports NULL versus NULL as a change
Follow-ups
- How would you write the same comparison on an engine without IS DISTINCT FROM?
- Can IS NOT DISTINCT FROM use an index?
Tips
- Use the change-detection example; it is where this operator matters most