SQL QuestSQL Interview Questions › Window Functions

Busiest Merchants, and What a Tie Does to the Rank

MediumFreeQuerying BasicsWindow FunctionsJoinsAggregation & Grouping

RANK() and ROW_NUMBER() differ only when there is a tie — and this table has four of them. Three merchants sit on exactly 88 transactions. RANK() gives all three the number 10 and then jumps to 13. ROW_NUMBER() gives 10, 11, 12 and has to break the tie somehow — if you do not tell it how, the engine picks, and your answer changes between runs.

Count transactions per merchant and return merchant_id, name, txn_count, busy_rank (RANK() over txn_count descending — ties share a rank) and row_num (ROW_NUMBER() over txn_count descending, merchant_id ascending — always distinct). All 25 merchants. Order by txn_count descending, then merchant_id ascending.

Window functions run after the GROUP BY, so RANK() OVER (ORDER BY COUNT(*) DESC) is legal in the same SELECT that does the counting.

Solve it in the browser editor →

Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".

Schema

transactions

txn_idaccount_idamounttxn_atmerchant_idlatlngstatus
1149151.842026-03-04T12:39:39.078Z2440.342-74.4092completed
22110.722026-03-04T13:04:50.641Z752.936613.3229completed
335158.782026-03-04T13:27:15.528Z2552.739713.3134completed

merchants

merchant_idnamecategorycountryrisk_tier
1BigBox MartGroceryTRhigh
2Quick StopElectronicsJPhigh
3Aurora CafeTravelTRhigh

Expected output: 11 RideHail Inc 101 1 1; … 1 BigBox Mart 88 10 10; 8 Tech Den 88 10 11; 18 TrainHub 88 10 12; 6 Subscript Co 85 13 13; …

Hint

RANK() OVER (ORDER BY COUNT(*) DESC) AS busy_rank and ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC, m.merchant_id) AS row_num, both in the SELECT of a GROUP BY m.merchant_id, m.name query. The tiebreaker belongs inside ROW_NUMBER's OVER clause, not only in the final ORDER BY.

Concepts

SELECT Window Functions RANK ROW_NUMBER JOIN GROUP BY

Practise the topic: SQL practice questions · Window function practice · JOIN practice · GROUP BY exercises · Ranking function practice

In these company practice sets

Capital One · Stripe · Bloomberg

A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.

Related questions

Window Functions: ROW_NUMBERMedium · FreeMonth-over-Month Customer GrowthMedium · FreeRANK vs DENSE_RANK Side-by-SideMedium · FreeTop 3 Salary Tiers (DENSE_RANK)Medium · FreeMost Recent Order Per Customer (ROW_NUMBER)Medium · FreeSecond-Highest Earner Per Department (ROW_NUMBER)Medium · Free

Where would this cost you points in an interview?

Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.

Take the readiness test