// conditional reference

SQL NULL-safe joins

Join patterns for keys that can be NULL on either side.

类别
条件
Returns
joined rows
In this category
30 of 43

语法

ON a.k IS NOT DISTINCT FROM b.k | ON a.k <=> b.k | ON COALESCE(a.k, -1) = COALESCE(b.k, -1)

引擎支持

引擎Support备注
SQL Server 是 IS NOT DISTINCT FROM since SQL Server 2022; else COALESCE
PostgreSQL 是 IS NOT DISTINCT FROM
MySQL 是 <=>
SQLite 是 IS (or IS DISTINCT FROM since 3.39)
Oracle Different name or syntax DECODE(a.k, b.k, 1, 0) = 1

示例

PostgreSQL

SELECT * FROM a JOIN b ON a.k IS NOT DISTINCT FROM b.k;

MySQL

SELECT * FROM a JOIN b ON a.k <=> b.k;

Oracle

SELECT * FROM a JOIN b ON DECODE(a.k, b.k, 1, 0) = 1;

值得了解

  • ON a.k = b.k never matches NULL keys: NULL = NULL is UNKNOWN, and joins keep only TRUE rows. That is the relational definition of match.
  • COALESCE(a.k, sentinel) = COALESCE(b.k, sentinel) is the classic fix but collides when a real key equals the sentinel.
  • Decide the semantics first: usually a NULL key means 'no relationship' and dropping those rows is correct; these recipes are for when NULL means the same unknown value.

Questions about JOIN

Why do NULL keys never join?

Equality with NULL is UNKNOWN and joins keep only TRUE rows; matching NULLs needs a null-safe predicate.

Is COALESCE on join keys safe?

Only if the sentinel cannot be a real key value; IS NOT DISTINCT FROM or <=> avoids the collision entirely.

Does this affect performance?

Null-safe predicates can defeat index seeks on some engines; measure, or add a computed nullable-key column.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.