← Questions
Top three items per category in SQL
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Aug 2025. It tests sql, window functions and data engineering.
A table holds content items, each with a category and an integer rating. Write a query that returns, for each category, its top three items by rating, with a deterministic rule for ties.
Interface
Unless you agree on a different schema with the interviewer, assume:
-
items(content_id VARCHAR(20), category VARCHAR(50), rating INT), one row per item. - Return
category, content_id, ratingfor at most three items per category: higher rating first, and among equal ratings the lexicographically smallercontent_idfirst. - Order the result by
categoryascending, thenratingdescending, thencontent_idascending.
Example
items
content_id | category | rating
c1 | news | 90
c2 | news | 75
c3 | news | 90
c4 | news | 60
c5 | news | 75
v1 | video | 40
result
category | content_id | rating
news | c1 | 90
news | c3 | 90
news | c2 | 75 # c2 beats c5 on content_id
video | v1 | 40 # a category with fewer than three items keeps them all
Constraints
- Every item has exactly one category;
content_idis unique. - Exactly three rows per category when it has at least three items.
Clarifying questions
- On ties, do you want exactly three rows per category, or every item that ties for third place?
- Can
ratingbeNULL, and where should those items rank? - Is "engagement" a single column, or must I aggregate it from an events table first?
- Which SQL dialect, and are window functions available?
What a strong answer covers
- A CTE with
ROW_NUMBER() OVER (PARTITION BY category ORDER BY rating DESC, content_id ASC)and a filterrn <= 3. - The difference between
ROW_NUMBER,RANKandDENSE_RANK, and what each returns on the tie at third place. - Why the filter goes in an outer query: window functions cannot appear in
WHERE. - An alternative without window functions (a correlated subquery counting better items) and its cost.
- Tests: ties at the cut, a category with one item,
NULLratings.
Follow-ups
- Compute the rating first from an events table (views, likes) over the last 7 days.
- Return the top
kper category withkgiven as a parameter. - The same in Python over a list of rows, in
O(n log k)per category with a heap.
Where it's asked
- Meta · AI-enabled coding · Last asked Aug 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
sql · window functions · data engineering
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
