SQL Exercises With Solutions: Challenge Set
12 interview-style SQL challenges on the practice shop database, with expected results and explained solutions: second-highest values, pairs, basket analysis, streaks, cohorts, running balances, relational division and data-quality checks.
kvi5hnuCode Sprout team member10 min readOn this page
The last exercise set is a collection of problems of the kind asked in SQL interviews and met in real reporting work. Each one combines several techniques, and most have more than one good solution. The tables are described in SQL Exercises With Solutions: Beginner, and the runnable block below creates them.
Try each problem for at least ten minutes before opening the hint. In an interview, explaining your approach matters as much as the final query: say how you'd break the problem down, which edge cases you'd check (ties, NULLs, empty groups), and how you'd test the result. The answers model that reasoning.
As in the other sets, an order line's value is ROUND(qty * unit_price * (1 - discount), 2), and cancelled orders don't count as sales. Where a problem needs "today", use 30 April 2026, so results don't depend on when you run them.
-- 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.placed_on, o.status, p.name AS product, oi.qty
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.placed_on >= DATE '2026-04-01'
ORDER BY o.order_id, p.name;
order_id | placed_on | status | product | qty
----------+------------+---------+------------------+-----
1019 | 2026-04-01 | shipped | Spark mini light | 3
1020 | 2026-04-08 | shipped | Fleece midlayer | 1
1021 | 2026-04-15 | pending | Fleece midlayer | 2
1022 | 2026-04-17 | pending | Spark mini light | 1
(4 rows)
Classic interview questions
1. The second-highest price
Find the second-highest distinct product price, and the products with that price. If several products shared the highest price, the next lower price should be the answer.
Expected result:
name | price
--------------+--------
Ridge 2 tent | 249.99
(1 row)
Hint
Rank the distinct prices, or find the highest price below the maximum.
Answer
SELECT name, price
FROM products
WHERE price = (
SELECT MAX(price)
FROM products
WHERE price < (SELECT MAX(price) FROM products)
);
The inner subquery finds the highest price, and the middle one the highest price below it, which is correct with ties at the top. ORDER BY price DESC OFFSET 1 LIMIT 1 is a common wrong answer: if two products shared the top price, it would return the top price again. DENSE_RANK() OVER (ORDER BY price DESC) = 2 is the general version for the Nth-highest value (article 27). If there were only one distinct price, this query would correctly return no rows.
2. Customers in the same city
List each pair of different customers who live in the same city, once per pair, with the city.
Expected result:
city | customer_1 | customer_2
--------+------------+------------
Leeds | Ben Okafor | Eli Novak
Mumbai | Gita Bose | Isha Menon
Pune | Asha Rao | Chen Wei
(3 rows)
Answer
SELECT a.city, a.name AS customer_1, b.name AS customer_2
FROM customers a
JOIN customers b
ON b.city = a.city
AND b.customer_id > a.customer_id
ORDER BY a.city, a.name;
A self-join on city pairs customers in the same city. b.customer_id > a.customer_id does two jobs: it stops customers pairing with themselves, and it lists each pair once rather than as (A, B) and (B, A). Customers with a NULL city never pair, because NULL = NULL isn't true, which is the right behaviour for unknown cities (article 14).
3. Categories often bought together
Find pairs of different product categories that appear together in more than one non-cancelled order. Show both category names and the number of orders.
Expected result:
category_1 | category_2 | orders
------------+------------+--------
Lighting | Packs | 2
Packs | Clothing | 2
Tents | Clothing | 2
Tents | Lighting | 2
(4 rows)
Hint
Join the order lines to themselves within the same order, so each row is a pair of lines.
Answer
SELECT c1.name AS category_1, c2.name AS category_2, COUNT(DISTINCT a.order_id) AS orders
FROM order_items a
JOIN products pa ON pa.product_id = a.product_id
JOIN order_items b ON b.order_id = a.order_id
JOIN products pb ON pb.product_id = b.product_id
AND pb.category_id > pa.category_id
JOIN orders o ON o.order_id = a.order_id
JOIN categories c1 ON c1.category_id = pa.category_id
JOIN categories c2 ON c2.category_id = pb.category_id
WHERE o.status <> 'cancelled'
GROUP BY c1.name, c2.name
HAVING COUNT(DISTINCT a.order_id) > 1
ORDER BY orders DESC, category_1, category_2;
This is a market-basket query. Joining the order lines to themselves within the same order gives every pair of lines in it, and pb.category_id > pa.category_id keeps each pair of categories once, in one direction, and drops pairs within the same category. An order with two packs and one clothing item produces two Packs-Clothing pairs, so COUNT(DISTINCT a.order_id) counts orders rather than pairs. At product level, no pair of products in this shop appears in more than one order, which is common in small data: grouping into categories gives patterns enough data to show up. On a large shop the self-join grows with the square of the basket size, so real systems often limit it to recent orders.
4. Best-selling product in each country
For each customer country with sales, find the product with the most units sold in non-cancelled orders. Include all products tied for first place.
Expected result:
country | name | units
---------+------------------+-------
FR | Spark mini light | 3
GB | Fleece midlayer | 6
IN | Glow head torch | 8
(3 rows)
Answer
WITH units AS (
SELECT c.country, p.name, SUM(oi.qty) AS units
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN customers c ON c.customer_id = o.customer_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status <> 'cancelled'
GROUP BY c.country, p.product_id, p.name
),
ranked AS (
SELECT units.*, RANK() OVER (PARTITION BY country ORDER BY units DESC) AS rnk
FROM units
)
SELECT country, name, units
FROM ranked
WHERE rnk = 1
ORDER BY country, name;
Aggregate first, then rank within each country, then keep rank 1. RANK gives every tied product rank 1, so ties all appear, as the task asks. ROW_NUMBER would pick one of them arbitrarily.
Behaviour over time
5. Inactive customers
As of 30 April 2026, find customers whose most recent order of any status was more than 30 days earlier, or who have never ordered. Show the name, the last order date, and the days since it.
Expected result:
name | last_order | days_since
--------------+------------+------------
Jonas Berg | (null) | (null)
Eli Novak | 2026-03-09 | 52
Gita Bose | 2026-03-14 | 47
Isha Menon | 2026-03-21 | 40
Hugo Lefevre | 2026-03-24 | 37
Ben Okafor | 2026-03-28 | 33
(6 rows)
Answer
SELECT c.name, MAX(o.placed_on) AS last_order,
DATE '2026-04-30' - MAX(o.placed_on) AS days_since
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING MAX(o.placed_on) IS NULL
OR MAX(o.placed_on) < DATE '2026-04-30' - 30
ORDER BY last_order NULLS FIRST, c.name;
The LEFT JOIN keeps customers without orders, whose MAX(placed_on) is NULL, and the HAVING condition has to include them explicitly, since NULL < date isn't true. Using a fixed date instead of CURRENT_DATE keeps the result reproducible, and in real reports you'd pass it in as a parameter. NULLS FIRST lists the never-ordered customer first.
6. Longest streak of consecutive months
For each customer, find the longest run of consecutive calendar months in which they placed at least one order of any status. Show customers whose longest streak is at least 2 months, with the streak length and the months it starts and ends.
Expected result:
name | months | first_month | last_month
--------------+--------+-------------+------------
Asha Rao | 4 | 2026-01-01 | 2026-04-01
Chen Wei | 2 | 2026-03-01 | 2026-04-01
Gita Bose | 2 | 2026-02-01 | 2026-03-01
Hugo Lefevre | 2 | 2026-02-01 | 2026-03-01
Isha Menon | 2 | 2026-02-01 | 2026-03-01
(5 rows)
Hint
This is a gaps-and-islands problem. Numbering a customer's months in order and subtracting that number from the month gives the same value for every month in a run.
Answer
WITH months AS (
SELECT DISTINCT customer_id,
DATE_TRUNC('month', placed_on)::date AS month
FROM orders
),
islands AS (
SELECT customer_id, month,
month - (ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY month)
* INTERVAL '1 month') AS grp
FROM months
),
streaks AS (
SELECT customer_id, COUNT(*) AS months, MIN(month) AS first_month, MAX(month) AS last_month,
RANK() OVER (PARTITION BY customer_id ORDER BY COUNT(*) DESC) AS rnk
FROM islands
GROUP BY customer_id, grp
)
SELECT c.name, s.months, s.first_month, s.last_month
FROM streaks s
JOIN customers c ON c.customer_id = s.customer_id
WHERE s.rnk = 1 AND s.months >= 2
ORDER BY s.months DESC, c.name;
First reduce each customer's orders to the distinct months they ordered in. Within a run of consecutive months, the month goes up by one each time and so does the row number, so month - row_number months stays constant: that value identifies the island. Group by it to get each streak's length and limits, and rank the streaks per customer to keep the longest (article 30). Asha Rao ordered in all four months.
7. Customers ordering within 30 days of joining
Group customers into cohorts by the month they joined. For each cohort, show how many customers joined and how many placed an order of any status within 30 days of joining.
Expected result:
cohort | customers | ordered_within_30_days
------------+-----------+------------------------
2025-06-01 | 1 | 0
2025-08-01 | 1 | 0
2025-09-01 | 1 | 0
2025-11-01 | 1 | 0
2025-12-01 | 1 | 0
2026-01-01 | 2 | 1
2026-02-01 | 2 | 2
2026-03-01 | 1 | 0
(8 rows)
Answer
SELECT DATE_TRUNC('month', c.joined_on)::date AS cohort,
COUNT(*) AS customers,
COUNT(*) FILTER (WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.placed_on < c.joined_on + 30
)) AS ordered_within_30_days
FROM customers c
GROUP BY cohort
ORDER BY cohort;
Cohort analysis groups customers by when they started. Using EXISTS inside FILTER counts each customer at most once, however many qualifying orders they have. Counting rows of a join to orders instead would count orders, not customers. joined_on + 30 adds 30 days to a date in PostgreSQL. Several cohorts show 0 here, because this shop only has orders from January 2026.
8. Running balance of instalment payments
For orders paid in more than one payment, list each payment with the order's value and the balance still owed after that payment.
Expected result:
order_id | paid_on | amount | order_value | balance
----------+------------+--------+-------------+---------
1003 | 2026-01-20 | 95.96 | 191.91 | 95.95
1003 | 2026-02-03 | 95.95 | 191.91 | 0.00
1009 | 2026-02-22 | 78.75 | 157.50 | 78.75
1009 | 2026-03-08 | 78.75 | 157.50 | 0.00
1017 | 2026-03-24 | 18.00 | 36.00 | 18.00
1017 | 2026-04-07 | 18.00 | 36.00 | 0.00
(6 rows)
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
)
SELECT p.order_id, p.paid_on, p.amount, d.order_value,
d.order_value - SUM(p.amount) OVER (PARTITION BY p.order_id ORDER BY p.paid_on, p.payment_id) AS balance
FROM payments p
JOIN due d ON d.order_id = p.order_id
WHERE p.order_id IN (SELECT order_id FROM payments GROUP BY order_id HAVING COUNT(*) > 1)
ORDER BY p.order_id, p.paid_on;
A running total of payments per order, subtracted from the order value, gives the balance after each payment. payment_id in the window's ORDER BY breaks ties between payments on the same day. Joining due is safe because it has one row per order. The final balance of 0 for each order confirms they were fully paid.
Harder problems
9. Customers who bought from every category
Find customers who have bought, in non-cancelled orders, at least one product from every category that contains products.
Expected result:
name | categories
------------+------------
Isha Menon | 4
(1 row)
Hint
Count the distinct categories each customer bought from, and compare with the number of categories that have products.
Answer
SELECT c.name, COUNT(DISTINCT p.category_id) AS categories
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
WHERE o.status <> 'cancelled'
GROUP BY c.customer_id, c.name
HAVING COUNT(DISTINCT p.category_id) = (SELECT COUNT(DISTINCT category_id) FROM products)
ORDER BY c.name;
"Customers who bought from every category" is relational division. Counting is the usual solution: a customer qualifies when the number of distinct categories they bought from equals the number of categories there are. The other classic form uses a double NOT EXISTS: customers for whom there's no category they didn't buy from. Comparing with categories in products, rather than all rows of categories, leaves out Outdoor, Camping and Hiking, which contain no products directly.
10. Repeat purchases of the same product
Find customers who bought the same product in two or more different non-cancelled orders. Show the customer, the product and the number of orders.
Expected result:
customer | product | orders
-----------+------------------+--------
Asha Rao | Day 18 backpack | 2
Asha Rao | Spark mini light | 2
Eli Novak | Fleece midlayer | 2
(3 rows)
Answer
SELECT c.name AS customer, p.name AS product, COUNT(*) AS orders
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN customers c ON c.customer_id = o.customer_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status <> 'cancelled'
GROUP BY c.customer_id, c.name, p.product_id, p.name
HAVING COUNT(*) > 1
ORDER BY orders DESC, customer, product;
Group by customer and product, and keep the groups with more than one row. Because (order_id, product_id) is the primary key of order_items, each row in a group is a different order, so COUNT(*) counts orders. Without that key, you'd need COUNT(DISTINCT o.order_id). Checking a constraint like this before choosing between them is good practice.
11. Shipping within three days, by employee
For each employee who handled shipped or delivered orders, show how many such orders they handled, how many were shipped within 3 days of being placed, and that as a percentage rounded to whole numbers.
Expected result:
name | shipped_orders | within_3_days | pct
-------------+----------------+---------------+-----
Quinn Adams | 2 | 2 | 100
Omar Said | 5 | 4 | 80
Rosa Lima | 4 | 3 | 75
Priya Nair | 6 | 3 | 50
Noah Price | 1 | 0 | 0
(5 rows)
Answer
SELECT e.name,
COUNT(*) AS shipped_orders,
COUNT(*) FILTER (WHERE o.shipped_on - o.placed_on <= 3) AS within_3_days,
ROUND(100.0 * COUNT(*) FILTER (WHERE o.shipped_on - o.placed_on <= 3) / COUNT(*)) AS pct
FROM orders o
JOIN employees e ON e.employee_id = o.employee_id
WHERE o.status IN ('shipped', 'delivered')
GROUP BY e.employee_id, e.name
ORDER BY pct DESC, e.name;
Conditional counts with FILTER calculate the numerator and the denominator in one pass. 100.0 makes the division decimal: with 100 * and integer counts, PostgreSQL would divide integers and truncate (article 38). The portable alternative to FILTER is SUM(CASE WHEN ... THEN 1 ELSE 0 END).
12. Data-quality checks
Write one query that reports problems in the data, each as a row with a check name and a count: orders marked shipped or delivered but with no shipped_on, orders with a shipped_on before placed_on, shipped or delivered orders not fully paid, and products with negative stock. Show every check, even those with a count of 0.
Expected result:
check_name | problems
------------------------------+----------
shipped without a ship date | 0
shipped before it was placed | 0
shipped but not fully paid | 1
negative stock | 0
(4 rows)
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 'shipped without a ship date' AS check_name, COUNT(*) AS problems
FROM orders WHERE status IN ('shipped', 'delivered') AND shipped_on IS NULL
UNION ALL
SELECT 'shipped before it was placed', COUNT(*)
FROM orders WHERE shipped_on < placed_on
UNION ALL
SELECT 'shipped but not fully paid', COUNT(*)
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
UNION ALL
SELECT 'negative stock', COUNT(*)
FROM products WHERE stock < 0;
Each check is a separate aggregate query, and UNION ALL stacks them into one report. An aggregate without GROUP BY always returns one row, so checks with no problems show 0 rather than disappearing. Queries like this are worth scheduling: they catch problems that constraints don't, such as the unpaid order 1012. Some checks, such as negative stock, could become CHECK constraints instead (article 52), which is better than detecting the problem afterwards.
Common questions
How should I approach an SQL problem in an interview? Restate the problem, ask about edge cases such as ties, NULLs and empty groups, then build the query in steps, often as CTEs, checking each step's result. Mention indexes and performance at the end if there's time.
My solution uses a correlated subquery where the answer uses a window function. Is that worse? Not necessarily. Both are correct. On large tables, window functions often scan the data once, while correlated subqueries may run per row, so check the plan (article 67).
How do I check my answer when I don't know the expected result? Test small cases by hand, check totals against simpler queries, and look at the edge cases: a customer with no orders, a tie, a NULL.
Summary
- Ties change answers: use
DENSE_RANKorRANK, notOFFSET, for Nth-highest and best-per-group questions. - Self-joins with
a.id < b.idlist each pair once. - Gaps-and-islands problems subtract a row number from a sequence to label runs.
- Relational division counts distinct matches against the total, or uses a double
NOT EXISTS. - Conditional aggregates with
FILTERproduce several counts and percentages in one pass. - Data-quality reports stack aggregate checks with
UNION ALL.
Practice questions
Rewrite "Customers who bought from every category" using NOT EXISTS instead of counting.
Answer
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM (SELECT DISTINCT category_id FROM products) cat
WHERE NOT EXISTS (
SELECT 1
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.customer_id = c.customer_id
AND o.status <> 'cancelled'
AND p.category_id = cat.category_id
)
)
ORDER BY c.name;
It reads as "customers for whom there's no category that they haven't bought from".
Why does "The second-highest price" return no rows if all products had the same price, and is that right?
Answer
The middle subquery finds no price below the maximum, so it returns NULL, and price = NULL matches nothing. That's correct: there is no second-highest price. If a report needs a row anyway, select the subquery itself, SELECT (SELECT MAX(price) ...) AS second_price, which returns one row containing NULL.
That completes the course. To test everything together, take the SQL course final exam, then the quizzes on interview questions, delicate details and dialect differences.
Previous: SQL Exercises With Solutions: Advanced

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.