Select one deterministic row from each group

Selecting the largest value in a group is different from selecting the complete row that contains it. MAX(Total) gives a number. It does not automatically identify the matching Id, and several rows can share that maximum.

Define the winner before writing the query. This example chooses the largest purchase for each customer and keeps the lowest purchase id when totals tie. It returns exactly one row per customer that has at least one purchase.

Make ties visible in the fixture

Ada has two purchases with the same highest total, ids 101 and 102. Lin's highest total belongs to id 202. The required output is therefore 101 / Ada / 25 and 202 / Lin / 12.

Each following query is complete and read-only. The first uses a window function, while the second is PostgreSQL's concise DISTINCT ON alternative. Run either independently. Neither relies on the order in which the fixture rows are written.

🔢ROW_NUMBER

Rank rows inside each customer

SQL
WITH Purchases(Id, Customer, Total) AS (
    VALUES (102, 'Ada', 25), (101, 'Ada', 25),
           (103, 'Ada', 18), (201, 'Lin', 9),
           (202, 'Lin', 12)
), Ranked AS (
    SELECT Id, Customer, Total,
           ROW_NUMBER() OVER (
               PARTITION BY Customer
               ORDER BY Total DESC, Id ASC
           ) AS PositionInGroup
    FROM Purchases
)
SELECT Id, Customer, Total
FROM Ranked
WHERE PositionInGroup = 1
ORDER BY Customer;

PARTITION BY restarts numbering for each customer. The window ordering determines the winner within that customer. The final ORDER BY determines the presentation of the selected winners. These are separate responsibilities.

A subquery or CTE is needed because the window result is not available to the same query block's WHERE clause. The fixture and this ranking query also run on modern SQLite. Other engines can use the same ranking idea while requiring different fixture syntax.

🐘DISTINCT ON

Use PostgreSQL DISTINCT ON

SQL
WITH Purchases(Id, Customer, Total) AS (
    VALUES (102, 'Ada', 25), (101, 'Ada', 25),
           (103, 'Ada', 18), (201, 'Lin', 9),
           (202, 'Lin', 12)
)
SELECT DISTINCT ON (Customer) Id, Customer, Total
FROM Purchases
ORDER BY Customer, Total DESC, Id ASC;

DISTINCT ON retains the first row for each listed expression. PostgreSQL requires those expressions to match the leftmost ordering expressions. The remaining ordering chooses which member comes first. This syntax is PostgreSQL-specific, so do not present it as a portable replacement for ROW_NUMBER.

Without the complete ordering, the chosen row is not predictable. With it, this query produces the same ids 101 and 202 as the ranking example.

Choose whether ties should survive

The unique Id tie-breaker intentionally selects one of Ada's equal purchases. If the requirement is to return every purchase tied for the highest total, rank by Total DESC alone with RANK and keep rank 1. Including Id in that rank would break the tie and defeat that requirement.

Decide how NULL totals should behave. A missing amount is not automatically the smallest amount, and default NULL ordering differs across engines. PostgreSQL can state NULLS LAST explicitly. Alternatively, exclude unknown totals before ranking if they are ineligible. The fixture uses non-null totals so neither policy is silently chosen for real data.

Filter at the intended stage

A filter inside Ranked changes the candidate purchases before selecting a winner. A filter outside it removes already chosen winners. For example, “largest eligible purchase” and “largest purchase, provided it is eligible” can produce different results.

Do not attach an arbitrary Id to GROUP BY Customer, MAX(Total). Joining an aggregate back to its source can return several tied rows, which may be correct but is a different contract. On large tables, inspect a plan for an index beginning with the grouping key followed by the ranking columns. The useful index depends on filters and workload, so the example makes no universal performance claim.

Source and further reading

This article addresses the problem raised by David Wolever in “Select first row in each GROUP BY group?” on Stack Overflow, licensed under CC BY-SA 4.0 . The question is the topic source. The explanations and examples here are newly authored from the database documentation, rather than reproduced from a community answer.

3.5. Window Functions
3.5. Window Functions # A window function performs a calculation across a set of table rows that are somehow related to …
https://www.postgresql.org/docs/current/tutorial-window.html
SELECT
SELECT SELECT, TABLE, WITH — retrieve rows from a table or view Synopsis [ WITH [ RECURSIVE ] with_query [, …
https://www.postgresql.org/docs/current/sql-select.html
Window Functions
https://sqlite.org/windowfunctions.html

Author: Herman Schoenfeld