COUNT(x), SUM and AVG skip NULLs, and an empty SUM needs care
Aggregates are the third place NULL bites.
Predict
A city has no orders. What does SUM(total_cents) give for it after a LEFT JOIN?
COUNT(x), SUM and AVG skip NULL inputs. That's usually what you want, and sometimes it isn't. An average rating over the orders that have a rating isn't an average over all orders, and the question decides which one you need.
With no non-NULL input at all, SUM returns NULL, not 0. PostgreSQL's manual warns about exactly this.
SELECT SUM(total_cents) AS sum_cents, COALESCE(SUM(total_cents), 0) AS or_zero, COUNT(*) AS order_rowsFROM ordersWHERE promo = 'WELCOME';
sum_cents
or_zero
order_rows
NULL
0
0
That's why a LEFT JOIN's empty groups need COALESCE. A city with no orders gets NULL revenue, and the report shows a blank where the question wanted a 0.
In the editor, fix SPEND: every customer's spend, with Dee's 0.
Pick an answer above to see the rest
Instructions
1
Asked for every customer's total spend in cents, 0 for none, an assistant wrote SPEND, and Dee shows NULL. Fix it.