Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top Customers SQL Query

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Top Customers SQL Query. Start with the requirements and the two tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Google Cloud Marketplace needs a customer leaderboard based on completed orders. Write a PostgreSQL query that identifies the five customers with the greatest completed-order spending.

Requirements

  1. Return each customer's customer_id, customer_name, and total completed-order value as total_spent.
  2. Include customers without completed orders, treating their total as zero.
  3. Exclude cancelled and refunded orders from the spending calculation.
  4. Sort by total spending descending, use customer_id ascending as a deterministic tie-breaker, and return only five rows.

Schema

customers
ColumnTypeDescription
customer_idPKINTUnique customer identifier
customer_nameVARCHAR(100)Customer display name
orders
ColumnTypeDescription
order_idPKINTUnique order identifier
customer_idINTCustomer associated with the order
order_statusVARCHAR(20)Current order status
order_totalNUMERIC(10,2)Order value in USD
Tablescustomersorders
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results