Sub topic 2
How WHERE, HAVING, and CASE Handle UNKNOWN
This chapter assumes you can write SELECT, WHERE, GROUP BY, and HAVING, and that you know the sample employees table from earlier chapters. Each comparison with NULL yields UNKNOWN, so this chapter shows what that result does in filters, expressions, and aggregates.
How WHERE, HAVING, and CASE Handle UNKNOWN
A WHERE clause keeps a row only when its condition is TRUE. FALSE and UNKNOWN both drop the row. HAVING applies the same rule to groups, and CASE takes a WHEN branch only when that branch is TRUE. An UNKNOWN condition falls through to the next WHEN or to ELSE.
SELECT name FROM employees WHERE commission > 100; -- returns Di only
SELECT name,
CASE WHEN commission > 100 THEN 'high'
ELSE 'low or unknown'
END AS band
FROM employees; -- Ada and Cy get 'low or unknown'NULL Propagation in Arithmetic and String Expressions
Any arithmetic operation with a NULL operand returns NULL. The same holds for most string concatenation in standard SQL, although some systems such as Oracle treat NULL differently in concatenation.
SELECT name, commission + 10 AS bumped
FROM employees; -- NULL for Ada and CyReplacing and Creating NULLs with COALESCE and NULLIF
COALESCE returns its first non-NULL argument. NULLIF returns NULL when its two arguments are equal, which lets you turn a sentinel value such as zero into NULL before dividing.
SELECT name, COALESCE(commission, 0) AS commission_or_zero
FROM employees;
SELECT 100 / NULLIF(0, 0) AS safe_ratio; -- NULL instead of a division errorAggregates and NULL: COUNT(*) vs COUNT(column), SUM, AVG
COUNT(*) counts rows. COUNT(column), SUM, and AVG skip NULL values. AVG divides by the number of non-NULL values, so replacing NULL with zero changes the result.
SELECT COUNT(*) AS all_rows, -- 4
COUNT(commission) AS with_commission, -- 2
SUM(commission) AS total, -- 400.00
AVG(commission) AS avg_non_null, -- 200.00
AVG(COALESCE(commission, 0)) AS avg_with_zeros -- 100.00
FROM employees;Exercise
How many rows does SELECT name FROM employees WHERE commission <> 100 return?
Show answer
One row, Di. Ada and Cy have NULL commission, so the comparison is UNKNOWN and both rows are dropped.