Lab 06 — JOINs: Combining Tables
The most powerful concept in SQL. Link customers, orders, and products together into one result set.
📖 Concept Recap: JOINs
- INNER JOIN returns only rows where a match exists in both tables.
- LEFT JOIN returns all rows from the left table plus matched rows from the right. Unmatched right-side columns are NULL.
- ON specifies the join condition:
ON orders.customer_id = customers.id - Use table aliases (
o,p,c) to keep queries readable:FROM orders o - Prefix ambiguous columns with the alias:
o.idvsc.namevsp.name - You can chain multiple JOIN clauses to link three or more tables.
👀 Worked Example (read-only)
Full order history joining all three tables at once.
SELECT o.id AS order_id,
c.name AS customer,
c.city,
p.name AS product,
p.category,
o.quantity,
o.total,
o.order_date
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
INNER JOIN products p ON o.product_id = p.id
ORDER BY o.order_date;
Exercise 1 — Basic INNER JOIN
Show each order with the customer name and product name. Fill in the blanks: the correct column names and JOIN conditions.
o = orders alias, c = customers alias, p = products alias. The linking columns are customer_id and product_id.Exercise 2 — LEFT JOIN: All Customers Including Those with No Orders
Show all customers with their total amount spent. Customers who have never placed an order should appear with 0 total (use COALESCE). Sort by total spent descending.
FROM customers c LEFT JOIN orders o ON c.id = o.customer_id, then GROUP BY and use COALESCE(SUM(o.total), 0).Exercise 3 — Products That Have Never Been Ordered
Use a LEFT JOIN from products to orders, then filter WHERE orders.id IS NULL to find products with no order history. These are dead-stock items.
FROM products p LEFT JOIN orders o ON p.id = o.product_id WHERE o.id IS NULLMini Project — Complete Order Intelligence Report
As a business analyst, write 4 JOIN queries to understand purchasing behaviour fully:
- Full order history: order ID, customer name, product name, category, quantity, total, date.
- Customer purchase summary: name, city, number of orders, total spent — sorted by total DESC.
- Product popularity: product name, category, times ordered, total quantity sold.
- Which customers bought which categories: customer name, category, total spent in that category.
🏁 Lab 06 Complete!
You can now combine multiple tables using INNER JOIN and LEFT JOIN, use table aliases, and find rows with no matching records using the IS NULL trick.
Next up: queries inside queries.
Continue to Lab 07 — Subqueries →