SQL Interview & Case Lab
Back to Business SQL Patterns

Top-N per Group — The RANK / ROW_NUMBER Trap

The single most-asked SQL interview question — with the three subtle wrong-answer traps. FIND_VIDEO: search 'SQL top N per group ROW_NUMBER RANK' — recommended channel: LearnSQL. Aim for 10 min or under.

18 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Ranking Functions Intro — Explains conceptual differences between RANK, DENSE_RANK, and ROW_NUMBER.
  2. Evaluating Gap Behavior in RANK — Demonstrates how duplicate gross revenue values cause rank skipping in SQL Server.
  3. Applying DENSE_RANK and ROW_NUMBER — Compares contiguous dense ranking and distinct row numbering on identical dataset lines.
  4. Ranking on Aggregated Data — Embeds sum aggregations inside window ranking clauses alongside GROUP BY operations.
  5. Partitioned Ranking by Geography — Joins geography dimensions and partitions city gross revenue rankings within each state.
  6. Multi-table Brand Ranking Slices — Joins the item dimension to analyze brand performance partitions across state markets.
PDF notes

Frequently asked questions

Why does RANK() jump from 1 to 83 in duplicate line items?

Because 82 rows share the first rank position. RANK() calculates the next rank as the previous rank plus the count of tied records.

Can window ranking functions accept column arguments inside their parentheses?

No. Functions like RANK(), DENSE_RANK(), and ROW_NUMBER() do not take arguments; ordering expressions are specified inside OVER(ORDER BY ...).

What happens if PARTITION BY is omitted from a ranking query?

The entire result set is treated as a single partition, ranking all rows globally across the whole table.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.