CHAPTER 18
Aggregating by category — the analytics workhorse.
Customer names, order dates, and product names in each order
SELECT c.name AS customer, o.order_date, p.name AS product, oi.qty, oi.unit_price FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN order_items oi ON o.order_id = oi.order_id JOIN products p ON oi.product_id = p.product_id ORDER BY o.order_date, c.name;
✅ Pro Tips: Always use short, meaningful table aliases (c for customers, o for orders, p for products). Avoid single letters where they are ambiguous. In a 6-table JOIN, good aliases are the difference between readable code and maintenance hell.
| order_id | customer_id | order_date | total | status |
|---|---|---|---|---|
| 1 | 1 | 2024-01-15 | 79999 | completed |
| 2 | 2 | 2024-01-20 | 3498 | completed |
| 3 | 1 | 2024-02-10 | 65000 | completed |
| 4 | 3 | 2024-02-14 | 499 | pending |
| 5 | 2 | 2024-03-01 | 248 | completed |
| 6 | 5 | 2024-03-15 | 2999 | shipped |
| 7 | 1 | 2024-04-05 | 149 | completed |
| customer_id | name | city | country |
|---|---|---|---|
| 1 | Ananya | Hyderabad | India |
| 2 | Rohan | Bangalore | India |
| 3 | Sam | Mumbai | India |
| 4 | Lisa | London | UK |
| 5 | Ravi | Delhi | India |
| item_id | order_id | product_id | qty | unit_price |
|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 79999 |
| 2 | 2 | 3 | 1 | 2999 |
| 3 | 2 | 2 | 1 | 499 |
| 4 | 3 | 5 | 1 | 65000 |
| 5 | 4 | 2 | 1 | 499 |
| 6 | 5 | 4 | 2 | 99 |
| 7 | 5 | 6 | 1 | 50 |
| 8 | 6 | 3 | 1 | 2999 |
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | iPhone 15 | Electronics | 79999 | 50 |
| 2 | SQL Book | Books | 499 | 200 |
| 3 | Headphones | Electronics | 2999 | 75 |
| 4 | Notebook | Stationery | 99 | 500 |
| 5 | Laptop | Electronics | 65000 | 20 |
| 6 | Pen Set | Stationery | 149 | 0 |
| 7 | Mouse | Electronics | 599 | 25 |