Skip to main content

Command Palette

Search for a command to run...

LeetCode 586: Customer Placing the Largest Number of Orders

Solving LeetCode 586: Finding the Customer with Most Orders

Updated
2 min read
V

I'm Varchasv, a Data Engineer working on enterprise data integration.

Currently on a 90-problem challenge to level up my technical skills and switch to a more development-focused role.

What I'm doing:

  • Solving 2 Leetcode problems daily (SQL + DSA).
  • Blogging about each problem.
  • Building in public.

My Goal - Land a better data engineering role by mid-2026.

Follow my journey !!

Date: January 27, 2026
Category: SQL
Time Taken: minute
Difficulty: Easy


Problem Statement

Write a solution to find the customer_number for the customer who has placed the largest number of orders.

The test cases are generated so that exactly one customer will have placed more orders than any other customer.

Link: Customers Placing the Largest Number of Orders


My Approach

Solution 1 (Simpler, faster on small tables):

The simplest solution is to use GROUP BY on customer_number and then ORDER BY the count of order_number in descending order. This method is quick for smaller tables, but it doesn't scale well.


Solution Code:

SELECT customer_number 
FROM Orders
GROUP BY customer_number
ORDER BY COUNT(order_number) DESC
LIMIT 1

Solution 2 (Complex, More Scalable):

A more scalable and flexible alternative is to use Window Functions. We can use two CTEs to get the count of order_number and calculate the rank based on these counts in descending order. Finally, we select the customer_number where the rank is 1.

Solution Code:

WITH customerTotals AS (
    SELECT 
        customer_number, 
        COUNT(order_number) AS order_total
    FROM Orders
    GROUP BY customer_number
),
rankedCustomers AS (
    SELECT 
        customer_number, 
        order_total, 
        DENSE_RANK() OVER(ORDER BY order_total DESC) AS rnk
    FROM customerTotals
)

SELECT customer_number
FROM rankedCustomers
WHERE rnk = 1

Key Takeaway: We can use any aggregate functions in the ORDER BY statement.

Pattern: Grouping | Window Functions

Mistakes I Made: In the first solution, I didn't know that we could use COUNT() in the ORDER BY statement.

Series: 90 Days of Data Engineering Progress: 21/90 problems completed

Tags: #DEQuest #LeetCode #SQL #DataEngineering #BuildInPublic

90 Days of Data Engineering

Part 22 of 48

Solving 90 problems over 18 weeks. Daily posts Mon-Fri. Goal: Switch to development role.

Up next

LeetCode 206: Reverse Linked List

How to Solve LeetCode 206: Reverse Linked List Problem