Third Highest Spender

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L4
Asked in
Amazon

Problem

Find the user with the third highest total spend across all transactions. If there is a tie, include all users sharing that rank. Show the user ID and total spend.

Bronze medal in spending.

Tables

transactions

Columns: transaction_id INTEGER, user_id INTEGER, product_id INTEGER, quantity INTEGER, total_amount REAL, transaction_date TEXT

transactions: 10 of 200 rows
transaction_iduser_idproduct_idquantitytotal_amounttransaction_date
10671971001223.462026-02-02
11342941050336.932026-03-03
12013911099450.42026-04-04
12684881148563.872026-05-05
13355851197002026-06-06
14026821246290.812026-07-07
146977912953104.282026-08-08
153687613444117.752026-09-09
160397313935-452026-01-10
1670107014421144.692026-02-11

customers

Columns: customer_id INTEGER, first_name TEXT, last_name TEXT, country TEXT

customers: 10 of 200 rows
customer_idfirst_namelast_namecountry
40089PriyaGuptaIndia
40178LucaRossiItaly
40267AvaNguyenVietnam
40356EthanJohnsonSpain
40445MariaGarciaChina
40534ChenWeiRussia
40623SofiaPetrovaIreland
40712LiamO'ConnorMexico
40801IsabellaMartinezCanada
40890NoahBrownFrance

Expected output

First 1 of 1 rows
user_idtotal_spend
87610134.6

Worked solution and explanation

Why this problem exists in real interviews

This is the classic Nth-highest value problem. Interviewers use it to test whether you know how to rank aggregated values with a window function and extract a specific position.


Break down the requirements

Step 1: Aggregate spend per entity

SUM(total_amount) grouped by the spender produces per-entity totals.

Step 2: Rank by total spend

DENSE_RANK() OVER (ORDER BY total_spend DESC) assigns positions. DENSE_RANK ensures tied values share the same rank.

Step 3: Filter to rank 3

Wrap in a subquery and filter WHERE rnk = 3 to extract the third-highest spender.


The solution

`DENSE_RANK` for Nth-position extraction
SELECT user_id, total_spend
FROM (
    SELECT
        user_id,
        SUM(total_amount) AS total_spend,
        DENSE_RANK() OVER (ORDER BY SUM(total_amount) DESC) AS rnk
    FROM transactions
    GROUP BY user_id
) ranked
WHERE rnk = 3

Common follow-up questions