Keep the latest row

Part of the free LogicWiz Data Engineering course, Module 2: SQL for pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 9:20 on Wednesday, and Tess's dashboard says SwiftKart has 150 orders. The shop took 80. Every night the shop sends a file of the orders that were created or changed that day, and you append it to a landing table, stg_orders. Most orders are in there two or three times, and order 1012 says both placed and shipped.

You'll learn to

  • Explain where repeated rows come from: versions, retries, re-sent files
  • Keep one row per key with ROW_NUMBER, and choose the survivor
  • Add a tie-breaker so every run gives the same result
  • Say what the dedup costs, and how an index removes the sort

Learn

One order, three rows

Start with one order. The next card shows every row the landing table holds for order 1012.

You will see three. One says placed. Two say shipped, and those two are the same down to the second.

Nothing is broken in the load. The shop's export sends an order again whenever it changes, and one night a file was delivered twice. The landing table did what a landing table should: it kept everything it was sent.

The dashboard is the problem. It counts landing rows and calls them orders.

Order 1012 in the landing table

SELECT order_id, status, updated_at, file_name, loaded_at
FROM stg_orders
WHERE order_id = 1012
ORDER BY updated_at, loaded_at;

Three rows: the placed version, the shipped version, and the same shipped version again from the retried file.

Versions and copies

Repeats in raw data are normal, and they come in two kinds.

Versions: the source sends a row every time it changes. Order 1012 arrived as placed on 2 June and again as shipped on 3 June. Both rows are true. Only one is current.

Copies: the same row delivered twice. The 3 June file failed half-way and was sent again, so its rows landed twice. Message systems do the same: most deliver "at least once", so a message can arrive twice.

The raw landing table should keep everything, because you may need it later. The table people query should have one row per order: the latest version.

How order 1012 landed three times

Three nightly files each put one row for order 1012 into the landing table: a placed version from the 2 June file, a shipped version from the 3 June file, and the same shipped version again from the retried 3 June file.

Follow each arrow from a file to the row it added: the blue row is a version, the two amber rows are copies of each other.

Rows against orders

SELECT COUNT(*) AS landing_rows,
       COUNT(DISTINCT order_id) AS orders
FROM stg_orders;

150 landing rows, 80 orders. The habit from Module 1: when COUNT(*) and COUNT(DISTINCT key) differ, the key repeats.

Number the versions, keep number 1

Removing repeats is called deduplication, or dedup for short. The fix reuses ROW_NUMBER from Lesson 2.3. Give every row a number within its order, newest first. Then keep the rows numbered 1.

ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC, loaded_at DESC)

  • PARTITION BY is the key that must end up unique: one window per order.
  • ORDER BY decides who wins inside the window: the latest updated_at, and among exact copies, the one loaded last.

An outer query then filters rn = 1. It is top-N per group with N = 1. This is the most common pattern in data engineering SQL, and the most common interview question.

Order 1012: three rows become one

The three landing rows of order 1012 are sorted newest first, the tie between the two shipped rows is broken by load time, the rows are numbered 1 to 3, and only number 1 is kept.

  1. As landed. Three rows for one order, in the order they arrived. PARTITION BY order_id puts them in one window.

  2. Newest first. ORDER BY updated_at DESC moves the two shipped rows to the top. They tie: the same updated_at, to the second.

  3. Break the tie. loaded_at DESC puts the copy that was loaded last on top. Now the order is fixed, and ROW_NUMBER writes 1, 2, 3.

  4. Keep number 1. The outer query keeps rn = 1: one row for order 1012, and it says shipped.

Watch the two amber rows: they are equal on updated_at, and only the tie-breaker decides which one becomes number 1.

The trap: two small slips. ORDER BY updated_at without DESC keeps the oldest version, so every order looks placed. And without a tie-breaker the survivor is random when two rows share a timestamp: the job passes its tests today and returns a different row next week. Always end the ORDER BY with something unique.

Keep the latest version of every order

WITH ranked AS (
  SELECT *,
         ROW_NUMBER() OVER (
           PARTITION BY order_id
           ORDER BY updated_at DESC, loaded_at DESC
         ) AS rn
  FROM stg_orders
)
SELECT order_id, customer_id, status, updated_at
FROM ranked
WHERE rn = 1
ORDER BY order_id;

80 rows, one per order, each with its latest status. Check the count every time you dedup.

Remember: PARTITION BY the key that must be unique, ORDER BY newest first with a tie-breaker, keep rn = 1. Then check that COUNT(*) equals COUNT(DISTINCT key).

The ORDER BY is a business rule

Which row wins is not a technical detail. Decide it with the people who use the table, and write it down.

For orders, "latest updated_at wins" is natural. For customers it is less obvious. Maya Chen signed up three times with one email: accounts 2, 12 and 29. Do you keep the earliest account, the one with the most orders, or the most recently updated one?

"Earliest sign-up, then lowest id" keeps account 12, which has never ordered. That may be fine. It may surprise finance. Either way it should be a choice, not an accident.

A different rule: one customer per email, earliest wins

SELECT email, customer_id, signup_date
FROM (
  SELECT email, customer_id, signup_date,
         ROW_NUMBER() OVER (
           PARTITION BY email
           ORDER BY signup_date, customer_id
         ) AS rn
  FROM customers
  WHERE email IS NOT NULL
) ranked
WHERE rn = 1
ORDER BY email;

27 rows: one per email. Customers with no email cannot be matched this way, so they are left out on purpose, and a real pipeline would report them.

Why not DISTINCT or MAX?

Two shortcuts look tempting. Neither works.

SELECT DISTINCT removes rows that are identical in every column. The retried rows differ in file_name and loaded_at, and the versions differ in status, so nearly all of them survive.

GROUP BY order_id with MAX(updated_at) gives you the latest time, not the latest row. To get the status you must join back on (order_id, updated_at), and an exact copy then returns two rows again.

Postgres and DuckDB also have DISTINCT ON (order_id) ... ORDER BY order_id, updated_at DESC, a neat shortcut that most other engines lack. ROW_NUMBER works in Postgres, DuckDB, Spark, Snowflake and BigQuery alike.

The same dedup in DuckDB, on the daily files

import duckdb

raw = duckdb.sql("SELECT COUNT(*) FROM read_csv_auto('landing/orders/*.csv')").fetchone()[0]
latest = duckdb.sql("""
    SELECT order_id, status, updated_at
    FROM read_csv_auto('landing/orders/*.csv', filename = true)
    QUALIFY ROW_NUMBER() OVER (
        PARTITION BY order_id
        ORDER BY updated_at DESC, filename DESC
    ) = 1
""")
print("landed rows:", raw)
print("orders after dedup:", latest.count("*").fetchone()[0])

The same pattern on the raw daily files, with DuckDB's QUALIFY. filename = true adds each row's source file as a column, which makes a handy tie-breaker for copies: here the retry file sorts after the original. latest.count("*") counts the rows of the deduplicated result.

Under the hood: the sort is the job

Now the cost. The plan has three steps.

A Sort orders every row by order_id, updated_at DESC, loaded_at DESC: the PARTITION BY column, then the window's ORDER BY. A WindowAgg walks the sorted rows and numbers each order's versions. A filter keeps rn = 1.

The Run Condition from Lesson 2.3 helps here too. Once an order's row number passes 1, the rest of its versions are skipped, so the WindowAgg passes up 80 rows, not 150.

The Sort is almost the whole cost. It runs in memory up to work_mem, then spills to temporary files as an external merge. DISTINCT ON runs the very same Sort with a Unique step on top. For 2 billion landing rows, that sort is the job.

The dedup plan, and DISTINCT ON

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, status
FROM (
  SELECT order_id, status,
         ROW_NUMBER() OVER (
           PARTITION BY order_id
           ORDER BY updated_at DESC, loaded_at DESC
         ) AS rn
  FROM stg_orders
) ranked
WHERE rn = 1;

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT DISTINCT ON (order_id) order_id, status
FROM stg_orders
ORDER BY order_id, updated_at DESC, loaded_at DESC;

Both plans sort the same 150 rows on the same key. Postgres prints the window as ORDER BY stg_orders.updated_at, stg_orders.loaded_at without the DESC; the Sort Key line below it shows the real directions.

The dedup plan, with its row counts

A plan tree: 150 landing rows are scanned and sorted, the window numbers them and stops at row 1 of each order, and 80 rows reach the filter.

Read it from the bottom up, and watch the numbers on the right: 150 rows are scanned and sorted, and the window passes up only 80.

An index keeps the rows sorted

What if the rows arrived already sorted? Then the plan needs no Sort at all. That is what an index can give you.

Think of the index at the back of a book: the words are in order, and each one points to a page. Postgres's usual index, a B-tree, works the same way. Its leaf pages hold the keys in order, each with the address of its table row (the ctid: a page and a slot). Above them, internal pages hold signpost keys that point one level down, up to a single root.

A composite index sorts by its first column, then by the second within equal firsts, and so on. Read front to back, an index on (order_id, updated_at DESC, loaded_at DESC) hands over each order's versions newest first: exactly the window's order.

Inside the index on 100,000 order ids

A metapage points to a root page with 274 downlinks; below it 274 leaf pages, linked left to right, each holding up to 367 keys with the ctid of their table row.

Read it top to bottom: a lookup goes from the root to one leaf, then to the table row. The leaves are linked to their neighbours, so a scan can walk along them in key order. Counted with Postgres's pageinspect extension (not loaded in this browser).

Column order decides

The index only helps if its order is the window's order: the PARTITION BY column first, then the ORDER BY columns with the same directions. All of them reversed works too, because a B-tree can be read backwards.

  • (updated_at, order_id) is sorted by time. It is useless for numbering per order.
  • (order_id, updated_at DESC) leaves the tie-breaker unsorted, and here the planner still sorts everything.
  • (order_id, updated_at DESC, loaded_at DESC) matches, and the Sort disappears.

An index is not free. Every insert must write to it as well, and it takes space: 150 pages here for a 256-page table.

Wrong index, right index

-- 30,000 versions of 12,000 orders, no index
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, status
FROM (
  SELECT order_id, status,
         ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC, loaded_at DESC) AS rn
  FROM stg_big
) ranked
WHERE rn = 1;

-- sorted by time: the Sort stays
CREATE INDEX stg_big_time_idx ON stg_big (updated_at DESC, order_id);
EXPLAIN (COSTS OFF)
SELECT order_id, status
FROM (
  SELECT order_id, status,
         ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC, loaded_at DESC) AS rn
  FROM stg_big
) ranked
WHERE rn = 1;

-- the window's own order: the Sort is gone
CREATE INDEX stg_big_latest_idx ON stg_big (order_id, updated_at DESC, loaded_at DESC);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, status
FROM (
  SELECT order_id, status,
         ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC, loaded_at DESC) AS rn
  FROM stg_big
) ranked
WHERE rn = 1;

Three plans. The first sorts 30,000 rows (quicksort Memory: 2036kB). The second has an index sorted by time, and the Sort stays. The last reads Index Scan using stg_big_latest_idx straight into the WindowAgg. An index scan visits table pages in index order, not file order, which is why the planner only prefers it when the sort it saves costs more.

Numbers to remember

WhatNumber or nameWhat it means
A B-tree page8 kBLeaves hold the keys in order. Over 99% of an index's pages are leaves
A unique index on 100,000 integers276 pages274 leaves, one root, and the metapage: a first page that says where the root is
Entries per leafUp to 367Leaves are filled to 90%, the default fillfactor, which leaves room for inserts
Finding one key3 pagesThe root, one leaf and the table page
Levels in a huge index3 or 4One more level multiplies the reach by a few hundred: a third level covers tens of millions of keys, a fourth billions
The SortN log N comparisons, in memory up to workmem (4 MB by default)Past that it becomes an external merge through temporary files
Run ConditionSince Postgres 15rn = 1 stops each order after its first row
Filters an index can jump toEquality on the leading columns, plus a range on the first column without oneWHERE orderid = 1012 AND updatedat = .... A filter on a later column alone means reading the whole index
Skip scanPostgres 18Lets a filter on a later column use the index when the leading column has only a few distinct values
Spark's dropDuplicates(["orderid"])Keeps an arbitrary row per keySo teams use a window with rownumber() there too

What changed at SwiftKart

The dashboard now reads from a clean query: one row per order, its latest version. It says 80 orders, and order 1012 says shipped. The landing table still holds all 150 rows, untouched, in case the rule changes.

The rule itself is written down: the latest updated_at wins, and a tie goes to the row loaded last. A check runs after every dedup: COUNT(*) must equal COUNT(DISTINCT order_id).

So far a window function gave each row a number. Tomorrow morning Tess will ask how yesterday compared with the day before, and for that a row has to read its neighbour. That is Lesson 2.5.

In one line

Keep the latest row with ROW_NUMBER() OVER (PARTITION BY key ORDER BY updated_at DESC, tie-breaker) and rn = 1; the ORDER BY is a business rule, so choose it on purpose and make it unique.

Interview corner

How do you remove duplicates and keep the latest record for each key?

Number the rows per key with ROW_NUMBER() OVER (PARTITION BY key ORDER BY updated_at DESC, tie_breaker) in a CTE and keep rn = 1. The tie-breaker, such as a load timestamp or file name, makes the result deterministic when two rows share a timestamp. Then I check that COUNT(*) equals COUNT(DISTINCT key).

Why not use DISTINCT or GROUP BY with MAX?

DISTINCT only removes rows identical in every column, so versions with different statuses survive. MAX(updated_at) gives the latest time but not the rest of the row, and joining back on the timestamp returns duplicates when two rows share it. ROW_NUMBER returns exactly one whole row per key.

Where do duplicates come from in a pipeline?

Sources that send every change, so one key arrives in several versions; retries that resend a file or a batch; and at-least-once delivery in message systems such as Kafka. The raw layer keeps them all, and the clean layer deduplicates on the business key with a clear rule for which row wins.

The dedup over the landing table got slow as it grew. What is it doing, and what are your options?

It sorts every landing row by key and version order before the window can number them, so cost grows as N log N and the sort spills to disk once it passes work_mem. Options, cheapest first: dedup only the new batch plus the keys it touches instead of the whole history; give the sort more work_mem for that session; add a B-tree index on (key, version columns in the window's directions) so rows arrive presorted, at the cost of index maintenance on every load; or move the job to an engine that sorts in parallel. In Postgres 15 and later the rn = 1 filter already becomes a run condition, so the window itself is cheap; the sort is the problem.