Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top Users by Spend

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

Your question is Top Users by Spend. 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

The v4c.ai workspace team wants to identify its highest-spending users. Write a PostgreSQL query that calculates each user's total purchase spend and returns the top three users.

Requirements

  1. Join the user information to aggregated purchase data.
  2. Calculate total spend as the sum of each user's purchase amounts.
  3. Return the top three users, ordered by total spend descending.
  4. Use user_id as a deterministic tie-breaker when total spend is equal. Transactions with a NULL amount should not increase spend, and purchases that do not match a user should not appear in the result.

Schema

users
ColumnTypeDescription
user_idPKINTEGERUnique user identifier
user_nameVARCHAR(100)User's display name
purchases
ColumnTypeDescription
purchase_idPKINTEGERUnique purchase identifier
user_idINTEGERUser associated with the purchase
amountDECIMAL(10,2)Purchase amount
Tablesuserspurchases
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results