SQL Exercises With Solutions: Advanced
15 advanced SQL exercises on the practice shop database, with expected results and explained solutions: ranking and top-N per group, running totals, LAG and moving averages, gaps and calendars, recursive hierarchies, pivots and medians.
kvi5hnuCode Sprout team member9 min readOn this page
The third exercise set uses the same shop database as the earlier sets. The tables are described in SQL Exercises With Solutions: Beginner, and the runnable block below creates them.
These exercises need window functions, recursive CTEs and reporting techniques from Parts 6 and 9. Many can be solved in more than one way. The answers show one clear solution and mention alternatives.
As before, an order's value is the sum of ROUND(qty * unit_price * (1 - discount), 2) over its lines, and cancelled orders don't count as sales unless the exercise says so. Several answers start with this CTE:
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.placed_on,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id, o.customer_id, o.placed_on
)
-- Practice shop database for the SQL exercises
CREATE TABLE categories (
category_id INTEGER PRIMARY KEY,
name VARCHAR(30) NOT NULL,
parent_id INTEGER REFERENCES categories (category_id)
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL), (2, 'Camping', 1), (3, 'Hiking', 1),
(4, 'Tents', 2), (5, 'Lighting', 2), (6, 'Packs', 3), (7, 'Clothing', 3);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category_id INTEGER NOT NULL REFERENCES categories (category_id),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
discontinued BOOLEAN NOT NULL DEFAULT false
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 4, 249.99, 12, false),
(2, 'Summit 4 tent', 4, 489.00, 3, false),
(3, 'Breeze 1 tent', 4, 159.00, 0, true),
(4, 'Glow head torch', 5, 34.50, 40, false),
(5, 'Basecamp lantern', 5, 27.00, 15, false),
(6, 'Spark mini light', 5, 12.00, 60, false),
(7, 'Trail 30 backpack', 6, 89.95, 22, false),
(8, 'Day 18 backpack', 6, 54.00, 0, false),
(9, 'Summit 60 pack', 6, 199.00, 5, false),
(10, 'Merino socks', 7, 16.00, 75, false),
(11, 'Rain shell jacket', 7, 129.00, 9, false),
(12, 'Fleece midlayer', 7, 69.00, 0, true);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
country CHAR(2) NOT NULL,
joined_on DATE NOT NULL,
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', 'IN', DATE '2025-06-14', NULL),
(2, 'Ben Okafor', 'Leeds', 'GB', DATE '2025-08-02', 1),
(3, 'Chen Wei', 'Pune', 'IN', DATE '2025-09-20', 1),
(4, 'Dana Cruz', 'York', 'GB', DATE '2025-11-05', 2),
(5, 'Eli Novak', 'Leeds', 'GB', DATE '2025-12-11', NULL),
(6, 'Farah Haddad', NULL, 'IN', DATE '2026-01-03', 3),
(7, 'Gita Bose', 'Mumbai', 'IN', DATE '2026-01-19', NULL),
(8, 'Hugo Lefevre', 'Lyon', 'FR', DATE '2026-02-07', 5),
(9, 'Isha Menon', 'Mumbai', 'IN', DATE '2026-02-22', 7),
(10, 'Jonas Berg', 'Oslo', 'NO', DATE '2026-03-30', NULL);
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
title VARCHAR(30) NOT NULL,
manager_id INTEGER REFERENCES employees (employee_id),
hired_on DATE NOT NULL
);
INSERT INTO employees VALUES
(1, 'Maya Iyer', 'Head of Sales', NULL, DATE '2022-04-01'),
(2, 'Noah Price', 'Sales Lead', 1, DATE '2023-01-16'),
(3, 'Omar Said', 'Sales Associate', 2, DATE '2024-05-06'),
(4, 'Priya Nair', 'Sales Associate', 2, DATE '2024-09-23'),
(5, 'Quinn Adams', 'Sales Lead', 1, DATE '2023-07-03'),
(6, 'Rosa Lima', 'Sales Associate', 5, DATE '2025-10-13');
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
employee_id INTEGER REFERENCES employees (employee_id),
placed_on DATE NOT NULL,
shipped_on DATE,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(1001, 1, 3, DATE '2026-01-07', DATE '2026-01-09', 'shipped'),
(1002, 2, 4, DATE '2026-01-13', DATE '2026-01-18', 'delivered'),
(1003, 3, 6, DATE '2026-01-20', DATE '2026-01-21', 'shipped'),
(1004, 4, 3, DATE '2026-01-23', DATE '2026-01-28', 'shipped'),
(1005, 5, 4, DATE '2026-01-29', DATE '2026-02-03', 'shipped'),
(1006, 6, 6, DATE '2026-02-03', NULL, 'cancelled'),
(1007, 7, 2, DATE '2026-02-09', DATE '2026-02-14', 'shipped'),
(1008, 8, 5, DATE '2026-02-16', DATE '2026-02-19', 'shipped'),
(1009, 9, 3, DATE '2026-02-22', DATE '2026-02-25', 'shipped'),
(1010, 1, 4, DATE '2026-02-25', DATE '2026-02-26', 'delivered'),
(1011, 2, 6, DATE '2026-03-03', DATE '2026-03-04', 'shipped'),
(1012, 3, 3, DATE '2026-03-05', DATE '2026-03-07', 'shipped'),
(1013, 1, 4, DATE '2026-03-07', DATE '2026-03-10', 'shipped'),
(1014, 5, 6, DATE '2026-03-09', DATE '2026-03-18', 'delivered'),
(1015, 7, 3, DATE '2026-03-14', NULL, 'cancelled'),
(1016, 9, 4, DATE '2026-03-21', DATE '2026-03-23', 'shipped'),
(1017, 8, 6, DATE '2026-03-24', DATE '2026-03-27', 'shipped'),
(1018, 2, 5, DATE '2026-03-28', DATE '2026-03-30', 'delivered'),
(1019, 1, 3, DATE '2026-04-01', DATE '2026-04-04', 'shipped'),
(1020, 3, 4, DATE '2026-04-08', DATE '2026-04-13', 'shipped'),
(1021, 4, 3, DATE '2026-04-15', NULL, 'pending'),
(1022, 6, 6, DATE '2026-04-17', NULL, 'pending');
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
product_id INTEGER NOT NULL REFERENCES products (product_id),
qty INTEGER NOT NULL CHECK (qty > 0),
unit_price DECIMAL(8, 2) NOT NULL,
discount DECIMAL(3, 2) NOT NULL DEFAULT 0,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(1001, 4, 2, 32.00, 0.00),
(1001, 8, 1, 54.00, 0.00),
(1002, 9, 1, 199.00, 0.00),
(1003, 10, 2, 15.00, 0.00),
(1003, 7, 2, 89.95, 0.10),
(1004, 3, 1, 159.00, 0.00),
(1004, 11, 1, 129.00, 0.10),
(1004, 2, 1, 489.00, 0.10),
(1005, 10, 2, 15.00, 0.00),
(1005, 12, 2, 69.00, 0.10),
(1006, 1, 1, 249.99, 0.00),
(1006, 9, 1, 199.00, 0.00),
(1007, 4, 3, 34.50, 0.10),
(1008, 3, 1, 159.00, 0.00),
(1008, 4, 1, 34.50, 0.00),
(1009, 3, 1, 159.00, 0.10),
(1009, 10, 1, 16.00, 0.10),
(1010, 9, 1, 199.00, 0.05),
(1010, 8, 2, 54.00, 0.05),
(1011, 10, 1, 16.00, 0.00),
(1011, 6, 1, 12.00, 0.00),
(1012, 5, 3, 27.00, 0.10),
(1013, 3, 1, 159.00, 0.00),
(1013, 6, 1, 12.00, 0.05),
(1014, 12, 2, 69.00, 0.00),
(1014, 8, 2, 54.00, 0.05),
(1015, 9, 1, 199.00, 0.00),
(1016, 4, 3, 34.50, 0.05),
(1016, 7, 2, 89.95, 0.00),
(1017, 6, 3, 12.00, 0.00),
(1018, 8, 2, 54.00, 0.00),
(1019, 6, 3, 12.00, 0.00),
(1020, 12, 1, 69.00, 0.00),
(1021, 12, 2, 69.00, 0.10),
(1022, 6, 1, 12.00, 0.00);
CREATE TABLE payments (
payment_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id),
paid_on DATE NOT NULL,
amount DECIMAL(8, 2) NOT NULL,
method VARCHAR(10) NOT NULL
);
INSERT INTO payments VALUES
(1, 1001, DATE '2026-01-07', 118.00, 'paypal'),
(2, 1002, DATE '2026-01-13', 199.00, 'card'),
(3, 1003, DATE '2026-01-20', 95.96, 'paypal'),
(4, 1003, DATE '2026-02-03', 95.95, 'paypal'),
(5, 1004, DATE '2026-01-23', 715.20, 'card'),
(6, 1005, DATE '2026-01-29', 154.20, 'card'),
(7, 1007, DATE '2026-02-09', 93.15, 'card'),
(8, 1008, DATE '2026-02-16', 193.50, 'card'),
(9, 1009, DATE '2026-02-22', 78.75, 'card'),
(10, 1009, DATE '2026-03-08', 78.75, 'card'),
(11, 1010, DATE '2026-02-25', 291.65, 'paypal'),
(12, 1011, DATE '2026-03-03', 28.00, 'paypal'),
(13, 1013, DATE '2026-03-07', 170.40, 'upi'),
(14, 1014, DATE '2026-03-09', 240.60, 'card'),
(15, 1016, DATE '2026-03-21', 278.23, 'paypal'),
(16, 1017, DATE '2026-03-24', 18.00, 'card'),
(17, 1017, DATE '2026-04-07', 18.00, 'card'),
(18, 1018, DATE '2026-03-28', 108.00, 'upi'),
(19, 1019, DATE '2026-04-01', 36.00, 'paypal'),
(20, 1020, DATE '2026-04-08', 69.00, 'card'),
(21, 1021, DATE '2026-04-15', 124.20, 'paypal');
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.placed_on,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id, o.customer_id, o.placed_on
)
SELECT * FROM order_values ORDER BY order_id FETCH FIRST 5 ROWS ONLY;
order_id | customer_id | placed_on | order_value
----------+-------------+------------+-------------
1001 | 1 | 2026-01-07 | 118.00
1002 | 2 | 2026-01-13 | 199.00
1003 | 3 | 2026-01-20 | 191.91
1004 | 4 | 2026-01-23 | 715.20
1005 | 5 | 2026-01-29 | 154.20
(5 rows)
Ranking
1. Price rank within each category
For every product, show its category ID, name, price, and its price rank within its category, where 1 is the most expensive. Products with equal prices share a rank, and the next rank isn't skipped.
Expected result:
category_id | name | price | price_rank
-------------+-------------------+--------+------------
4 | Summit 4 tent | 489.00 | 1
4 | Ridge 2 tent | 249.99 | 2
4 | Breeze 1 tent | 159.00 | 3
5 | Glow head torch | 34.50 | 1
5 | Basecamp lantern | 27.00 | 2
5 | Spark mini light | 12.00 | 3
6 | Summit 60 pack | 199.00 | 1
6 | Trail 30 backpack | 89.95 | 2
6 | Day 18 backpack | 54.00 | 3
7 | Rain shell jacket | 129.00 | 1
7 | Fleece midlayer | 69.00 | 2
7 | Merino socks | 16.00 | 3
(12 rows)
Answer
SELECT category_id, name, price,
DENSE_RANK() OVER (PARTITION BY category_id ORDER BY price DESC) AS price_rank
FROM products
ORDER BY category_id, price_rank;
PARTITION BY category_id restarts the ranking for each category. DENSE_RANK gives tied values the same rank and continues with the next number. RANK would leave a gap after a tie, and ROW_NUMBER would number tied rows arbitrarily (article 27).
2. Two best sellers in each category
For each category, show the two products with the highest sales value, with the value and their position.
Expected result:
category_id | pos | name | sales
-------------+-----+-------------------+--------
4 | 1 | Breeze 1 tent | 620.10
4 | 2 | Summit 4 tent | 440.10
5 | 1 | Glow head torch | 289.98
5 | 2 | Spark mini light | 107.40
6 | 1 | Summit 60 pack | 388.05
6 | 2 | Day 18 backpack | 367.20
7 | 1 | Fleece midlayer | 455.40
7 | 2 | Rain shell jacket | 116.10
(8 rows)
Hint
Calculate each product's sales first, then number the products within each category, then filter.
Answer
WITH product_sales AS (
SELECT p.category_id, p.name, SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS sales
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status <> 'cancelled'
GROUP BY p.category_id, p.product_id, p.name
),
ranked AS (
SELECT category_id, name, sales,
ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY sales DESC, name) AS pos
FROM product_sales
)
SELECT category_id, pos, name, sales
FROM ranked
WHERE pos <= 2
ORDER BY category_id, pos;
Window functions are calculated after WHERE, so you can't filter on pos in the query that computes it. Compute it in a CTE, then filter outside (article 27). The name tiebreaker makes the numbering deterministic when two products have the same sales. Use RANK instead of ROW_NUMBER if ties should both be included.
3. Customer spending in three bands
Split the customers who have spent anything into three equal-sized bands by total spending: band 1 for the top spenders. Show the name, the amount spent and the band.
Expected result:
name | spent | band
--------------+--------+------
Dana Cruz | 839.40 | 1
Asha Rao | 616.05 | 1
Isha Menon | 435.73 | 1
Eli Novak | 394.80 | 2
Ben Okafor | 335.00 | 2
Chen Wei | 333.81 | 2
Hugo Lefevre | 229.50 | 3
Gita Bose | 93.15 | 3
Farah Haddad | 12.00 | 3
(9 rows)
Answer
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.placed_on,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id, o.customer_id, o.placed_on
)
SELECT c.name, SUM(ov.order_value) AS spent,
NTILE(3) OVER (ORDER BY SUM(ov.order_value) DESC) AS band
FROM order_values ov
JOIN customers c ON c.customer_id = ov.customer_id
GROUP BY c.customer_id, c.name
ORDER BY spent DESC;
A window function can be applied to the result of grouping, including to an aggregate: NTILE(3) OVER (ORDER BY SUM(...) DESC). The grouping happens first, then the window is computed over the grouped rows. NTILE divides rows as evenly as possible, here 3, 3 and 3 (article 27).
4. Each customer's first order
Show each customer's first non-cancelled order: the customer ID, the order ID, the date and the value.
Expected result:
customer_id | order_id | placed_on | order_value
-------------+----------+------------+-------------
1 | 1001 | 2026-01-07 | 118.00
2 | 1002 | 2026-01-13 | 199.00
3 | 1003 | 2026-01-20 | 191.91
4 | 1004 | 2026-01-23 | 715.20
5 | 1005 | 2026-01-29 | 154.20
6 | 1022 | 2026-04-17 | 12.00
7 | 1007 | 2026-02-09 | 93.15
8 | 1008 | 2026-02-16 | 193.50
9 | 1009 | 2026-02-22 | 157.50
(9 rows)
Answer
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.placed_on,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id, o.customer_id, o.placed_on
)
SELECT DISTINCT ON (customer_id) customer_id, order_id, placed_on, order_value
FROM order_values
ORDER BY customer_id, placed_on, order_id;
DISTINCT ON (customer_id) is PostgreSQL's shortcut for "first row per group": it keeps the first row for each customer in the ORDER BY order. The portable version numbers the rows with ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY placed_on, order_id) and keeps number 1 (article 27). Farah Haddad's first order, 1006, was cancelled, so 1022 is shown.
Running totals, previous rows and moving averages
5. Monthly sales with a running total and change
For each month, show the sales value, the running total since January, and the change from the previous month.
Expected result:
month | sales | running_total | change
------------+---------+---------------+---------
2026-01-01 | 1378.31 | 1378.31 | (null)
2026-02-01 | 735.80 | 2114.11 | -642.51
2026-03-01 | 934.13 | 3048.24 | 198.33
2026-04-01 | 241.20 | 3289.44 | -692.93
(4 rows)
Answer
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.placed_on,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id, o.customer_id, o.placed_on
),
monthly AS (
SELECT DATE_TRUNC('month', placed_on)::date AS month, SUM(order_value) AS sales
FROM order_values
GROUP BY 1
)
SELECT month, sales,
SUM(sales) OVER (ORDER BY month) AS running_total,
sales - LAG(sales) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month;
SUM(...) OVER (ORDER BY month) adds up all months up to the current one, a running total (article 28). LAG(sales) is the previous month's value, NULL for the first month, so the change is NULL there too (article 29).
6. Days between a customer's orders
For customers with more than two orders of any status, list each order with its date and the number of days since that customer's previous order.
Expected result:
customer_id | order_id | placed_on | days_since_previous
-------------+----------+------------+---------------------
1 | 1001 | 2026-01-07 | (null)
1 | 1010 | 2026-02-25 | 49
1 | 1013 | 2026-03-07 | 10
1 | 1019 | 2026-04-01 | 25
2 | 1002 | 2026-01-13 | (null)
2 | 1011 | 2026-03-03 | 49
2 | 1018 | 2026-03-28 | 25
3 | 1003 | 2026-01-20 | (null)
3 | 1012 | 2026-03-05 | 44
3 | 1020 | 2026-04-08 | 34
(10 rows)
Answer
SELECT customer_id, order_id, placed_on,
placed_on - LAG(placed_on) OVER (PARTITION BY customer_id ORDER BY placed_on) AS days_since_previous
FROM orders
WHERE customer_id IN (
SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(*) > 2
)
ORDER BY customer_id, placed_on;
PARTITION BY customer_id makes LAG look only at the same customer's orders. The filter in WHERE is safe here, because it removes whole customers, never some of a customer's orders. Removing individual orders before the window would change which order counts as "previous".
7. Moving average of March orders
Order the non-cancelled orders by date and order ID. For each one, calculate the average value of that order and the two before it, rounded to 2 places. Show only orders placed in March, but the averages must still include February orders where they're among the two before.
Expected result:
order_id | placed_on | order_value | avg_last_3
----------+------------+-------------+------------
1011 | 2026-03-03 | 28.00 | 159.05
1012 | 2026-03-05 | 72.90 | 130.85
1013 | 2026-03-07 | 170.40 | 90.43
1014 | 2026-03-09 | 240.60 | 161.30
1016 | 2026-03-21 | 278.23 | 229.74
1017 | 2026-03-24 | 36.00 | 184.94
1018 | 2026-03-28 | 108.00 | 140.74
(7 rows)
Hint
Filtering to March before calculating the average would leave the first March orders without their predecessors.
Answer
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.placed_on,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id, o.customer_id, o.placed_on
),
moving AS (
SELECT order_id, placed_on, order_value,
ROUND(AVG(order_value) OVER (ORDER BY placed_on, order_id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg_last_3
FROM order_values
)
SELECT *
FROM moving
WHERE placed_on >= DATE '2026-03-01' AND placed_on < DATE '2026-04-01'
ORDER BY placed_on, order_id;
The frame ROWS BETWEEN 2 PRECEDING AND CURRENT ROW averages exactly three rows, or fewer at the very start (article 28). Because WHERE runs before window functions, the window is calculated in a CTE over all orders, and the outer query filters. The first March order's average includes the last two February orders.
8. Long quiet spells
Looking at all orders of any status in date order, find gaps of more than 5 days between one order and the next. Show the dates on either side of each gap and its length in days.
Expected result:
gap_after | gap_before | days
------------+------------+------
2026-01-07 | 2026-01-13 | 6
2026-01-13 | 2026-01-20 | 7
2026-01-23 | 2026-01-29 | 6
2026-02-03 | 2026-02-09 | 6
2026-02-09 | 2026-02-16 | 7
2026-02-16 | 2026-02-22 | 6
2026-02-25 | 2026-03-03 | 6
2026-03-14 | 2026-03-21 | 7
2026-04-01 | 2026-04-08 | 7
2026-04-08 | 2026-04-15 | 7
(10 rows)
Answer
WITH next_orders AS (
SELECT placed_on,
LEAD(placed_on) OVER (ORDER BY placed_on) AS next_placed_on
FROM orders
)
SELECT placed_on AS gap_after, next_placed_on AS gap_before,
next_placed_on - placed_on AS days
FROM next_orders
WHERE next_placed_on - placed_on > 5
ORDER BY placed_on;
LEAD looks at the next row. Comparing each row with its neighbour is the basis of gaps-and-islands problems (article 30). The last order has no next one, so its difference is NULL and the condition drops it.
Calendars and pivots
9. Orders per day, including empty days
Show the number of orders, of any status, placed on each day from 1 to 10 April 2026, including days with none.
Expected result:
day | orders
------------+--------
2026-04-01 | 1
2026-04-02 | 0
2026-04-03 | 0
2026-04-04 | 0
2026-04-05 | 0
2026-04-06 | 0
2026-04-07 | 0
2026-04-08 | 1
2026-04-09 | 0
2026-04-10 | 0
(10 rows)
Answer
SELECT d::date AS day, COUNT(o.order_id) AS orders
FROM generate_series(DATE '2026-04-01', DATE '2026-04-10', INTERVAL '1 day') AS d
LEFT JOIN orders o ON o.placed_on = d::date
GROUP BY d
ORDER BY d;
Grouping orders by date can only show days that have orders. Generating the calendar with generate_series and outer-joining the orders to it fills in the empty days, and COUNT(o.order_id) counts 0 for them (article 41). generate_series with an interval returns timestamps, so ::date converts them.
10. Monthly sales by department, side by side
Show one row per month with the sales value of the Camping and Hiking departments in separate columns, and the month's total.
Expected result:
month | camping | hiking | total
------------+---------+--------+---------
2026-01-01 | 663.10 | 715.21 | 1378.31
2026-02-01 | 429.75 | 306.05 | 735.80
2026-03-01 | 389.63 | 544.50 | 934.13
2026-04-01 | 48.00 | 193.20 | 241.20
(4 rows)
Answer
SELECT DATE_TRUNC('month', o.placed_on)::date AS month,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) FILTER (WHERE parent.name = 'Camping') AS camping,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) FILTER (WHERE parent.name = 'Hiking') AS hiking,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS total
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
JOIN categories parent ON parent.category_id = cat.parent_id
WHERE o.status <> 'cancelled'
GROUP BY 1
ORDER BY 1;
Each FILTER (WHERE ...) aggregate adds up only the rows of its department, turning rows into columns: a pivot (article 44). The portable form is SUM(CASE WHEN parent.name = 'Camping' THEN ... END). A month with no sales in a department would show NULL there. Wrap it in COALESCE(..., 0) if you want 0.
11. Median and average order value
Calculate the average and the median value of non-cancelled orders, both rounded to 2 places, and the number of orders.
Expected result:
orders | average | median
--------+---------+--------
20 | 164.47 | 139.20
(1 row)
Answer
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.placed_on,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id, o.customer_id, o.placed_on
)
SELECT COUNT(*) AS orders,
ROUND(AVG(order_value), 2) AS average,
ROUND(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY order_value)::numeric, 2) AS median
FROM order_values;
PERCENTILE_CONT(0.5) is the median: with an even number of orders, it averages the middle two. It returns double precision, so it's cast to numeric for ROUND. The average is well above the median because of a few large orders, such as 1004. That's why the median is often the better "typical" value (article 38).
12. Products sold at more than one price
Find products whose unit_price has varied across order lines. Show the product's name, its current price, and the distinct prices it was sold at, lowest first, as a comma-separated list.
Expected result:
name | current_price | prices_charged
-----------------+---------------+----------------
Glow head torch | 34.50 | 32.00, 34.50
Merino socks | 16.00 | 15.00, 16.00
(2 rows)
Answer
WITH prices AS (
SELECT DISTINCT product_id, unit_price
FROM order_items
)
SELECT p.name, p.price AS current_price,
STRING_AGG(pr.unit_price::text, ', ' ORDER BY pr.unit_price) AS prices_charged
FROM products p
JOIN prices pr ON pr.product_id = p.product_id
GROUP BY p.product_id, p.name, p.price
HAVING COUNT(*) > 1
ORDER BY p.name;
The CTE keeps each distinct price of each product once, so COUNT(*) counts different prices, and STRING_AGG joins them into one string in numeric order (article 37). Writing STRING_AGG(DISTINCT ...) directly is also possible, but then its ORDER BY must use exactly the aggregated expression, the text, and text sorts '9.00' after '15.00'. This history is why order_items stores the price charged, rather than relying on products.price.
Recursive queries
13. The management chain
Show every employee with their level in the hierarchy, where the head of sales is level 1, and the path of names from the top, such as Maya Iyer > Noah Price. Sort by the path.
Expected result:
level | name | path
-------+-------------+-------------------------------------
1 | Maya Iyer | Maya Iyer
2 | Noah Price | Maya Iyer > Noah Price
3 | Omar Said | Maya Iyer > Noah Price > Omar Said
3 | Priya Nair | Maya Iyer > Noah Price > Priya Nair
2 | Quinn Adams | Maya Iyer > Quinn Adams
3 | Rosa Lima | Maya Iyer > Quinn Adams > Rosa Lima
(6 rows)
Answer
WITH RECURSIVE chain AS (
SELECT employee_id, name, 1 AS level, name::text AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.name, c.level + 1, c.path || ' > ' || e.name
FROM employees e
JOIN chain c ON e.manager_id = c.employee_id
)
SELECT level, name, path
FROM chain
ORDER BY path;
The anchor member selects the top of the tree. The recursive member joins each employee to the row for their manager already in chain, adding 1 to the level and extending the path. It stops when no more employees are found. Casting to text in the anchor gives the column a type that matches the growing path built by the recursive part (articles 25 and 48).
14. Who referred whom, all the way up
Starting from Dana Cruz, follow referred_by up to the first customer in the chain. Show each customer's name and how many steps they are from Dana, who is step 0.
Expected result:
step | name
------+------------
0 | Dana Cruz
1 | Ben Okafor
2 | Asha Rao
(3 rows)
Answer
WITH RECURSIVE up AS (
SELECT customer_id, name, referred_by, 0 AS step
FROM customers
WHERE name = 'Dana Cruz'
UNION ALL
SELECT c.customer_id, c.name, c.referred_by, u.step + 1
FROM customers c
JOIN up u ON c.customer_id = u.referred_by
)
SELECT step, name
FROM up
ORDER BY step;
This walks the tree upwards: the join goes from the current row's referred_by to that customer's ID, the reverse of the management chain exercise. It stops at Asha Rao, whose referred_by is NULL, because the join finds no match.
15. Size of each referral network
For each customer who referred someone, count everyone they brought in directly or indirectly: the people they referred, the people those referred, and so on.
Expected result:
name | network_size
------------+--------------
Asha Rao | 4
Ben Okafor | 1
Chen Wei | 1
Eli Novak | 1
Gita Bose | 1
(5 rows)
Answer
WITH RECURSIVE network AS (
SELECT referred_by AS root_id, customer_id
FROM customers
WHERE referred_by IS NOT NULL
UNION ALL
SELECT n.root_id, c.customer_id
FROM customers c
JOIN network n ON c.referred_by = n.customer_id
)
SELECT r.name, COUNT(*) AS network_size
FROM network n
JOIN customers r ON r.customer_id = n.root_id
GROUP BY r.customer_id, r.name
ORDER BY network_size DESC, r.name;
The anchor pairs every customer with whoever referred them directly. The recursive member then adds the customers referred by anyone already in a network, keeping the same root. Counting the rows per root gives the size of each network. Asha Rao referred Ben Okafor and Chen Wei, who brought in Dana Cruz and Farah Haddad, so their network is 4. If the data could contain a cycle, add CYCLE customer_id SET is_cycle USING path to stop it (article 25).
Common questions
Why can't I filter on a window function in WHERE?
WHERE is evaluated before window functions are calculated. Compute the window function in a CTE or derived table and filter outside it. Some databases, including Snowflake, BigQuery and Oracle AI Database 26ai, offer QUALIFY as a shortcut. PostgreSQL, MySQL and SQL Server don't.
When should I use DISTINCT ON and when ROW_NUMBER?
DISTINCT ON is shorter but specific to PostgreSQL, and keeps exactly one row per group. ROW_NUMBER works everywhere and can keep the first two, three or more rows.
Is a recursive CTE slow? Each iteration is a join, so it's efficient with an index on the parent column. It's usually much faster than looping in application code.
Summary
- Ranking functions number rows within partitions. Filter on them in an outer query.
SUMwith an ordered window gives running totals, and aROWSframe gives moving averages.LAGandLEADcompare a row with its neighbours, the basis of gaps and changes.- Generate a calendar with
generate_seriesto report days with no data. FILTERaggregates pivot rows into columns.PERCENTILE_CONT(0.5)gives the median.- Recursive CTEs walk trees up or down, building levels, paths and network sizes.
Practice questions
Rewrite "Each customer's first order" so it works in databases without DISTINCT ON.
Answer
WITH order_values AS (...), -- as above
numbered AS (
SELECT order_values.*,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY placed_on, order_id) AS rn
FROM order_values
)
SELECT customer_id, order_id, placed_on, order_value
FROM numbered
WHERE rn = 1
ORDER BY customer_id;
In "Monthly sales with a running total", what would SUM(sales) OVER () give, without ORDER BY?
Answer
The grand total of all months on every row. Without ORDER BY, the window frame is the whole partition. With ORDER BY, the default frame runs from the first row to the current one.

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.