SQL

IS DISTINCT FROM — Null-Safe Equality

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`=` returns NULL when either side is NULL. `IS DISTINCT FROM` (and its inverse `IS NOT DISTINCT FROM`) treat NULLs as equal to themselves — the right tool for change detection.
SQL
Raw
-- Find rows where the new value DIFFERS from the old value, treating both NULLs as equal
SELECT id, name, old_status, new_status
FROM   audit
WHERE  old_status IS DISTINCT FROM new_status;
-- old=NULL  new='active' → DIFFERENT
-- old='x'   new='x'      → SAME (excluded)
-- old=NULL  new=NULL     → SAME (excluded)

-- Equivalent without IS DISTINCT FROM — verbose, easy to get wrong
WHERE (old_status <> new_status) OR (old_status IS NULL) <> (new_status IS NULL);

-- Use in a MERGE / UPSERT: only update if values actually changed
UPDATE users SET name = $1, email = $2, updated_at = NOW()
WHERE  id = $3
   AND (name, email) IS DISTINCT FROM ($1, $2);

-- MySQL equivalent — the safe-equals operator <=>
SELECT * FROM audit WHERE NOT (old_status <=> new_status);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.