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:

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

Step-by-Step Process

  1. Identify the common column (e.g., product_id).
  2. Write the JOIN statement.
  3. Apply SUM(price * quantity).
  4. Use GROUP BY category and HAVING ....

Expected Deliverables