Programming

Use PostgreSQL Window Functions to Rank Rows Within Groups Without Losing Detail

Rank every row inside its group with `ROW_NUMBER()`, `RANK()`, or `DENSE_RANK()`—without collapsing the result to one row per group.

A common reporting problem is to find the top products in each category, the newest orders for each customer, or the highest-scoring entries in each team. A grouped aggregate can summarize each group, but it does not keep every source row available in the result. A PostgreSQL window function can calculate a position for each row while retaining the row’s other selected columns.

This tutorial builds a query that ranks products within categories, explains how ties affect the ranking, and shows how to filter for the top rows. The key distinction is that PARTITION BY defines the groups for the calculation; it does not combine those groups into one output row each.

The problem: rank rows without summarizing them

Suppose a table contains products and their prices:

CREATE TEMP TABLE products (
    product_id integer PRIMARY KEY,
    category   text NOT NULL,
    product_name text NOT NULL,
    price      numeric(10, 2) NOT NULL
);

INSERT INTO products (product_id, category, product_name, price) VALUES
    (1, 'Books', 'SQL Field Guide', 32.00),
    (2, 'Books', 'Query Patterns', 28.00),
    (3, 'Books', 'Data at Work', 32.00),
    (4, 'Games', 'River Tiles', 41.00),
    (5, 'Games', 'Moon Station', 35.00),
    (6, 'Games', 'Garden Paths', 35.00);

The task is to show each product, its price, and its position among products in the same category, ordered from most expensive to least expensive.

A GROUP BY category query is not the right tool for this result: grouping produces a summary per category, such as a maximum price or a count. It does not produce a rank alongside every product row. Instead, add a window expression to the selected columns:

SELECT
    product_id,
    category,
    product_name,
    price,
    ROW_NUMBER() OVER (
        PARTITION BY category
        ORDER BY price DESC, product_id
    ) AS position
FROM products
ORDER BY category, position;

The output has the original product details plus a calculated position. The OVER clause defines the set of rows the function considers. PARTITION BY category starts a separate calculation for each category. The ORDER BY inside OVER determines the order used to assign positions within each category.

The final ORDER BY category, position is separate: it controls how the complete query result is displayed. If you omit it, do not rely on the rows appearing in ranking order just because the window definition has an ORDER BY.

The calculation follows this path:

flowchart LR
    A["Product rows"] --> B["Partition by category"]
    B --> C["Order within category"]
    C --> D["Calculate row position"]
    D --> E["Keep product details"]

Each input row remains part of the result; the window calculation adds a value rather than replacing the rows with one aggregate per category.

1. Choose the ranking function

Three ranking functions are useful here, but they answer slightly different questions.

ROW_NUMBER(): assign a unique position to every row

Use ROW_NUMBER() when each row needs its own numbered position. If two products have the same price, the ORDER BY should include a tie-breaker when you need their order to be repeatable.

SELECT
    product_id,
    category,
    product_name,
    price,
    ROW_NUMBER() OVER (
        PARTITION BY category
        ORDER BY price DESC, product_id ASC
    ) AS row_num
FROM products
ORDER BY category, row_num;

The product_id tie-breaker makes the ordering criteria distinguish rows with equal prices. It does not imply that one tied product is genuinely more expensive; it simply makes the chosen sequence explicit. In this example, the lower ID comes first when prices tie.

If you order only by price DESC, equal-price rows are peers for that ordering. Their relative order is not specified by that expression. If a report depends on which tied row receives number 1, add a suitable, unique tie-breaker.

RANK(): preserve tied positions and leave gaps

Use RANK() when equal ordering values should receive the same rank and subsequent ranks should reflect the number of preceding rows. For the Books category, the two products priced at 32.00 both receive rank 1; the next product receives rank 3.

SELECT
    product_id,
    category,
    product_name,
    price,
    RANK() OVER (
        PARTITION BY category
        ORDER BY price DESC
    ) AS price_rank
FROM products
ORDER BY category, price_rank, product_id;

Notice that product_id appears in the final ordering, but not in the window ordering. That is intentional. Adding a unique ID to the window’s ORDER BY would make the two equal-price rows different peers, so they would no longer share a rank.

PostgreSQL describes rank() as returning the rank of the current row with gaps: it corresponds to the row number of the first row in that row’s peer group. This makes RANK() appropriate when tied values should share a position and later positions should leave space for those ties.

DENSE_RANK(): preserve ties without gaps

Use DENSE_RANK() when tied rows should share a rank, but the next distinct value should receive the next consecutive rank. The SQL changes only in the function name:

SELECT
    product_id,
    category,
    product_name,
    price,
    DENSE_RANK() OVER (
        PARTITION BY category
        ORDER BY price DESC
    ) AS price_rank
FROM products
ORDER BY category, price_rank, product_id;

For the Books prices, DENSE_RANK() assigns rank 1 to both products at 32.00 and rank 2 to the product at 28.00. RANK() instead assigns that last product rank 3. Both functions retain every product row; they differ in how they number the positions after ties.

As a practical choice, ask what “top three” means in the product requirement:

  • If it means exactly three rows per category, use ROW_NUMBER() and decide how ties are broken.
  • If it means all rows whose rank is three or better, use RANK() or DENSE_RANK() according to whether gaps matter.
  • If it means the three highest distinct price levels, use DENSE_RANK().

A tie can mean that a ranking query returns more than three rows when you filter to ranks 1 through 3. That is not an error; it follows from asking to preserve ties.

2. Return only the top rows in each group

