NULL and Three-Valued Logic

NULL means "no value" or "unknown". It differs from 0 and from the empty string. A comparison with NULL is neither true nor false but UNKNOWN, and since WHERE keeps only true rows, unknown rows are dropped.

The examples create NULLs with NULLIF(region, 'SEOUL'). If the region is SEOUL, it is NULL; otherwise it is the original value.

= NULL finds nothing

= NULL vs IS NULL

SELECT
  COUNT(CASE WHEN NULLIF(region, 'SEOUL') = NULL THEN 1 END) AS eq_null,
  COUNT(CASE WHEN NULLIF(region, 'SEOUL') IS NULL THEN 1 END) AS is_null
FROM customers

x = NULL is unknown whatever x is. To test for NULL, use IS NULL and IS NOT NULL.

Three-valued logic table

ABA AND BA OR B
TrueUnknownUnknownTrue
FalseUnknownFalseUnknown
UnknownUnknownUnknownUnknown

NOT unknown is also unknown. So even when you invert a condition with NOT, NULL rows fall on neither side.

A condition, its negation, and rows in neither

SELECT
  COUNT(CASE WHEN NULLIF(region, 'SEOUL') = 'BUSAN' THEN 1 END)       AS is_busan,
  COUNT(CASE WHEN NOT (NULLIF(region, 'SEOUL') = 'BUSAN') THEN 1 END) AS not_busan,
  COUNT(*)                                                            AS total
FROM customers

is_busan + not_busan is less than total. The difference is the NULL rows (Seoul customers).

NOT IN and NULL

a NOT IN (x, y, NULL) is a <> x AND a <> y AND a <> NULL. The last term is always unknown, so the whole can never be true.

NOT IN with a NULL in the list

SELECT cust_id
FROM customers
WHERE cust_id <= 5
  AND cust_id NOT IN (2, 3, NULL)

The result is 0 rows. Remove NULL and run it again to get 1, 4, 5. If a subquery result may contain NULLs, use NOT EXISTS (Subqueries).

Aggregate functions and NULL

COUNT(*) counts rows; COUNT(expr) counts rows where the expression is not NULL. SUM, AVG, MIN, and MAX also skip NULLs.

COUNT(*) vs COUNT(expr)

SELECT COUNT(*)                        AS all_rows,
       COUNT(NULLIF(region, 'SEOUL'))  AS non_null,
       COUNT(DISTINCT region)          AS regions
FROM customers

COALESCE and NULLIF

FunctionResult
COALESCE(a, b, …)The first non-NULL value. NULL if all are NULL
NULLIF(a, b)NULL if a = b, otherwise a

Replacing NULL with another value

SELECT cust_id,
       NULLIF(region, 'SEOUL')                       AS region_or_null,
       COALESCE(NULLIF(region, 'SEOUL'), '(NONE)')    AS region_label
FROM customers
WHERE cust_id <= 10
ORDER BY cust_id

NULLIF also avoids division by zero: amt / NULLIF(qty, 0) is NULL instead of an error when qty is 0.

Oracle: the empty string is NULL

Oracle stores and treats the zero-length string '' as NULL. In the standard, PostgreSQL, and SQL Server, '' is a non-NULL value. Run the same query while switching DBs.

Comparing with the empty string

SELECT COUNT(*) AS cnt
FROM customers
WHERE cust_nm <> ''

PostgreSQL and SQL Server return 100,000 rows; Oracle returns 0. In Oracle, cust_nm <> '' is the same as cust_nm <> NULL and is always unknown.