by wireprotocol · 6y ago · 0 comments
-- Find all customers with total orders
-- less than $100 in 2019
SELECT c.name
FROM customers c LEFT JOIN orders o
ON (c.id = o.customer_id)
WHERE DATE_TRUNC('year', o.ts) = '2019-01-01'::timestamptz
GROUP BY c.name
HAVING SUM(o.price) < 100;
Can you find the problem?[ SPOILER ]
The problem is if there is a customer with no orders. The left join will produce NULLs for the attributes of "orders", and SUM() will sum them up to NULL because it thinks NULL means "nothing". The predicate "NULL < 100" will then think the NULL means "unknown" and produce the result "unknown". Then, the HAVING clause treats NULL like FALSE, and does not produce the row.
So if you don't start out with any NULLs, and you have complete and unambiguous knowledge of your entire data set, how does "unknown" get injected into such an innocent-looking example?
If a JOIN could somehow return hierarchically structured data then there would've been no gotchas here.
But yes, I think left join is fundamentally about grouping, and grouping would be better solved with set-valued attributes or relation-valued attributes.
I wouldn't call that "hierarchically-structured data" because that has the connotation that the data is actually stored in a hierarchy, which I think is generally a bad idea (though not always).
So in your case I'd do
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE c.id = o.customer_id
AND DATE_TRUNC('year', o.ts) = '2019-01-01'::timestamptz
HAVING SUM(o.price) < 100
)
Again, might be dumb, but I usually find it easier to think in terms of subqueries rather than joins. Not that I find joining hard per se, just feels more natural and to the point to use subqueries. Database I use also seems to optimize it better most of the time.Could just modify it to exclude the orders above 100 ("where not exists"...), no?
Edit: just read what you said was wrong with it, and realized you missed the one in the where clause.
Like you said, really hammers home how hard to deal with null is with properly all the time.
WHERE DATE_TRUNC('year', o.ts) = '2019-01-01'::timestamptz
will filter out customers without orders even before the HAVING (because DATE_TRUNC of NULL is NULL)? I mean, I guess you're still demonstrating the perils of NULL with that ;) WHERE EXTRACT(YEAR FROM o.ts) = 2019
...though I imagine some people dislike the way EXTRACT treats words like YEAR as keywords. Always interesting to see which solution people choose when there are several options. :)A language should help you avoid making mistakes, not trick you into making them. The path of least resistance should be the safest and most normal thing, and SQL fails here.
But saying SQL is tricking people into making mistakes? Nah. The real issue seems to be writing a query without a proper understanding of NULL, not being tricked by the language.