// conditional reference

SQL NULL-safe equality

Equality tests that report TRUE or FALSE even when NULLs are involved.

Categoría
Condicional
Returns
boolean
In this category
29 of 43

Sintaxis

a <=> b | a IS NOT DISTINCT FROM b | a IS b

Soporte del motor

MotorSupportNotas
SQL Server Sí IS NOT DISTINCT FROM since SQL Server 2022
PostgreSQL Sí IS NOT DISTINCT FROM
MySQL Sí <=> operator
SQLite Sí IS / IS NOT
Oracle Different name or syntax no operator; DECODE(a, b, 1, 0) = 1

Ejemplos

MySQL

SELECT 1 <=> 1 AS t, NULL <=> NULL AS t2, NULL <=> 1 AS f;

SQLite

SELECT NULL IS NULL AS t, NULL IS 1 AS f;

PostgreSQL

SELECT NULL IS NOT DISTINCT FROM NULL AS t;

Conviene saberlo

  • Plain = returns UNKNOWN when either side is NULL; the null-safe forms return a definite TRUE or FALSE.
  • The portable recipe on engines with none of the syntax: EXISTS (SELECT a INTERSECT SELECT b), since INTERSECT treats NULLs as equal. Oracle needs FROM dual on both halves.
  • Oracle's DECODE(a, b, 1, 0) = 1 works because DECODE, unlike CASE, treats two NULLs as equal.
  • MySQL's <=> returns 1/0 including NULL pairs; SQLite's IS does the same as a wordier operator.

Questions about NULL-safe

How do I test NULL = NULL?

You cannot with =; use IS NULL on both sides, <=> in MySQL, IS in SQLite or IS NOT DISTINCT FROM.

What works on every engine?

EXISTS (SELECT a INTERSECT SELECT b): INTERSECT defines NULLs as equal by standard.

Why does DECODE help in Oracle?

DECODE's NULL-equality rule: two NULL arguments compare equal, unlike CASE expressions.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

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