// conditional reference

SQL NULL-safe joins

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

Categoría
Condicional
Returns
joined rows
In this category
30 of 43

Sintaxis

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

Soporte del motor

MotorSupportNotas
SQL Server Sí IS NOT DISTINCT FROM since SQL Server 2022; else COALESCE
PostgreSQL Sí IS NOT DISTINCT FROM
MySQL Sí <=>
SQLite Sí IS (or IS DISTINCT FROM since 3.39)
Oracle Different name or syntax DECODE(a.k, b.k, 1, 0) = 1

Ejemplos

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;

Conviene saberlo

  • 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.