SQL.How can you compare two nullable values safely, and how does IS DISTINCT FROM differ from <>?

`<>` returns **UNKNOWN** if either value is `NULL`.

`IS DISTINCT FROM` provides a NULL-safe comparison: it always returns **TRUE or FALSE**, treating two NULLs as equal and one NULL as different from a non-NULL value.

| Comparison | `a <> b` | `a IS DISTINCT FROM b` |
|---|---|---|
| `5`, `5` | FALSE | FALSE |
| `5`, `10` | TRUE | TRUE |
| `5`, `NULL` | UNKNOWN | TRUE |
| `NULL`, `NULL` | UNKNOWN | FALSE |

```sql
WHERE old_value IS DISTINCT FROM new_value
-- Detects changes, including transitions to or from NULL
```

For NULL-safe equality, use the opposite:

```sql
WHERE a IS NOT DISTINCT FROM b
-- TRUE when values are equal or both NULL
```

**Interview answer:** “Unlike <>, IS DISTINCT FROM always returns TRUE or FALSE, even with NULLs. It treats two NULLs as equal, making it useful for reliably detecting changes between nullable values.”
This entry was posted in Без рубрики. Bookmark the permalink.