SQL Exercises With Solutions: Intermediate
16 intermediate SQL exercises on the practice shop database, with expected results and explained solutions: multi-table joins, outer joins, avoiding fan-out, correlated subqueries, CTEs, set operations and reporting by month and category.
kvi5hnuCode Sprout team member9 min readOn this page
The second exercise set uses the same shop database as the beginner set. If you skipped it, read the description of the tables there: SQL Exercises With Solutions: Beginner. The runnable block below creates the database again, so you can try your queries in it.
These exercises are about combining data. Most need two or more tables, and several have a trap that gives a plausible but wrong answer. The explanations point out the traps. Write your query, check it against the expected result, and read the answer even when you're right: there's often a second good way to write it.
Two reminders:
- An order line's value is
ROUND(qty * unit_price * (1 - discount), 2). An order's value is the sum of its line values. - Unless an exercise says otherwise, cancelled orders don't count as sales.
-- 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');
SELECT o.order_id, o.status,
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
GROUP BY o.order_id, o.status
ORDER BY o.order_id;
order_id | status | order_value
----------+-----------+-------------
1001 | shipped | 118.00
1002 | delivered | 199.00
1003 | shipped | 191.91
1004 | shipped | 715.20
1005 | shipped | 154.20
1006 | cancelled | 448.99
1007 | shipped | 93.15
1008 | shipped | 193.50
1009 | shipped | 157.50
1010 | delivered | 291.65
1011 | shipped | 28.00
1012 | shipped | 72.90
1013 | shipped | 170.40
1014 | delivered | 240.60
1015 | cancelled | 199.00
1016 | shipped | 278.23
1017 | shipped | 36.00
1018 | delivered | 108.00
1019 | shipped | 36.00
1020 | shipped | 69.00
1021 | pending | 124.20
1022 | pending | 12.00
(22 rows)
Joining several tables
1. The five biggest orders
Show the five non-cancelled orders with the highest value: the order ID, the customer's name and the order value.
Expected result:
order_id | customer | order_value
----------+------------+-------------
1004 | Dana Cruz | 715.20
1010 | Asha Rao | 291.65
1016 | Isha Menon | 278.23
1014 | Eli Novak | 240.60
1002 | Ben Okafor | 199.00
(5 rows)
Answer
SELECT o.order_id, c.name AS customer, SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_id, c.name
ORDER BY order_value DESC
FETCH FIRST 5 ROWS ONLY;
Each order joins to one customer and to several lines, and grouping by order adds its lines up. c.name is in GROUP BY because it's selected. Since each order has exactly one customer, adding it doesn't split any group. PostgreSQL would also accept grouping by o.order_id, c.customer_id alone, because name depends on the customer's primary key (article 19).
2. Sales by category
Show the total sales value for each product category, highest first.
Expected result:
category | sales
----------+---------
Packs | 1097.06
Tents | 1060.20
Clothing | 661.90
Lighting | 470.28
(4 rows)
Answer
SELECT cat.name AS category, 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
JOIN categories cat ON cat.category_id = p.category_id
WHERE o.status <> 'cancelled'
GROUP BY cat.name
ORDER BY sales DESC;
Four tables are joined in a chain: lines to orders (for the status), lines to products, and products to categories. Start from the table whose rows you're adding up, order_items, and join outwards. Each join here goes from many to one, so no rows are multiplied.
3. Sales by department
Categories form a tree: Tents and Lighting are inside Camping, Packs and Clothing inside Hiking. Show the total sales for each department, the second level of the tree (Camping and Hiking).
Expected result:
department | sales
------------+---------
Hiking | 1758.96
Camping | 1530.48
(2 rows)
Hint
Join categories a second time, to the parent of each product's category.
Answer
SELECT parent.name AS department, 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
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 parent.name
ORDER BY sales DESC;
The second copy of categories, aliased parent, is joined through parent_id. This works because every product's category sits directly under a department. For trees of any depth, use a recursive CTE (article 48), as in the advanced set.
4. Category paths
List every category as a path, such as Camping > Tents. The top-level category, Outdoor, has just its own name. Sort by the path.
Expected result:
path
--------------------
Camping > Lighting
Camping > Tents
Hiking > Clothing
Hiking > Packs
Outdoor
Outdoor > Camping
Outdoor > Hiking
(7 rows)
Answer
SELECT COALESCE(parent.name || ' > ', '') || c.name AS path
FROM categories c
LEFT JOIN categories parent ON parent.category_id = c.parent_id
ORDER BY path;
The LEFT JOIN keeps categories without a parent. For them, parent.name || ' > ' is NULL, because concatenating NULL gives NULL, and COALESCE replaces it with an empty string. That NULL behaviour is a useful trick here, but surprising elsewhere. CONCAT ignores NULLs instead (article 36).
Outer joins and missing data
5. Spending by every customer
Show every customer's name and their total spending on non-cancelled orders, including customers who spent nothing, who should show 0. Highest spenders first, and by name when tied.
Expected result:
name | spent
--------------+--------
Dana Cruz | 839.40
Asha Rao | 616.05
Isha Menon | 435.73
Eli Novak | 394.80
Ben Okafor | 335.00
Chen Wei | 333.81
Hugo Lefevre | 229.50
Gita Bose | 93.15
Farah Haddad | 12.00
Jonas Berg | 0
(10 rows)
Hint
Where should the condition on status go so customers without orders aren't lost?
Answer
SELECT c.name, COALESCE(SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)), 0) AS spent
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
AND o.status <> 'cancelled'
LEFT JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.name
ORDER BY spent DESC, c.name;
The status condition is in the ON clause. In WHERE, o.status <> 'cancelled' would be unknown for customers without orders, whose o.status is NULL, and remove Jonas Berg: the outer join would turn into an inner one (article 13). Farah Haddad shows 12.00: their cancelled order is excluded, but the pending one counts. COALESCE turns the NULL sum of no rows into 0.
6. Unpaid shipped orders
Find shipped or delivered orders whose payments don't cover the order value. Show the order ID, the value, and the amount paid, as 0 when there are no payments.
Expected result:
order_id | order_value | paid
----------+-------------+------
1012 | 72.90 | 0
(1 row)
Hint
Joining lines and payments to the order at the same time multiplies rows. Add each up separately.
Answer
WITH due AS (
SELECT order_id, SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS order_value
FROM order_items oi
GROUP BY order_id
),
paid AS (
SELECT order_id, SUM(amount) AS paid
FROM payments
GROUP BY order_id
)
SELECT o.order_id, d.order_value, COALESCE(p.paid, 0) AS paid
FROM orders o
JOIN due d ON d.order_id = o.order_id
LEFT JOIN paid p ON p.order_id = o.order_id
WHERE o.status IN ('shipped', 'delivered')
AND COALESCE(p.paid, 0) < d.order_value;
An order with two lines and two payments would give four rows if both were joined directly, doubling both sums: the fan-out problem (articles 17 and 68). Summarising lines and payments in separate CTEs gives one row per order from each, so they can be compared safely. The LEFT JOIN keeps orders without any payment, which is exactly the case here.
7. Sales staff performance
For every employee, show the number of non-cancelled orders they handled and the total value of those orders. Employees who handled none should show 0 for both.
Expected result:
name | orders | sales
-------------+--------+---------
Omar Said | 6 | 1223.80
Priya Nair | 6 | 1162.48
Rosa Lima | 5 | 508.51
Quinn Adams | 2 | 301.50
Noah Price | 1 | 93.15
Maya Iyer | 0 | 0
(6 rows)
Answer
WITH order_values AS (
SELECT o.order_id, o.employee_id, 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.employee_id
)
SELECT e.name, COUNT(ov.order_id) AS orders, COALESCE(SUM(ov.order_value), 0) AS sales
FROM employees e
LEFT JOIN order_values ov ON ov.employee_id = e.employee_id
GROUP BY e.employee_id, e.name
ORDER BY sales DESC, e.name;
Order values are calculated first, one row per order, so that counting orders afterwards counts orders and not lines. COUNT(ov.order_id) counts only matched rows, giving 0 for Maya Iyer, while COUNT(*) would count the row the outer join adds and give 1 (article 18).
Subqueries
8. Products above their category's average price
Find the products that cost more than the average price of the products in their own category.
Expected result:
name | price
-------------------+--------
Basecamp lantern | 27.00
Glow head torch | 34.50
Rain shell jacket | 129.00
Summit 4 tent | 489.00
Summit 60 pack | 199.00
(5 rows)
Answer
SELECT p.name, p.price
FROM products p
WHERE p.price > (
SELECT AVG(p2.price)
FROM products p2
WHERE p2.category_id = p.category_id
)
ORDER BY p.name;
The subquery is correlated: it refers to p.category_id from the outer query, so it's evaluated for each product with that product's category (article 23). The same result comes from a window function, AVG(price) OVER (PARTITION BY category_id), in a derived table (article 26).
9. Customers whose first order was in February
Find customers whose first order of any status was placed in February 2026. Show their name and the date of that first order.
Expected result:
name | first_order
--------------+-------------
Farah Haddad | 2026-02-03
Gita Bose | 2026-02-09
Hugo Lefevre | 2026-02-16
Isha Menon | 2026-02-22
(4 rows)
Answer
SELECT c.name, f.first_order
FROM customers c
JOIN (
SELECT customer_id, MIN(placed_on) AS first_order
FROM orders
GROUP BY customer_id
) f ON f.customer_id = c.customer_id
WHERE f.first_order >= DATE '2026-02-01'
AND f.first_order < DATE '2026-03-01'
ORDER BY c.name;
First find each customer's first order date in a derived table, then filter. A plain WHERE placed_on in February would also find Asha Rao, whose order 1010 was in February but who first ordered in January. Farah Haddad's first order was cancelled, but the task says any status, so it counts.
10. Largest order of each customer
For each customer who has ordered, show their largest non-cancelled order: the customer's name, the order ID and the value. If two orders tie, show both.
Expected result:
name | order_id | order_value
--------------+----------+-------------
Asha Rao | 1010 | 291.65
Ben Okafor | 1002 | 199.00
Chen Wei | 1003 | 191.91
Dana Cruz | 1004 | 715.20
Eli Novak | 1014 | 240.60
Farah Haddad | 1022 | 12.00
Gita Bose | 1007 | 93.15
Hugo Lefevre | 1008 | 193.50
Isha Menon | 1016 | 278.23
(9 rows)
Answer
WITH order_values AS (
SELECT o.order_id, o.customer_id, 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
)
SELECT c.name, ov.order_id, ov.order_value
FROM order_values ov
JOIN customers c ON c.customer_id = ov.customer_id
WHERE ov.order_value = (
SELECT MAX(ov2.order_value)
FROM order_values ov2
WHERE ov2.customer_id = ov.customer_id
)
ORDER BY c.name;
This is the classic "greatest per group" problem. You can't select order_id next to MAX(order_value) in one grouped query, because the maximum doesn't say which order it came from. Comparing each order with its customer's maximum keeps ties. The advanced and challenge sets solve similar problems with window functions: ROW_NUMBER in "Two best sellers in each category" and RANK in "Best-selling product in each country" (article 27).
11. Products never sold in Britain
List the products that have never been in a non-cancelled order from a customer in Great Britain (country = 'GB').
Expected result:
name
-------------------
Basecamp lantern
Glow head torch
Ridge 2 tent
Trail 30 backpack
(4 rows)
Answer
SELECT p.name
FROM products p
WHERE NOT EXISTS (
SELECT 1
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN customers c ON c.customer_id = o.customer_id
WHERE oi.product_id = p.product_id
AND c.country = 'GB'
AND o.status <> 'cancelled'
)
ORDER BY p.name;
NOT EXISTS with a join inside asks "is there no such sale?" for each product. It's safe with NULLs, unlike NOT IN (article 16).
12. Share of sales by country
Show each country's total sales and its percentage of all sales, rounded to one decimal place, largest first. Include only countries with sales.
Expected result:
country | sales | pct
---------+---------+------
GB | 1569.20 | 47.7
IN | 1490.74 | 45.3
FR | 229.50 | 7.0
(3 rows)
Answer
WITH by_country AS (
SELECT c.country, 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 customers c ON c.customer_id = o.customer_id
WHERE o.status <> 'cancelled'
GROUP BY c.country
)
SELECT country, sales,
ROUND(100 * sales / (SELECT SUM(sales) FROM by_country), 1) AS pct
FROM by_country
ORDER BY sales DESC;
The CTE is used twice: once as the rows, and once in a scalar subquery for the overall total. SUM(sales) OVER () would give the same total as a window function (article 26). The percentages may not add up to exactly 100 after rounding, which is normal.
Set operations and summaries
13. Bought both a tent and a backpack
Find the customers who have bought, in non-cancelled orders, at least one product from the Tents category and at least one from the Packs category.
Expected result:
name
------------
Asha Rao
Isha Menon
(2 rows)
Answer
SELECT c.name
FROM customers c
WHERE c.customer_id IN (
SELECT o.customer_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
WHERE cat.name = 'Tents' AND o.status <> 'cancelled'
INTERSECT
SELECT o.customer_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
WHERE cat.name = 'Packs' AND o.status <> 'cancelled'
)
ORDER BY c.name;
INTERSECT keeps the customer IDs present in both lists (article 15). A common mistake is WHERE cat.name = 'Tents' AND cat.name = 'Packs', which is never true, since one row has one category. Another correct approach groups each customer's purchases and uses HAVING COUNT(DISTINCT cat.name) = 2 with cat.name IN ('Tents', 'Packs').
14. Ordered in February but not in March
Find the customers who placed an order in February 2026 but none in March 2026.
Expected result:
name
--------------
Farah Haddad
(1 row)
Answer
SELECT name
FROM customers
WHERE customer_id IN (
SELECT customer_id FROM orders
WHERE placed_on >= DATE '2026-02-01' AND placed_on < DATE '2026-03-01'
EXCEPT
SELECT customer_id FROM orders
WHERE placed_on >= DATE '2026-03-01' AND placed_on < DATE '2026-04-01'
)
ORDER BY name;
EXCEPT returns the rows of the first query that aren't in the second. Oracle has long called it MINUS, and 21c added EXCEPT as well. The same question can be answered with NOT EXISTS (article 15).
15. Orders paid in instalments
Find the orders paid with more than one payment. Show the order ID, the number of payments, the first and last payment date, and the total paid.
Expected result:
order_id | payments | first_paid | last_paid | total_paid
----------+----------+------------+------------+------------
1003 | 2 | 2026-01-20 | 2026-02-03 | 191.91
1009 | 2 | 2026-02-22 | 2026-03-08 | 157.50
1017 | 2 | 2026-03-24 | 2026-04-07 | 36.00
(3 rows)
Answer
SELECT order_id, COUNT(*) AS payments,
MIN(paid_on) AS first_paid, MAX(paid_on) AS last_paid,
SUM(amount) AS total_paid
FROM payments
GROUP BY order_id
HAVING COUNT(*) > 1
ORDER BY order_id;
Group the payments by order and keep the groups with more than one row. MIN and MAX work on dates as well as numbers.
16. Monthly sales
Show the number of non-cancelled orders and their total value for each month, in date order. Show each month as its first day.
Expected result:
month | orders | sales
------------+--------+---------
2026-01-01 | 5 | 1378.31
2026-02-01 | 4 | 735.80
2026-03-01 | 7 | 934.13
2026-04-01 | 4 | 241.20
(4 rows)
Answer
SELECT DATE_TRUNC('month', o.placed_on)::date AS month,
COUNT(DISTINCT o.order_id) AS orders,
SUM(ROUND(oi.qty * oi.unit_price * (1 - oi.discount), 2)) AS sales
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY month
ORDER BY month;
DATE_TRUNC('month', ...) maps every date in a month to its first day, which is a good grouping key, and casting to date drops the time part. After joining to lines, each order appears once per line, so COUNT(DISTINCT o.order_id) counts orders rather than lines (article 41).
Common questions
When should I use a CTE instead of a subquery? When a step is reused, as in the share-of-sales exercise, or when naming steps makes the query easier to read. They usually perform the same in PostgreSQL 12 and later (article 24).
How do I know whether a join will multiply rows? Ask how many rows of the joined table match each row you already have. Joining from many to one is safe. Joining to a second "many" table multiplies rows, so summarise it first.
Why do several solutions repeat the same order-value calculation?
For self-contained answers. In a real database, a view such as order_values would hold it once (article 56).
Summary
- Join outwards from the table whose rows you're counting or adding.
- Conditions on the optional side of an outer join belong in
ON, notWHERE. - Summarise each child table separately before combining them, to avoid fan-out.
- Correlated subqueries compare each row with its own group.
NOT EXISTSfinds what's missing. INTERSECTandEXCEPTexpress "both" and "but not" between lists.
Practice questions
Rewrite the "Bought both a tent and a backpack" exercise without INTERSECT.
Answer
SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
WHERE cat.name IN ('Tents', 'Packs') AND o.status <> 'cancelled'
GROUP BY c.customer_id, c.name
HAVING COUNT(DISTINCT cat.name) = 2
ORDER BY c.name;
In "Spending by every customer", what changes if the status condition moves to WHERE?
Answer
Customers with no non-cancelled orders disappear, because their o.status is NULL after the outer join and NULL <> 'cancelled' is unknown. Jonas Berg, who has never ordered, would be missing.
Previous: SQL Exercises With Solutions: Beginner

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.