← Questions

Top three items per category in SQL

0
MetaCodingLast asked Aug 2025

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, rating for at most three items per category: higher rating first, and among equal ratings the lexicographically smaller content_id first.
  • Order the result by category ascending, then rating descending, then content_id ascending.

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_id is 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 rating be NULL, 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 filter rn <= 3.
  • The difference between ROW_NUMBER, RANK and DENSE_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, NULL ratings.

Follow-ups

  • Compute the rating first from an events table (views, likes) over the last 7 days.
  • Return the top k per category with k given 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

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