r/learnSQL • u/Goldziher • Aug 05 '26
Why LEFT JOIN columns are nullable (a subtle SQL gotcha that causes real bugs)
Something that trips up a lot of people learning SQL, worth internalizing early.
Given:
SELECT u.id, u.name, o.total
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;An INNER JOIN would only return users who have at least one order. A LEFT JOIN keeps every user, and for a user with no orders, every column from o (here o.total) comes back NULL.
So o.total is nullable even if the orders.total column is declared NOT NULL. The NOT NULL constraint is about what can be stored in the table. The LEFT JOIN can still produce a NULL for it in the result set, because the matching row on the right side does not exist at all.
This is the source of a lot of bugs: code assumes total is always a number, then crashes or silently mis-sums when it hits a user with no orders. The fix is to remember that nullability in a result set comes from the query structure (which joins, COALESCE, CASE, aggregates), not just from the table definition.
Rule of thumb: any column from the nullable side of an outer join is nullable in your results. Handle it explicitly, e.g. COALESCE(o.total, 0) if zero is the right default.
6
u/MrLyttleG Aug 05 '26
C’est pas parceque SQL semble simple qu'il est facile de ne pas se tromper. Avant de se lancer dans SQL il est primordial de maîtriser la partie fonctionnelle des données, la technique viendra se greffer en seconde position.
3
u/OldValariya1014 Aug 05 '26
Wait so in my case I use SQL for hospital data and a left join would crash the system, what would be the best solution to include Null values without running thru every single record? Outer apply?
3
u/orz-_-orz Aug 06 '26
Ermmm....
Isn't that what LEFT JOIN supposed to do?
If you want not null value then should use INNER JOIN
2
u/elevarq Aug 06 '26
You made the data from “orders” optional, you used a LEFT JOIN.
When this causes bugs in the rest of your system, these parts contain bugs: they should be able to handle NULL.
1
u/Far_Swordfish5729 Aug 05 '26
That’s not a gotcha. It’s how the language works. You don’t use outer joins unless you explicitly want the unmatched rows present, in which case null explicitly means something to you and you check for it in the application layer.
-1
u/Ok_Carpet_9510 Aug 05 '26
Yeah 1 + 1 =2.