SQL and data modelling · Chapter 2
NULL, three-valued logic and grouping
About this chapter
A missing value in a table is not a zero and not an empty string: it is something the database was never told, so SQL treats every test on it as unknown. This chapter follows that one idea through the places where it surprises people: filters that drop rows, comparisons that never match, groups that gather the missing values together, averages and counts that skip them, and where rows with no value land when you sort.
Who it is for: Anyone learning SQL who has been surprised by a missing row, a total that looks too low, or an average that does not match what they expected.
You will be able to
- Explain why comparing a column with NULL never matches, and write the filter that does.
- Predict which rows a filter keeps when some values are missing, including when the filter is negated.
- Say what a count, a sum and an average do with missing values, and choose the count that fits the question.
- Decide where rows with no value appear in a sorted result, instead of relying on an engine's default.
- Choose between showing a stand-in for a missing value and leaving it missing in a calculation.
The key idea: A missing value is not a hidden zero. SQL will not guess it, so any test that depends on it comes out unknown, and a filter keeps only the rows whose test is true. A row can therefore be absent from a condition and from its opposite, which means a query about missing data has to say what should happen to those rows.
In this chapter
- NULL is not zero, not empty and not false
- Three-valued logic: TRUE, FALSE and UNKNOWN
- NULL in joins, aggregates, GROUP BY and sorting
- COALESCE and NULLIF
- GROUP BY and aggregate functions
Locked: needs a plan
You can read chapter 1 free. Chapter 2 is the next one.
What you can do now, free: re-read chapter 1 and try its problems.
What a plan gives you: all chapters of the track you pick and their checks. Starter is ₹229 a month or ₹1,699 a year. It renews until you cancel, and you can cancel any time. Paid plans open at launch.
Why is this locked?
Chapter 1 of every track is free, so you can see how the track reads. The rest of a track and its checks come with a plan, or open as you pass each chapter's check.
The price is for one period, a month or a year. A plan renews until you cancel.