SQL Guide · Prompt: “Return top deals ordered by revenue descending from the pipeline table”

Select Top N Rows Per Group in SQL with ROW_NUMBER()

Verified by LiveFormulaLab Engineering Team • Updated November 2026

Retrieve the top 3 highest deals or latest orders per category in SQL using ROW_NUMBER() OVER (PARTITION BY). Full guide and examples.

Verified SQL Syntax

SELECT account, segment, revenue
FROM pipeline
ORDER BY revenue DESC
LIMIT 3;

How This Formula Works (Step-by-Step)

When you need the top N items inside each group (such as the top 2 deals per sales segment), rank rows inside a CTE with ROW_NUMBER() OVER (PARTITION BY segment ORDER BY revenue DESC) and filter WHERE rn <= 2.

Step 1: Partition by the grouping column (segment) and sort descending by metric (revenue).

Step 2: Filter the outer query to keep only the top N ranked rows per partition.

Formula Syntax & Arguments Breakdown

Ranks rows inside each group via ROW_NUMBER() / DENSE_RANK() OVER (PARTITION BY segment ORDER BY revenue DESC) or sorts and caps top records with ORDER BY + LIMIT.

Argument / ClauseRequirementData TypeRole & Behavior
PARTITION BY segmentRequiredWindow PartitionSplits the dataset into independent ranking buckets (one per Segment, Category, or Region).
ORDER BY revenue DESCRequiredSort OrderPlaces the largest revenue or score at rank #1 inside each bucket.
LIMIT 3 / WHERE rn <= 3RequiredTop-N CapRetains only the top N ranked rows globally or per partition.

3 Real-World Use Cases

  • Fetching the most recent login event for every active customer.
  • Highlighting the top 3 highest-grossing products in each retail category.
  • Selecting the latest status update per support ticket.

Cross-Platform Equivalents

Excel
=TAKE(SORT(A2:C6, 3, -1), 3)
SQL
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY segment ORDER BY revenue DESC) AS rn FROM pipeline) SELECT * FROM ranked WHERE rn <= 2;
Python Pandas
df.sort_values('revenue', ascending=False).groupby('segment').head(2)

Common Mistakes & Pro Tips

Pitfalls & How to Fix Them

  • Mistake: Confusing ROW_NUMBER(), RANK(), and DENSE_RANK() produces unexpected extra or missing rows on tied values.

    Fix: Use ROW_NUMBER() for strictly N rows per group (with a deterministic tiebreaker), or DENSE_RANK() when ties should share a spot.

  • Mistake: Using SELECT ... WHERE ROW_NUMBER() OVER (...) <= 3 in the same query throws a SQL error.

    Fix: Compute the rank inside a CTE (WITH ranked AS (...)), then filter WHERE rn <= 3 in the outer query (or use QUALIFY in Snowflake/BigQuery/DuckDB).

  • Mistake: NULL values sort FIRST in PostgreSQL ORDER BY revenue DESC unless handled explicitly.

    Fix: Specify ORDER BY revenue DESC NULLS LAST so empty rows never steal top spots.

Engineering Pro Tips

  • In Snowflake, BigQuery, and DuckDB, the QUALIFY ROW_NUMBER() OVER (PARTITION BY segment ORDER BY revenue DESC) <= 3 clause eliminates the wrapper CTE.
  • In PostgreSQL, use DISTINCT ON (segment) ... ORDER BY segment, revenue DESC as an ultra-fast shortcut for Top-1 per group.
  • Create a composite index on (segment, revenue DESC) for instant Top-N queries on multi-million-row tables.

Frequently Asked Questions

Should I use ROW_NUMBER(), RANK(), or DENSE_RANK()?
Use ROW_NUMBER() when you want strictly N rows per group even on ties; use DENSE_RANK() to include tied scores.
Why do I need a CTE or subquery around ROW_NUMBER()?
SQL evaluates WHERE before window functions, so you must wrap the window function in a CTE before filtering rn <= N.
Does Postgres have a shortcut for Top 1 per group?
Yes: SELECT DISTINCT ON (segment) * FROM pipeline ORDER BY segment, revenue DESC.

Related Formulas & Guides