Count Orders Per Customer
Easy
SQLGROUP BYCOUNT
Problem
Schema: Orders(id INT, customer_id INT, total DECIMAL).
For each customer_id, return the customer and their order count, ordered by count desc.
Example 1
Input: orders: (1,7,...), (2,7,...), (3,8,...)
Output: (7, 2), (8, 1)
Constraints
- A customer can have zero rows; only customers with ≥ 1 order appear here.
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
SQL
SELECT customer_id, COUNT(*) AS order_count
FROM Orders
GROUP BY customer_id
ORDER BY order_count DESC, customer_id;
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Count Orders Per Customer interactively → ← All solutions