SQL - Joins (Overview)
Overview
Joins combine rows from multiple tables. Start with INNER JOIN, then LEFT/RIGHT/FULL for outer joins, and CROSS JOIN for a Cartesian product.
SELECT e.first_name, d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id;
SELECT e.first_name, d.name AS department
FROM employees e
INNER JOIN departments d ON d.id = e.department_id;
SELECT e.first_name, d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id;
Prerequisite
Load the Standard Test Data.
Expected Output (unordered)
| first_name | department |
|---|---|
| Ada | Engineering |
| Bob | Engineering |
| Chen | HR |
| Dee | Sales |
| Eli | Engineering |
Outer joins and more examples follow in dedicated lessons.
Domain Use Cases (customers/orders/products)
Top customers by spend
| name | total_spend |
|---|---|
| Alice | 2048.99 |
| Cara | 513.99 |
| Ben | 313.99 |
Order lines with product names
| order_id | customer | product | qty | price |
|---|---|---|---|---|
| 1 | Alice | Laptop Pro | 1 | 1999 |
| 1 | Alice | Wireless Mouse | 1 | 49.99 |
| 2 | Ben | Office Chair | 1 | 299 |
| 2 | Ben | Coffee Beans | 1 | 14.99 |
| 3 | Cara | Standing Desk | 1 | 499 |
| 3 | Cara | Wireless Mouse | 1 | 14.99 |