All articles

KajoData / SQL

Latest record per customer in SQL: ROW_NUMBER and ties

I show how to select each customer's complete latest order, resolve ties and place filters so a marketing list answers the question you actually intended.

Kajo RudzińskiPublished 8 min read

Three tracks of order cards feed a mechanism selecting one complete card from each group.

Marketing wants customers who haven’t bought anything recently, with the date and amount of their latest order. I could group by customer and find the maximum date. But that still leaves a question: which order amount belongs beside it?

My approach is to number each customer’s orders from newest to oldest and keep the first one. I’ll use PostgreSQL 18 syntax and a small synthetic dataset. The useful part goes beyond the function: I want to make the tie-breaking rule explicit and avoid a filter that quietly changes the meaning of the list.

Define what the latest order actually means

The starting point is one customer with many orders and a requested output of one row per customer. Before writing SQL, I clarify the date. Does marketing mean the order was placed, paid or fulfilled? Those describe different events. A convenient column name cannot settle that business question.

For this example, zamowienia is an orders table with exactly one row per order. The Polish column names match the source material: klient_id identifies a customer, zamowienie_id identifies an order, data_zamowienia is its purchase date and kwota is the order amount. Order IDs are unique and non-null. Initially, customer IDs and dates are also non-null, and amounts share one currency.

klient_id zamowienie_id data_zamowienia kwota
1 101 2026-01-10 100
1 102 2026-02-10 60
1 103 2026-02-10 80
2 201 2026-01-12 50
2 202 2026-03-01 40

Customer 1 has two purchases on the latest date, February 10. I need a rule for choosing between them. For now, I agree to use the larger order ID when dates tie. That makes the intended answer clear enough to check by reading the table.

Grouping by customer and taking the maximum date gives one date per customer. Under PostgreSQL’s grouping rules, I cannot simply attach an arbitrary unaggregated amount. Taking the maximum amount answers a different question. Here, customer 1’s largest purchase is 100, while the chosen latest purchase is worth 80. Combining those maxima would describe an order that never happened.

Number complete rows within each customer

ROW_NUMBER() assigns consecutive numbers beginning at one within each partition. This is the behavior described in the window function reference. My partition is a customer, so numbering restarts for the next customer.

I read the expression from the inside out. PARTITION BY klient_id defines the separate queues. ORDER BY data_zamowienia DESC, zamowienie_id DESC decides which order stands at the front. ROW_NUMBER() then assigns each row its position. I call the resulting column rn.

SELECT
    klient_id,
    zamowienie_id,
    data_zamowienia,
    kwota,
    ROW_NUMBER() OVER (
        PARTITION BY klient_id
        ORDER BY data_zamowienia DESC, zamowienie_id DESC
    ) AS rn
FROM zamowienia;

At this stage, I keep the orders and their amounts. The extra column describes a position; it hasn’t removed any purchase yet. I like inspecting this intermediate result because it exposes exactly which row would win before the final filter hides everything else.

For customer 1, the intended sequence of order IDs is 103, 102, 101. For customer 2, it is 202, 201. The rows numbered one therefore carry IDs 103 and 202. I can derive that expectation directly from the dates and the agreed tie-breaker without executing the example.

The grouping key deserves the same care as the ordering key. If customer identifiers are only unique within a company, a company identifier would also belong in the partition. Otherwise, separate people’s histories could enter the same queue. I establish the key from the data model rather than guessing from a familiar column name.

Filter the number in an outer query

Now I want rn = 1. In PostgreSQL, window calculations logically happen after WHERE, so I cannot filter this window result at the same query level. The PostgreSQL tutorial explains that order of processing. I discuss the broader sequence in my article on SQL’s logical query order.

I split the work into two readable steps. The WITH block assigns positions; the outer query selects the winning order. The CTE documentation describes this way of breaking a query into named parts. I don’t assume that giving the step a name creates a separate permanent table.

WITH ranking AS (
    SELECT
        klient_id,
        zamowienie_id,
        data_zamowienia,
        kwota,
        ROW_NUMBER() OVER (
            PARTITION BY klient_id
            ORDER BY data_zamowienia DESC, zamowienie_id DESC
        ) AS rn
    FROM zamowienia
)
SELECT klient_id, zamowienie_id, data_zamowienia, kwota
FROM ranking
WHERE rn = 1
ORDER BY data_zamowienia, klient_id;

The expected output has customer 1 with order 103 and amount 80, and customer 2 with order 202 and amount 40. Each output row preserves a complete purchase. Its date and amount come from the same source record.

The final ordering serves a different purpose from the ordering inside the window. Inside, I decide who wins. Outside, I decide how marketing sees the list. Here, older last purchases come first. If the recipient wanted customers listed by ID, I would change the final ordering while preserving the selection rule.

Make ties an explicit decision

Two purchases on one day can be perfectly valid. ROW_NUMBER() still gives them separate positions. If I order only by date, I have no guarantee about which tied row receives position one. An answer that happens to look right today leaves that decision unresolved.

Adding the order ID makes the choice unambiguous under my unique-ID assumption. If the table instead contained order lines, one order ID could appear several times. I would need to revisit the promise of one row per order before trusting the ranking. Adding sorting columns cannot repair a misunderstanding about what a row represents.

The larger order ID is an agreed tie-breaker here. It does not establish that the purchase happened later. If the business needs the actual event sequence, I look for a more precise timestamp or a reliable event sequence. Repeatability and business meaning are separate requirements that the final rule needs to satisfy together.

If marketing wants every purchase on the latest date, selecting exactly one row would discard relevant information. RANK() ordered by date alone is worth considering because tied rows share a position, as the ranking reference explains. I first settle the expected output, then choose the function that expresses it.

Two parallel card tracks meet at a mechanism that resolves a tie.

Put filters on the correct side of the ranking

Suppose marketing wants customers whose latest purchase was before March 1, 2026. For that question, I first choose the last order across the relevant history. Only then do I apply the date condition in the outer query.

-- Final query after the same WITH block:
SELECT klient_id, zamowienie_id, data_zamowienia, kwota
FROM ranking
WHERE rn = 1
  AND data_zamowienia < DATE '2026-03-01'
ORDER BY data_zamowienia, klient_id;

Customer 1 remains. Customer 2 bought on March 1 and is excluded. If I filtered out recent orders before ranking, order 202 would disappear first. January order 201 would become that customer’s latest visible order, incorrectly placing customer 2 on the campaign list.

The wording of the question determines the location of the filter. For “latest paid order,” I restrict the input to paid purchases. For “latest order, provided it is paid,” I select the latest order first and inspect its status afterward. Those requests can produce different answers. Writing both in plain language helps me spot the distinction before rearranging SQL clauses.

This also matters when someone proposes a smaller date range to make the query easier to work with. Restricting history changes what “latest” can mean. I want that scope documented and accepted rather than hidden inside a convenient source filter.

Handle missing dates and customers with no orders

So far, dates have been present. For real data, I want to understand what a missing date means. PostgreSQL’s default descending order places nulls first. If unknown dates should follow known dates, I can write data_zamowienia DESC NULLS LAST. The sorting documentation confirms this behavior.

That still leaves customers whose dates are all unknown. The next ordering key can select a record technically, but I cannot honestly describe it as the most recent purchase. I’d flag that case for clarification rather than conceal uncertainty behind a precise order number.

An orders table also cannot represent customers who have never bought anything. If marketing needs those people too, I need a separate customer list and a join to the selected orders. This is where a LEFT JOIN becomes useful. No purchase and an old purchase are different situations, so I keep their interpretation explicit.

Check the cases that could change the campaign

Before handing over the list, I write down the expected rows for a customer with one purchase, several dates and a tie. I also include someone with a recent order who must be excluded. That last case exposes a date filter placed too early, even when the rest of the output looks convincing.

Alongside the result, I keep the date definition, history scope and tie-breaking rule. The next person can then explain why a particular amount was selected. “Latest order” is a short label for several decisions that deserve to remain visible.

The same pattern can select a document’s latest status, a product’s latest price or a user’s latest login. Each time, I define the group and the event order again. Start with three groups from your own history table and identify the intended winner by hand. Any tie you cannot resolve gives you a concrete question for the process owner before the query enters a report.

Key takeaways

Why doesn't MAX of the date return the entire latest order?

MAX finds the greatest date value in a group. It does not select the remaining columns from the row carrying that date. I use row numbering to select a complete record.

How do I choose one order when dates tie?

I add an agreed tie-breaker, such as zamowienie_id DESC. The choice is unambiguous when the full set of ordering keys distinguishes the rows. A larger ID does not necessarily mean a later event.

Should I filter dates before applying ROW_NUMBER?

That depends on the question. To find the latest purchase across the relevant history, I rank that history first. I then check whether the selected purchase is old enough for the campaign.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.