SQL Kitchen

Lesson · Recipe № 010

NULL

Lesson 10
Recipe

NULL


A LEFT JOIN keeps every row from the first table even when nothing matches on the second. Where nothing matches, SQL doesn't leave the cell blank or put in a zero: it fills it with NULL, SQL's word for “nothing recorded here.”

Query

SELECT st.name, s.section
FROM staff st
LEFT JOIN stations s ON st.name = s.lead;

↓ result

st.name       s.section
Giorgos       hot
Yannick       cold
Sofia         cold
Dan           hot
Konstantinos  NULL
Eleni         NULL
Marina        NULL

You can't filter for NULL with = NULL: to SQL, nothing ever “equals” nothing, so that comparison silently matches zero rows. Use IS NULL instead, or IS NOT NULL for the opposite.

Query

SELECT st.name
FROM staff st
LEFT JOIN stations s ON st.name = s.lead
WHERE s.section IS NULL;

↓ result

st.name
Konstantinos
Eleni
Marina

NULL printed on a real docket looks like a bug, not an answer. COALESCE swaps it for a fallback value you choose, and leaves anything that isn't NULL exactly as it was.

Query

SELECT st.name, COALESCE(s.section, 'Not assigned') AS section
FROM staff st
LEFT JOIN stations s ON st.name = s.lead
ORDER BY st.name;

↓ result

st.name       section
Dan           hot
Eleni         Not assigned
Giorgos       hot
Konstantinos  Not assigned
Marina        Not assigned
Sofia         cold
Yannick       cold

One more habit worth knowing: COUNT(*) counts every row, but COUNT(some_column) only counts the rows where that column isn't NULL. Here that difference is the whole answer: 4 staff are assigned to a station, and 3 aren't, all from one join.

On the rail · tonight's orders

ORDER 028

for Eleni


Eleni wants to know which staff members aren't currently leading any station.

Your query returns

The name of every staff member with no matching station, alphabetically.


ORDER 029

for Marina


Marina's printing a staff list and doesn't want blank cells for people who don't lead a station.

Your query returns

Every staff member's name and the section they lead, showing 'Not assigned' instead of a blank where there isn't one.


ORDER 030

for Eleni


Eleni's trying to figure out if the kitchen is short on leadership or just top-heavy with cooks who don't lead anything. She wants a quick headcount: how many staff lead a station, and how many don't.

Your query returns

Two numbers in one row: how many staff are assigned to a station, and how many aren't.