0
0
SQLquery~5 mins

Top-N per group query in SQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a Top-N per group query in SQL?
It is a query that finds the top N rows for each group in a table, like the top 3 salespeople per region.
Click to reveal answer
beginner
Which SQL function is commonly used to assign ranks for Top-N per group queries?
The ROW_NUMBER() function assigns a unique rank number to each row within a group, helping to select the top N rows.
Click to reveal answer
intermediate
How do you limit results to the top 3 rows per group using ROW_NUMBER()?
Use ROW_NUMBER() OVER (PARTITION BY group_column ORDER BY sort_column DESC) and then filter WHERE row_number <= 3.
Click to reveal answer
intermediate
Why is PARTITION BY important in Top-N per group queries?
PARTITION BY divides the data into groups so the ranking function restarts for each group, allowing top N per group selection.
Click to reveal answer
intermediate
Can you use LIMIT or FETCH FIRST directly to get Top-N per group?
No, LIMIT or FETCH FIRST applies to the whole result set, not per group. You need ranking functions like ROW_NUMBER() for per group limits.
Click to reveal answer
Which SQL clause is used to restart row numbering for each group in a Top-N per group query?
AGROUP BY
BPARTITION BY
CORDER BY
DWHERE
What does ROW_NUMBER() do in a Top-N per group query?
AAssigns a unique rank number to each row within its group
BCounts total rows in the table
CFilters rows based on a condition
DGroups rows by a column
How do you select the top 5 rows per group after using ROW_NUMBER()?
ALIMIT 5
BGROUP BY row_number
CWHERE row_number <= 5
DORDER BY row_number DESC
Which of these is NOT a correct way to get Top-N per group in SQL?
AUsing LIMIT without partitioning
BUsing RANK() with PARTITION BY
CUsing DENSE_RANK() with PARTITION BY
DUsing ROW_NUMBER() with PARTITION BY
What is the purpose of ORDER BY inside ROW_NUMBER() OVER()?
ATo limit the number of rows returned
BTo group rows by a column
CTo filter rows after ranking
DTo define how rows are ranked within each group
Explain how to write a SQL query to get the top 3 highest salaries per department.
Think about dividing data by department and ranking salaries.
You got /3 concepts.
    Describe why LIMIT alone cannot be used to get Top-N per group in SQL.
    Consider how LIMIT works on the entire query output.
    You got /3 concepts.