Free courses in AI, Data Science & Machine Learning Written lessons · Quizzes · Final exams
Future Data Academy
Log inGet started ↗
← SQL learning path
Intermediate · SQLITE

JOINs and relationship grain

Avoid multiplying your metrics.

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

  1. Orders with names — Return order_id and name for every order, ordered by order_id.
  2. Include non-buyers — Return name and order_count for every customer, including zero, ordered by customer id.
  3. Never ordered — Return name for customers with no orders, ordered by customer id.
  4. Revenue by country — Return country and revenue for paid orders, ordered by country.
  5. Manager names — Return employee and manager names for employees with a manager, ordered by employee id.
  6. Keep senior employees — Return employee and manager (NULL if absent) for all employees, ordered by employee id.
  7. Paid orders including zero — Return name and paid_orders for all customers, including zero, ordered by customer id.
  8. Customer pairs — Return first_name and second_name for same-country pairs once (first id smaller), ordered by both ids.
  9. Team size — Return manager and reports for managers with direct reports, ordered by manager id.
  10. 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.