This course builds on SQL from zero and Combining and summarizing. This lesson recaps what it uses from them, so you can start here if you already write everyday SQL.
The examples use a small shop's database: customers, products, orders and order_items (one row per product in an order, with qty), plus staff (with each person's manager_id) and logins (the days customers signed in), which are new in this course. The practice lists every table under The tables.
A join pairs rows of two tables where a condition holds, usually a foreign key matching a primary key (o.customer_id = c.id). JOIN keeps only matches; LEFT JOIN keeps every row of the left table, with NULLs where nothing matched. GROUP BY makes one row per group, aggregates like COUNT and SUM work per group, and HAVING filters the groups. Joins multiply rows, so always know what one row stands for.
SELECT c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
HAVING COUNT(o.id) >= 2
ORDER BY orders DESC, c.name;
Returns
name | orders
-----+-------
Ana | 3
Ben | 2
Cleo | 2
(3 rows)
A subquery is a query in brackets inside another: one value (WHERE price > (SELECT AVG(price) …)), a list (WHERE id IN (SELECT …)) or a test (WHERE NOT EXISTS (SELECT 1 …)). A CTE names a step with WITH name AS (…), and steps can build on each other.
WITH totals AS (
SELECT i.order_id, SUM(i.qty * p.price) AS total
FROM order_items i JOIN products p ON p.id = i.product_id
GROUP BY i.order_id
)
SELECT ROUND(AVG(total), 2) AS avg_order, MAX(total) AS biggest
FROM totals;
And the order a query runs in: FROM and joins, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. Window functions, next lesson, slot in just after HAVING.
Practice
Each product's name and how many units of it have sold in total, with 0 for products that never sold.