SQL · PRACTICAL GUIDE

SQL Top N Per Group

Return the highest or latest rows inside each business group.

Practice SQLLearning path

What this solves

Find the two most expensive quotes per material. This pattern is useful when the business question is clear but a generic tutorial is too abstract.

The rule

Use ROW_NUMBER or DENSE_RANK partitioned by the group.

WITH q AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY Material ORDER BY Price DESC) rn FROM Quotes)
SELECT * FROM q WHERE rn<=2;

Real-work checklist

  1. Define the business key and expected grain before writing the formula, query or markup.
  2. Test the pattern on a small known sample where you can verify the answer manually.
  3. Check missing values, duplicates and data types before trusting a large result.
  4. Scale to the real file or database only after the logic is proven.

Common mistake

A global TOP or LIMIT does not produce N rows per group.

Try it next