SQL and data modeling

5 concepts · 10 practice questions

Join traps: fan-out and NULLs

Joining a one-to-many table repeats the parent row once per child, so summing a parent column after the join double counts (fan-out). Aggregate the many side to one row per key first, then join. A LEFT JOIN with a WHERE filter on the right table quietly becomes an inner join; put that filter in the ON clause. NULL never equals anything, NULL included, so NULL keys never match, and NOT IN against a subquery that returns a NULL yields no rows at all; use NOT EXISTS.

-- Wrong: each order total repeats once per shipment
SELECT o.customer_id, sum(o.total)
FROM orders o JOIN shipments s ON s.order_id = o.order_id
GROUP BY o.customer_id;

-- Right: reduce the many side first, then join
WITH ship AS (
  SELECT order_id, count(*) AS shipments
  FROM shipments GROUP BY order_id
)
SELECT o.customer_id,
       sum(o.total) AS revenue,
       sum(coalesce(s.shipments, 0)) AS shipments
FROM orders o LEFT JOIN ship s ON s.order_id = o.order_id
GROUP BY o.customer_id;

Also covered

Window functions
Modeling for analytics vs operations
Slowly changing dimensions
Query performance on customer databases

Sign in to read the rest and take the 10-question test.

Sign in to continue