Skip to main content
Intermediatecomparison

Name three ways NULL breaks queries.

Source: PostgreSQL: SELECT (clause processing)

Quick answer

= NULL never matches (use IS NULL); NOT IN with a NULL in the subquery returns no rows; aggregates ignore NULLs, so COUNT(col) and AVG(col) differ from what people expect; NULL in arithmetic or concatenation produces NULL; a WHERE filter on the right side of a LEFT JOIN removes the NULL-extended rows.

= NULL never matches (use IS NULL); NOT IN with a NULL in the subquery returns no rows; aggregates ignore NULLs, so COUNT(col) and AVG(col) differ from what people expect; NULL in arithmetic or concatenation produces NULL; a WHERE filter on the right side of a LEFT JOIN removes the NULL-extended rows.

Animated explanation

Comparisons

  • = NULL never matches: use IS NULL
  • NOT IN with a NULL returns no rows

Aggregates and arithmetic

  • COUNT(col) and AVG(col) skip NULLs
  • NULL in arithmetic gives NULL

LEFT JOIN

  • A WHERE filter on the right side
  • removes the NULL-extended rows
Three-valued logic: NULL is not equal, not unequal, just unknown.
See the concept: Join fan-outWhy a join to a one-to-many table multiplies sums
Join fan-out
order_lines: one row per line
O101line 1₹300
payments: one row per attempt
O101P101FAILED
O101P102SUCCESS
lines JOIN payments ON order_id
line 1P101₹300
line 1P102₹300
SUM(line_revenue)₹600

Wrong: the single ₹300 line is counted once per payment attempt.

Fix: aggregate payments to one row per order first

line 1, paid, ₹300, so SUM = ₹300

One order line, two payment attempts: a direct join doubles the revenue. Aggregating payments to order grain first keeps one row per line.

Key points

  • three-valued logic
  • NOT IN
  • COUNT(*) vs COUNT(col)
  • COALESCE

References

Discussion