First Among Equals

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

Problem

The merchandising team wants to see the products that move the most units, counting every unit across all of a product's orders. Return each product whose unit total matches the highest any product reached, showing how many orders it took and the units it moved.

When more than one product wears the crown, name every one of them.

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

products

Columns: product_id INTEGER, product_name TEXT, category TEXT, price REAL, rating REAL, in_stock INTEGER

products: 10 of 200 rows
product_idproduct_namecategorypriceratingin_stock
1001Basic Device 1XBooks17.522.71
1050Deluxe Bundle 2XClothing25.054.41
1099Pro Unit 3XHome & Kitchen32.582.11
1148Ultra Tool 4XCollectibles40.113.81
1197Essential Set 5XToys47.641.51
1246Classic System 6XBeauty03.21
1295Smart Gadget 7XAutomotive62.74.90
1344Eco Kit 8XGarden70.232.61
1393Turbo Pack 9XMusic77.764.30
1442Premium Widget 10XElectronics85.2921

Expected output

First 5 of 18 rows
product_nameorder_countunits_sold
Ultra Tool 4X210
Turbo Pack 9X210
Ultra Tool 14X210
Turbo Pack 19X210
Ultra Tool 24X210

Worked solution and explanation

What this really is

Strip the leaderboard costume off and this is an argmax that refuses to drop its ties. You total each product's units, then return every product sitting at the top total, not one arbitrary winner. Two things sink most attempts. First, ranking by the number of orders instead of units: on this data every product has the same order count, so a count can never separate them and the whole catalog ties. Second, reaching for 'sort descending, take the top row', which silently throws away the co-leaders. The correct shape is two passes: learn the winning total, then return everyone who hit it.

The naive answer and why it fails

Naive: LIMIT 1
GROUP BY product ORDER BY SUM(quantity) DESC LIMIT 1. It returns one product and looks right. The instant a second product ties on units, that product vanishes from the result with no error and no warning. You would ship a best-seller report that hides half the winners.
Correct: equal to the max
GROUP BY product, then HAVING SUM(quantity) = (the max unit total across all products). Every product at the peak survives, whether that is one product or fifty. The result is stable no matter how many share the lead.
All products tied at the top
SELECT p.product_name, COUNT(*) AS order_count, SUM(t.quantity) AS units_sold
FROM transactions t
JOIN products p ON t.product_id = p.product_id
GROUP BY p.product_id, p.product_name
HAVING SUM(t.quantity) = (
  SELECT MAX(units) FROM (
    SELECT SUM(t2.quantity) AS units
    FROM transactions t2
    JOIN products p2 ON t2.product_id = p2.product_id
    GROUP BY t2.product_id
  )
)

Total units per product, then a scalar max in HAVING keeps every co-leader.

Step 1: Total each product's units

Join to products on product_id for the name, group per product, and add up quantity for the unit total. COUNT(*) rides along as context: how many orders produced those units. Notice this is SUM(quantity), not COUNT(*): counting orders answers a different question, and here every product has the same order count, so a count could never rank them.

Step 2: Find the winning total as a scalar

The inner query repeats the same per-product unit total, then wraps it in MAX(units) to collapse all those totals into one number: the peak. It joins to products for the same reason the outer query does. Skip that join and the max is computed over product_ids that may not exist in the catalog, so the peak can belong to a product that never appears in the joined output, and nothing matches. It has to be its own aggregation because you cannot take MAX of an already grouped SUM in one level without a nested query.

Step 3: Keep only the products at the peak

HAVING SUM(quantity) = (that scalar) filters the grouped rows down to exactly the products sitting at the top. Ties survive naturally because equality does not care how many rows satisfy it. ORDER BY product_name then gives the stable alphabetical output the preview shows.

Common follow-up questions