SQL Problem Lab

Updated · 9 min read
hardPostgreSQL 18sqlpracticechallengesassessment

Each problem here is a request from the shop's manager, in plain words, with no starter query. That's how SQL work really arrives: someone asks a question, and you decide which tables to use, how to join and group them, and what the answer should look like. The problems use the shop dataset, an online store for learning supplies with 5,003 customers, 40 products and 60,000 orders over 2024 and 2025. Try it loads it the first time you run a problem, which takes a few seconds; after that, every run starts from a fresh copy.

How the Lab Works

  1. Read the ticket. Decide what one row of the answer means before you write anything.
  2. Write your query in Try it (open any solution's Try it and replace the code), and run it.
  3. Open Show solution and compare the rows. Any query that returns the same rows passes; the order matters only when the ticket asks for one.
TableRowsColumns
customers5,003customer_id, name, city, state, joined_on
products40product_id, name, category, price_usd
orders60,000order_id, customer_id, ordered_on, status (delivered, shipped, canceled, returned)
order_items117,894order_id, product_id, quantity, unit_price_usd
shipments58,800order_id, carrier, shipped_on, delivered_on
returns1,200order_id, product_id, returned_on, reason
inventory40product_id, in_stock, reorder_level

Easy Problems

Ticket 1: Our catalog. "How many products do we sell in each category, and what's the cheapest and most expensive in each?"

Show solution
SQL▶ Try it
SELECT category, count(*) AS products,
       min(price_usd) AS cheapest_usd, max(price_usd) AS priciest_usd
FROM products
GROUP BY category
ORDER BY category;
Output
  category   | products | cheapest_usd | priciest_usd
-------------+----------+--------------+--------------
 books       |       10 |        19.00 |        45.00
 courses     |       10 |        29.00 |        99.00
 electronics |       10 |        15.00 |       169.00
 stationery  |       10 |         5.00 |        14.00
(4 rows)

One row per category with three aggregates. See Aggregate Functions.

Ticket 2: Customers in Texas. "List our Texas customers who joined in 2025, newest first. Just the first ten."

Show solution
SQL▶ Try it
SELECT customer_id, name, city, joined_on
FROM customers
WHERE state = 'TX'
  AND joined_on >= '2025-01-01' AND joined_on < '2026-01-01'
ORDER BY joined_on DESC, customer_id
LIMIT 10;
Output
 customer_id |      name      |  city  | joined_on
-------------+----------------+--------+------------
         930 | Customer 00927 | Austin | 2025-11-30
        3030 | Customer 03027 | Austin | 2025-11-30
         438 | Customer 00435 | Austin | 2025-11-26
        2538 | Customer 02535 | Austin | 2025-11-26
        4638 | Customer 04635 | Austin | 2025-11-26
        2046 | Customer 02043 | Austin | 2025-11-22
        4146 | Customer 04143 | Austin | 2025-11-22
        1554 | Customer 01551 | Austin | 2025-11-18
        3654 | Customer 03651 | Austin | 2025-11-18
        1062 | Customer 01059 | Austin | 2025-11-14
(10 rows)

A half-open date range catches every day of 2025. See WHERE.

Ticket 3: Low stock. "Which products are at or below their reorder level? Show how many we have."

Show solution
SQL▶ Try it
SELECT p.name, i.in_stock, i.reorder_level
FROM inventory i
JOIN products p ON p.product_id = i.product_id
WHERE i.in_stock <= i.reorder_level
ORDER BY i.in_stock, p.name;
Output
          name           | in_stock | reorder_level
-------------------------+----------+---------------
 Gel Pens, 10 Pack       |        1 |            20
 Webcam HD               |        2 |            20
 Design Patterns Course  |        3 |            20
 Networking Fundamentals |       10 |            20
 USB-C Hub               |       11 |            20
 Interview Prep Course   |       12 |            20
 Clean Code Notes        |       19 |            20
 Graph Paper Pad         |       20 |            20
(8 rows)

Join inventory to products for the names. See INNER JOIN.

Ticket 4: Never ordered. "Have any customers signed up and never ordered anything?"

Show solution
SQL▶ Try it
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
ORDER BY c.customer_id;
Output
 customer_id |      name
-------------+----------------
         842 | Customer 00839
        2504 | Customer 02501
        2923 | Customer 02920
        3342 | Customer 03339
(4 rows)

NOT EXISTS is the safe anti-join. See EXISTS.

Medium Problems

Ticket 5: Revenue by year. "What was our revenue from delivered orders in 2024 and in 2025, and how did it change?"

Show solution
SQL▶ Try it
WITH yearly AS (
  SELECT EXTRACT(YEAR FROM o.ordered_on)::int AS year,
         sum(i.quantity * i.unit_price_usd) AS revenue_usd
  FROM orders o
  JOIN order_items i ON i.order_id = o.order_id
  WHERE o.status = 'delivered'
  GROUP BY 1
)
SELECT year, revenue_usd,
       revenue_usd - lag(revenue_usd) OVER (ORDER BY year) AS change_usd
FROM yearly
ORDER BY year;
Output
 year | revenue_usd | change_usd
------+-------------+------------
 2024 |  5991525.00 |       NULL
 2025 |  5861708.00 | -129817.00
(2 rows)

Aggregate per year in a CTE, then lag() for the change. See Running Totals, LAG and LEAD.

Ticket 6: Basket size. "On average, how many items and how many dollars are in an order? Don't count canceled orders."

Show solution
SQL▶ Try it
SELECT round(avg(items), 2) AS avg_items, round(avg(total_usd), 2) AS avg_order_usd
FROM (
  SELECT o.order_id, sum(i.quantity) AS items, sum(i.quantity * i.unit_price_usd) AS total_usd
  FROM orders o
  JOIN order_items i ON i.order_id = o.order_id
  WHERE o.status <> 'canceled'
  GROUP BY o.order_id
) AS per_order;
Output
 avg_items | avg_order_usd
-----------+---------------
      4.61 |        209.47
(1 row)

Total each order first, then average the totals; averaging item rows directly would weight big orders wrongly. See Subqueries.

Ticket 7: Top customers. "Who are our top five customers by delivered revenue in 2025? Include ties."

Show solution
SQL▶ Try it
WITH spend AS (
  SELECT o.customer_id, sum(i.quantity * i.unit_price_usd) AS revenue_usd
  FROM orders o
  JOIN order_items i ON i.order_id = o.order_id
  WHERE o.status = 'delivered'
    AND o.ordered_on >= '2025-01-01' AND o.ordered_on < '2026-01-01'
  GROUP BY o.customer_id
)
SELECT c.name, s.revenue_usd, r.rank
FROM (SELECT customer_id, RANK() OVER (ORDER BY revenue_usd DESC) AS rank FROM spend) r
JOIN spend s ON s.customer_id = r.customer_id
JOIN customers c ON c.customer_id = r.customer_id
WHERE r.rank <= 5
ORDER BY r.rank, c.name;
Output
      name      | revenue_usd | rank
----------------+-------------+------
 Customer 00122 |     6894.00 |    1
 Customer 00126 |     6880.00 |    2
 Customer 00342 |     6860.00 |    3
 Customer 00434 |     6622.00 |    4
 Customer 00150 |     6584.00 |    5
 Customer 00202 |     6584.00 |    5
(6 rows)

RANK() keeps ties at the cut-off. See Ranking Functions.

Ticket 8: Category mix by quarter. "Show revenue by category for each quarter of 2025, one row per quarter, one column per category."

Show solution
SQL▶ Try it
SELECT EXTRACT(QUARTER FROM o.ordered_on)::int AS quarter,
       sum(i.quantity * i.unit_price_usd) FILTER (WHERE p.category = 'books')       AS books_usd,
       sum(i.quantity * i.unit_price_usd) FILTER (WHERE p.category = 'stationery')  AS stationery_usd,
       sum(i.quantity * i.unit_price_usd) FILTER (WHERE p.category = 'electronics') AS electronics_usd,
       sum(i.quantity * i.unit_price_usd) FILTER (WHERE p.category = 'courses')     AS courses_usd
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
JOIN products p ON p.product_id = i.product_id
WHERE o.status = 'delivered'
  AND o.ordered_on >= '2025-01-01' AND o.ordered_on < '2026-01-01'
GROUP BY 1
ORDER BY 1;
Output
 quarter | books_usd | stationery_usd | electronics_usd | courses_usd
---------+-----------+----------------+-----------------+-------------
       1 | 271149.00 |       75395.50 |       693469.00 |   433766.00
       2 | 271793.00 |       76618.00 |       703879.00 |   438000.00
       3 | 277154.00 |       77333.50 |       707015.00 |   444500.00
       4 | 254975.00 |       71816.00 |       656547.00 |   408298.00
(4 rows)

Pivot with FILTER: one aggregate per category column. See Pivoting Data.

Hard Problems

Ticket 9: Cohorts. "For customers grouped by the month they joined in 2024, how many placed an order within 30 days of joining?"

Show solution
SQL▶ Try it
WITH first_orders AS (
  SELECT c.customer_id, c.joined_on,
         min(o.ordered_on) AS first_order_on
  FROM customers c
  LEFT JOIN orders o
    ON o.customer_id = c.customer_id AND o.ordered_on >= c.joined_on
  WHERE c.joined_on >= '2024-01-01' AND c.joined_on < '2025-01-01'
  GROUP BY c.customer_id, c.joined_on
)
SELECT to_char(date_trunc('month', joined_on), 'YYYY-MM') AS cohort,
       count(*) AS customers,
       count(*) FILTER (WHERE first_order_on < joined_on + 30) AS ordered_within_30_days
FROM first_orders
GROUP BY 1
ORDER BY 1;
Output
 cohort  | customers | ordered_within_30_days
---------+-----------+------------------------
 2024-01 |       223 |                     77
 2024-02 |       210 |                     74
 2024-03 |       224 |                     86
 2024-04 |       214 |                     78
 2024-05 |       221 |                     75
 2024-06 |       214 |                     76
 2024-07 |       223 |                     82
 2024-08 |       222 |                     81
 2024-09 |       215 |                     73
 2024-10 |       220 |                     79
 2024-11 |       213 |                     79
 2024-12 |       221 |                     81
(12 rows)

Find each customer's first order on or after joining in one pass (a join and min), then count per cohort. A correlated EXISTS per customer gives the same answer but is much slower here. See Common Table Expressions.

Ticket 10: Late deliveries. "What share of each carrier's deliveries took more than five days in each quarter of 2025? I want to know who's getting worse."

Show solution
SQL▶ Try it
SELECT s.carrier,
       EXTRACT(QUARTER FROM o.ordered_on)::int AS quarter,
       round(100.0 * count(*) FILTER (WHERE s.delivered_on - o.ordered_on > 5) / count(*), 1) AS late_pct
FROM shipments s
JOIN orders o ON o.order_id = s.order_id
WHERE s.delivered_on IS NOT NULL
  AND o.ordered_on >= '2025-01-01' AND o.ordered_on < '2026-01-01'
GROUP BY s.carrier, quarter
ORDER BY s.carrier, quarter;
Output
 carrier | quarter | late_pct
---------+---------+----------
 FedEx   |       1 |     61.1
 FedEx   |       2 |     61.3
 FedEx   |       3 |     61.3
 FedEx   |       4 |     61.0
 UPS     |       1 |     40.9
 UPS     |       2 |     40.8
 UPS     |       3 |     40.8
 UPS     |       4 |     40.8
 USPS    |       1 |     81.6
 USPS    |       2 |     81.8
 USPS    |       3 |     81.6
 USPS    |       4 |     81.7
(12 rows)

Exclude undelivered orders; 100.0 keeps the fraction. See Pivoting Data.

Ticket 11: Bought together. "Which pairs of products are bought together in the same order most often? Top five pairs."

Show solution
SQL▶ Try it
SELECT a.name AS product_a, b.name AS product_b, count(*) AS orders_together
FROM order_items x
JOIN order_items y ON y.order_id = x.order_id AND y.product_id > x.product_id
JOIN products a ON a.product_id = x.product_id
JOIN products b ON b.product_id = y.product_id
GROUP BY a.name, b.name
ORDER BY orders_together DESC, product_a, product_b
LIMIT 5;
Output
       product_a        |        product_b        | orders_together
------------------------+-------------------------+-----------------
 Algorithms Illustrated | Wireless Mouse          |             737
 Desk Planner 2025      | USB-C Hub               |             737
 Dot Grid Notebook      | JavaScript Video Course |             737
 Desk Planner 2025      | SQL Basics Video Course |             736
 Gel Pens, 10 Pack      | Git Video Course        |             633
(5 rows)

A self join on the order, with y.product_id > x.product_id so each pair counts once. See Self Join.

Ticket 12: Restock list. "For each product at or below its reorder level, how many did we sell in the last 90 days of 2025, so I know how much to order?"

Show solution
SQL▶ Try it
WITH recent AS (
  SELECT oi.product_id, sum(oi.quantity) AS sold
  FROM order_items oi
  JOIN orders o ON o.order_id = oi.order_id
  WHERE o.ordered_on >= DATE '2026-01-01' - 90
    AND o.ordered_on <  DATE '2026-01-01'
    AND o.status <> 'canceled'
  GROUP BY oi.product_id
)
SELECT p.name, i.in_stock, coalesce(r.sold, 0) AS sold_last_90_days
FROM inventory i
JOIN products p ON p.product_id = i.product_id
LEFT JOIN recent r ON r.product_id = i.product_id
WHERE i.in_stock <= i.reorder_level
ORDER BY sold_last_90_days DESC, p.name;
Output
          name           | in_stock | sold_last_90_days
-------------------------+----------+-------------------
 Gel Pens, 10 Pack       |        1 |              1249
 USB-C Hub               |       11 |              1243
 Clean Code Notes        |       19 |              1220
 Networking Fundamentals |       10 |               545
 Interview Prep Course   |       12 |               540
 Graph Paper Pad         |       20 |               538
 Webcam HD               |        2 |               513
 Design Patterns Course  |        3 |                 0
(8 rows)

Total recent sales per product in a CTE first, then LEFT JOIN it, so products with no recent sales still appear with 0. See Common Table Expressions.

Next Steps

Was this tutorial helpful?