Understand the concept
If a customer has three orders, that customer appears three times in a join. Another one-to-many table can multiply orders again. Aggregate each fact table to its intended grain before combining totals.
Apply the method
INNER JOIN drops unmatched records; LEFT JOIN preserves the left side. Count the right-side primary key to obtain zero for unmatched rows. COUNT(*) would count the placeholder. Put the right-side status filter in ON when non-buyers must remain.
Avoid a common mistake
Self-joins use aliases such as employee and manager. Pairing records needs a rule such as a.id < b.id to avoid both A–B and B–A. Test a record with no match and one with multiple matches before trusting totals.
Worked query
Return order_id and name for every order, ordered by order_id.
SELECT o.id AS order_id,c.name FROM orders o JOIN customers c ON c.id=o.customer_id ORDER BY o.id;Run and explore this example →Check your understanding
Before running your query, predict the output columns and approximate row count. After running it, inspect a missing value, a tie and a record with no match when available. Explain why the result answers the question.
Practice this topic
- Orders with names — Return order_id and name for every order, ordered by order_id.
- Include non-buyers — Return name and order_count for every customer, including zero, ordered by customer id.
- Never ordered — Return name for customers with no orders, ordered by customer id.
- Revenue by country — Return country and revenue for paid orders, ordered by country.
- Manager names — Return employee and manager names for employees with a manager, ordered by employee id.
- Keep senior employees — Return employee and manager (NULL if absent) for all employees, ordered by employee id.
- Paid orders including zero — Return name and paid_orders for all customers, including zero, ordered by customer id.
- Customer pairs — Return first_name and second_name for same-country pairs once (first id smaller), ordered by both ids.
- Team size — Return manager and reports for managers with direct reports, ordered by manager id.
- Complete spend table — Return name and revenue for all customers; use 0 when no paid revenue exists. Order by customer id.
SQLite reference: SQL language documentation. Written by Future Data Academy with AI assistance; query examples checked against the supplied teaching dataset.
