SQL Mock Interview

Updated · 6 min read
hardPostgreSQL 18sqlinterviewmock-interviewassessment

This page simulates a 45-minute SQL interview round: five tasks where you write and run queries, and five questions you answer out loud. Set a timer, work through the tasks in order, and only open a solution when its time is up. Four tasks use the shop dataset, an online store with 5,000 customers and 60,000 orders; Try it loads it the first time you run one, which takes a few seconds.

How the Mock Interview Works

PartTimeScoring
Five query tasks41 minutes in total, suggested per task2 points each: 1 for the right rows, 1 for a clear explanation of your approach
Five concept questions1 minute each, out loud2 points each: 1 for correctness, 1 for a concrete example
Totalabout 45 minutes20 points

The Shop Dataset

TableRowsColumns
customers5,003customer_id, name, city, state, joined_on
products40product_id, name, category, price_usd
orders60,000order_id, customer_id, ordered_on, status
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

Part 1: Five Query Tasks

Task 1 (5 min): Repeat customers. On the shop dataset, how many customers placed more than 20 orders? Return one number.

Show solution
SQL▶ Try it
SELECT count(*) AS customers_over_20
FROM (
  SELECT customer_id
  FROM orders
  GROUP BY customer_id
  HAVING count(*) > 20
) AS busy;
Output
 customers_over_20
-------------------
               503
(1 row)

Group orders per customer, keep the busy ones with HAVING, then count the groups. Interviewers listen for why HAVING and not WHERE. See HAVING.

Task 2 (8 min): Second purchase. On the shop dataset, for the three sisters (customers 1 to 3), show the date of each one's second order.

Show solution
SQL▶ Try it
SELECT customer_id, ordered_on AS second_order_on
FROM (
  SELECT customer_id, ordered_on,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_on, order_id) AS n
  FROM orders
  WHERE customer_id <= 3
) AS numbered
WHERE n = 2
ORDER BY customer_id;
Output
 customer_id | second_order_on
-------------+-----------------
           1 | 2024-02-27
           2 | 2024-02-12
           3 | 2024-03-15
(3 rows)

ROW_NUMBER() per customer, ordered by date with the order id as tie-breaker, then keep number 2. See Ranking Functions.

Task 3 (8 min): Return rate by category. On the shop dataset, show each product category with its number of items sold and the percentage of them returned, highest return rate first.

Show solution
SQL▶ Try it
SELECT p.category,
       count(*) AS items_sold,
       round(100.0 * count(r.order_id) / count(*), 2) AS return_pct
FROM order_items i
JOIN products p ON p.product_id = i.product_id
LEFT JOIN returns r ON r.order_id = i.order_id AND r.product_id = i.product_id
GROUP BY p.category
ORDER BY return_pct DESC, p.category;
Output
  category   | items_sold | return_pct
-------------+------------+------------
 books       |      30945 |       1.64
 stationery  |      30849 |       1.30
 electronics |      30836 |       0.61
 courses     |      25264 |       0.42
(4 rows)

A LEFT JOIN to returns keeps every item; count(r.order_id) counts only returned ones. 100.0 avoids integer division. See LEFT JOIN.

Task 4 (10 min): Late shipments. On the shop dataset, which carrier has the highest share of deliveries taking more than 5 days from order to delivery? Show each carrier with deliveries, late deliveries and the late percentage.

Show solution
SQL▶ Try it
SELECT s.carrier,
       count(*) AS deliveries,
       count(*) FILTER (WHERE s.delivered_on - o.ordered_on > 5) AS late,
       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
GROUP BY s.carrier
ORDER BY late_pct DESC, s.carrier;
Output
 carrier | deliveries | late  | late_pct
---------+------------+-------+----------
 USPS    |      19418 | 15852 |     81.6
 FedEx   |      19414 | 11883 |     61.2
 UPS     |      19416 |  7925 |     40.8
(3 rows)

FILTER counts the late ones in the same pass. Leaving out undelivered orders (delivered_on IS NOT NULL) keeps them from counting as on time. See Pivoting Data.

Task 5 (10 min): Fix the report. This Fee Tracker query should list each course with its total collected, including courses with no payments, but Git Basics is missing and Java OOP shows the wrong total. Fix it: SELECT c.title, sum(p.amount_usd) FROM courses c JOIN enrollments e ON e.course_id = c.course_id JOIN payments p ON p.course_id = c.course_id GROUP BY c.title;

Show solution
SQL▶ Try it
SELECT c.title, coalesce(sum(p.amount_usd), 0) AS collected_usd
FROM courses c
LEFT JOIN payments p ON p.course_id = c.course_id
GROUP BY c.course_id, c.title
ORDER BY c.course_id;
Output
       title       | collected_usd
-------------------+---------------
 Java Basics       |        450.00
 Java OOP          |        500.00
 Java Collections  |        550.00
 SQL Basics        |        200.00
 JavaScript Basics |        450.00
 Git Basics        |             0
(6 rows)

Two problems: the inner joins drop Git Basics, and joining enrollments repeats each payment once per enrollment of the course. Payments already carry course_id, so join payments alone with a LEFT JOIN, and coalesce the empty sum. See Joining Many Tables.

Part 2: Five Concept Questions

Answer each out loud in about a minute, then open the model answer.

What happens, step by step, when PostgreSQL runs a SELECT?

Parse, rewrite (views), plan using statistics to pick scans and joins, then execute and return rows. The logical order is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. See How a Query Runs.

A query is slow in production but fast on your laptop. Why might that be?

Different data size and distribution, stale statistics, a missing index, parameter values with very different selectivity, or contention with other sessions. Compare EXPLAIN (ANALYZE) on production data. See Writing Fast Queries.

How would you design tables for orders, products and customers?

customers, products and orders tables, with order_items linking orders and products (quantity, price at the time), keys and foreign keys, NUMERIC money and CHECK constraints. See Data Modeling.

Two users buy the last item at the same moment. How do you avoid selling it twice?

Do it in one transaction with a conditional update (UPDATE inventory SET in_stock = in_stock - 1 WHERE product_id = ? AND in_stock > 0) and check the row count, or lock the row with SELECT ... FOR UPDATE. See Locks and Deadlocks.

How do you safely add a NOT NULL column to a table with 50 million rows?

Add it nullable or with a constant default (instant in PostgreSQL 11+), backfill in batches, then add the constraint NOT VALID and validate it separately, with a lock timeout. See Schema Migrations.

Your Score

ScoreWhat it means
17 to 20Interview-ready for most SQL rounds. Keep sharp with the SQL Problem Lab.
12 to 16Close. Redo the tasks you missed tomorrow without looking, and read the linked lessons.
Below 12Work through the SQL Query Puzzles and the SQL Level 3 Test first, then try again.

Was this tutorial helpful?