Reason about SQL result shapes
Use joins and anti-joins without losing rows or multiplying totals.
Start with the desired row
State whether the result should contain one row per customer, order, or line item. A join to a one-to-many table multiplies parent rows; a later SUM may then count the same amount more than once. Build a tiny example with two customers and several orders before optimizing.
Find missing relationships safely
To find customers with no orders, a NOT EXISTS condition expresses the requirement directly. A LEFT JOIN with an `orders.id IS NULL` filter can also work, but predicates in the WHERE clause can accidentally turn the outer join into an inner join. Check the empty and multi-match cases.
SELECT c.id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.id
);
Protect the execution plan
Parameterized values prevent SQL injection; they do not fix a slow query. Index the foreign key used by the lookup, inspect an explain plan on realistic data, and paginate large results. Keep query semantics correct first. An index that speeds the wrong result is no improvement.
Check your understanding
Why can joining orders before summing a customer's balance inflate a result?
Show explanation
A one-to-many join repeats the customer row for each order. Aggregate at the right grain or use a separate subquery.
You can read for free. Create an account to save your progress.
← Previous lesson: Use small objects to protect invariants Next lesson: Page large results with the right index →Put this lesson into practice
A practice activity at this level in the same module.
Try: Diagnose and remove an N+1 queryFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.