SQL QuestSQL Interview Questions › Subqueries & CTEs

Recompute a Stale Counter

MediumFreeQuerying BasicsSubqueries & CTEsAggregation & Grouping

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_idnameemailsignup_datemembershiptotal_orders
1John Smithjohn.smith@email.com2023-01-15Gold15
2Emma Wilsonemma.wilson@email.com2023-03-20Silver8
3Michael Brownmichael.brown@email.com2023-02-10Gold12

orders

order_idcustomer_idproductcategoryquantitypricetotalorder_datecountrystatus
11Laptop ProElectronics11299.991299.992024-01-15USAcompleted
22Wireless MouseElectronics249.9999.982024-01-16Canadacompleted
33Office ChairFurniture1349.99349.992024-01-17USAcompleted

Expected output: 8 rows with recomputed counts, highest first

Hint

The hint for this one spells out most of the query, so it stays in the editor. Reach for 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

Department Roster with GROUP_CONCATMedium · FreeConsistent Director AnalysisMedium · FreeBelow Department AverageMedium · FreeHighest Total Salary Budget DepartmentMedium · FreeFare Imputation AnalysisMedium · FreeUNION ALL Dedup: Cross-Dataset SearchMedium · Free

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