SQL Quest › SQL Interview Questions › Subqueries & CTEs
Recompute a Stale Counter
The total_orders column on customers is a cached counter, and it has drifted out of sync with the actual orders table — a very common real-world bug.
Recompute it: set each customer's total_orders to their real number of rows in orders. Then show customer_id, name, total_orders for the top 8, ordered by total_orders descending, then customer_id.
The new idea is a correlated subquery inside SET: (SELECT COUNT(*) FROM orders o WHERE o.customer_id = customers.customer_id) runs once per customer row, and the reference to the outer customers.customer_id is what correlates it.
Watch what happens to customers with no orders at all — COUNT(*) over zero matching rows returns 0, not NULL, so they correctly land on 0. That is a happy accident of COUNT; had you used SUM, those rows would have gone NULL and quietly broken the column.
Solve it in the browser editor →
Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".
Schema
customers
| customer_id | name | signup_date | membership | total_orders | |
|---|---|---|---|---|---|
| 1 | John Smith | john.smith@email.com | 2023-01-15 | Gold | 15 |
| 2 | Emma Wilson | emma.wilson@email.com | 2023-03-20 | Silver | 8 |
| 3 | Michael Brown | michael.brown@email.com | 2023-02-10 | Gold | 12 |
orders
| order_id | customer_id | product | category | quantity | price | total | order_date | country | status |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 1 | Laptop Pro | Electronics | 1 | 1299.99 | 1299.99 | 2024-01-15 | USA | completed |
| 2 | 2 | Wireless Mouse | Electronics | 2 | 49.99 | 99.98 | 2024-01-16 | Canada | completed |
| 3 | 3 | Office Chair | Furniture | 1 | 349.99 | 349.99 | 2024-01-17 | USA | completed |
Expected output: 8 rows with recomputed counts, highest first
Hint
UPDATE, DML, Correlated Subquery, and open the hint there if you stall.Concepts
UPDATE DML Correlated Subquery Aggregation
Practise the topic: SQL practice questions · CTE practice · GROUP BY exercises
Related questions
Where would this cost you points in an interview?
Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.
Take the readiness test