Chapter 5 — MySQL: Joins & Aggregates
📚 Chapter Overview
Data is rarely in one table. In this chapter, you will learn how to combine tables using JOINs and perform high-level analysis using Aggregate functions like SUM, AVG, and COUNT.
Learning Objectives:
- Master
INNER JOIN,LEFT JOIN, andRIGHT JOIN. - Use
GROUP BYto summarize data. - Apply
HAVINGto filter aggregated results.
5.1 Joining Multiple Tables
Part 1 — Definition
A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Inner Join returns only matching records. Left Join returns all records from the left table and matching ones from the right.
Part 2 — Syntax
SELECT table1.col, table2.col
FROM table1
INNER JOIN table2
ON table1.common_id = table2.common_id;
Part 3 — Example
Problem: Show all orders along with the name of the customer who placed them.
SELECT orders.order_id, customers.name
FROM orders
INNER JOIN customers
ON orders.customer_id = customers.id;
Observation: The ON clause defines the "Bridge" (Primary Key / Foreign Key) between tables.
Part 4 — Video
Video: Coming Soon
5.2 Aggregates and Grouping
Part 1 — Definition
Aggregate Functions perform a calculation on a set of values and return a single value. GROUP BY is used to arrange identical data into groups (e.g., total sales by city).
Part 2 — Syntax
SELECT category, SUM(price)
FROM products
GROUP BY category;
Part 3 — Example
Problem: Find the average order value for each customer.
SELECT customer_id, AVG(amount) as avg_order
FROM orders
GROUP BY customer_id
ORDER BY avg_order DESC;
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Perform a "Sales Audit" across two tables.
Requirements
- Join
OrdersandProductstables. - Calculate the Total Revenue per Product Category.
- Filter to show only categories with revenue > 10,000 using
HAVING.
Step-by-Step Process
- Identify the common column (e.g., product_id).
- Write the
JOINstatement. - Apply
SUM(price * quantity). - Use
GROUP BY categoryandHAVING ....
Expected Deliverables
- The SQL query script.