Orders per User in One Report
The report currently recounts orders separately for every user, which scales poorly on larger data. Rewrite it as one set-based calculation: every user must remain in the result, even with no orders. Return id and orders_count, sorted by id.
Original query
SELECT u.id, (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS orders_count FROM users u ORDER BY u.id
Expected output sample
This is what a correct answer looks like — its row count is its own, it doesn't have to match the schema tables.
| id | orders_count |
|---|---|
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
Sign in to see submission history
Sign inSign in to use AI Mentor
Sign in