A window result is calculated for rows in the query result, so a simple way to filter by its rank is to calculate it in a subquery and filter in the outer query. This returns the two highest-priced products per category, with ties broken by product_id so there are at most two rows per category.

SELECT
    product_id,
    category,
    product_name,
    price,
    row_num
FROM (
    SELECT
        product_id,
        category,
        product_name,
        price,
        ROW_NUMBER() OVER (
            PARTITION BY category
            ORDER BY price DESC, product_id ASC
        ) AS row_num
    FROM products
) AS ranked_products
WHERE row_num <= 2
ORDER BY category, row_num;

The inner query computes the row number while selecting the product details. The outer query applies the limit to that calculated number. Because the function partitions by category, the condition row_num <= 2 is applied to each category’s numbering, not once to the complete table.

For a tie-inclusive result, replace the inner ROW_NUMBER() with RANK() or DENSE_RANK() and filter the corresponding rank column. For example, DENSE_RANK() <= 2 returns every product in the two highest distinct price levels in each category. A category can therefore contribute more than two rows.

If the requirement is “the two highest rows, including every row tied at the second position,” RANK() <= 2 expresses that rule. Be careful: a tie at rank 1 means rank 2 may not exist, since RANK() leaves gaps. DENSE_RANK() <= 2 instead includes the two highest distinct price levels. Choose based on the intended business meaning, not simply on which function name looks familiar.

3. Keep ranking order separate from display order

The window’s ORDER BY and the query’s final ORDER BY serve different purposes. The window ordering establishes positions. The outer ordering arranges rows for the consumer.

For example, this query ranks by price within each category but displays the complete result from cheapest to most expensive:

SELECT
    product_id,
    category,
    product_name,
    price,
    RANK() OVER (
        PARTITION BY category
        ORDER BY price DESC
    ) AS price_rank
FROM products
ORDER BY category, price ASC, product_id;

The rank still reflects descending price. The output order does not change the rank calculation. Conversely, the window’s ordering does not promise that the final rows will be returned in that same order; use a query-level ORDER BY whenever presentation order matters.

A useful review habit is to read the two clauses independently:

  1. Inside OVER: Which rows belong to the same group, and what values determine their rank?
  2. At the end of the query: In what order should the result rows be returned?

4. Add a filter without accidentally dropping rows

A common mistake is to write a grouped aggregate when the requirement is to retain detail, or to select only the rank and forget the fields that identify the original row. Keep the detail columns in the ranked query, then filter the calculated rank in the outer query.

For instance, to find each category’s highest-priced product while preserving ties, use RANK():

SELECT
    product_id,
    category,
    product_name,
    price,
    price_rank
FROM (
    SELECT
        product_id,
        category,
        product_name,
        price,
        RANK() OVER (
            PARTITION BY category
            ORDER BY price DESC
        ) AS price_rank
    FROM products
) AS ranked_products
WHERE price_rank = 1
ORDER BY category, product_id;

If two products tie for the highest price, both rows have rank 1 and both are returned. If the requirement is instead exactly one winner per category, use ROW_NUMBER() with a deterministic tie-breaker. That is a product decision: choosing a single winner discards the tie as a tie, even though it retains the selected winner’s detail.

5. Adapt the pattern to real data

Replace products with your table, category with the grouping key, and price with the value to rank. A customer-order query, for example, can partition by customer and rank orders by creation time. A score report can partition by team and rank by score. The essential shape stays the same:

SELECT
    detail_columns,
    ranking_function() OVER (
        PARTITION BY group_column
        ORDER BY ranking_column DESC
    ) AS position
FROM your_table;

For repeatable ROW_NUMBER() results, extend the ordering with a column or combination of columns that distinguishes rows. For tie-preserving RANK() or DENSE_RANK(), do not add a unique tie-breaker to the window ordering if it would split values that should remain tied. You can still use extra columns in the query’s final ORDER BY to make display order stable.

Check the meaning of the ranking value before implementing it. Ranking by created_at DESC means newest first; ranking by price ASC means cheapest first. NULL values and the chosen sort direction can also matter in real tables. Decide explicitly whether nulls belong in the ranking and where they should appear, rather than assuming that an example’s non-null data covers that policy.

Common mistakes to avoid

  • Using GROUP BY when each source row must remain visible. Aggregation summarizes rows; a window function adds a calculation alongside rows.
  • Putting the grouping key only in the final ORDER BY. That sorts categories together but does not restart numbering for each category. Put the key in PARTITION BY.
  • Adding a unique key to a tie-preserving window order. That can split equal-value peers and make RANK() or DENSE_RANK() assign separate positions.
  • Assuming ROW_NUMBER() resolves ties according to an intended business rule. Include an explicit tie-breaker if a stable winner is required.
  • Expecting the window ordering to sort the final output. Add an outer ORDER BY for the returned row sequence.
  • Assuming “top N” always returns N rows. Rank-based filtering can return more than N rows when ties are included; ROW_NUMBER() with a tie-breaker gives an exact per-group count, subject to groups having enough rows.

The finished pattern

For an exact number of rows per group, calculate ROW_NUMBER() with a deliberate ordering and filter it in an outer query. For a ranking that treats equal ordering values as ties, choose RANK() when gaps after ties are meaningful or DENSE_RANK() when the next distinct value should receive the next consecutive rank.

In all three cases, PARTITION BY creates independent ranking groups, and the window function adds a ranking value without collapsing the selected detail rows. That is the core PostgreSQL pattern for ranking within groups while keeping the rows you need to inspect or return.

External Sources used for this article

Related Articles

View all →

Put it into practice

Related tools

All tools →