Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonPractical

Write SQL to return the top N rows inside each category, team, or customer group.

Answer

Use a ranking window function partitioned by the group key and ordered by the metric, then filter the generated rank in an outer query. ROW_NUMBER returns exactly N rows per group, while RANK or DENSE_RANK can include additional tied rows depending on the business rule.

Strong answer includes

  • partitions ranking by group
  • chooses ROW_NUMBER versus RANK or DENSE_RANK deliberately
  • uses deterministic ordering when an exact row count is required

Practical example

Solution · Top N per group
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

Partition by the group, order by the metric, then filter the generated row number. Use RANK or DENSE_RANK when tied metric values should all qualify.

Expected result: Up to N rows per group, or more when the chosen rank function intentionally includes ties.

#sql#top-n#window-functions#ranking

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery