How do you rank entities by a metric within each group using window functions?

Last updated 13 July 2026

Rank within groups by combining a ranking window function with PARTITION BY: the partition restarts the ranking for each group, and the ORDER BY inside the window defines the metric direction. Choose the ranking function based on how ties should behave.

  • Core structure:

    • PARTITION BY group_col resets numbering per group.

    • ORDER BY metric DESC ranks the highest metric as 1 (use ASC for lowest-first).

  • Picking the function:

    • ROW_NUMBER() for a strict "top N per group" where exactly N rows are wanted.

    • RANK() or DENSE_RANK() when tied entities should share a position.

  • Filtering to top-N: Compute the rank in a CTE or subquery, then filter (window functions can't go in WHERE directly).

[lang:sql] WITH ranked AS ( SELECT dept, name, sales, RANK() OVER (PARTITION BY dept ORDER BY sales DESC) AS r FROM reps ) SELECT * FROM ranked WHERE r <= 3; -- top 3 reps per department

  • https://skphd.medium.com/sql-window-functions-interview-questions-and-answers-127ee0be483b
  • https://medium.com/@shreyassn/120-sql-interview-questions-db85e4304ffd
  • https://www.foundit.in/career-advice/20-common-sql-interview-questions-answers/
  • https://medium.com/@Ishan.tharusha.wijayabahu/top-50-essential-sql-interview-questions-for-software-engineers-in-2024-8da12396f199
  • https://interviewkickstart.com/blogs/interview-questions/sql-interview-questions
  • https://medium.com/data-engineer/recursive-ctes-in-sql-7b5dc666b16a
  • https://codewiz.info/blog/sql-common-table-expressions/
  • https://www.dbvis.com/thetable/a-complete-guide-to-the-mysql-cte-mechanism/
All Advanced SQL interview questions