Use a five-row PostgreSQL fixture to distinguish duplicate results from stored records, rank survivors and rehearse a reversible cleanup.

Topics: SQL, Window functions, Data quality

Author: PracHub

Published: 11/6/2026

Remove Duplicate Rows in SQL: Choose a Survivor Before You Delete

November 6, 2026
4 min read
Remove Duplicate Rows in SQL: Choose a Survivor Before You Delete

Quick Overview

Use a five-row PostgreSQL fixture to distinguish duplicate results from stored records, rank survivors and rehearse a reversible cleanup.

SQLWindow functionsData quality
Data ScientistFree

A payment feed can deliver the same event twice. If the second delivery changes the status from pending to settled, deleting either row at random can change the answer to a revenue question. Before writing SQL, specify the business key, which version wins, and whether the task asks for a clean report or a change to stored records.

Decide what one row represents

Consider this deliberately small staging table. Every listed column is non-null. The primary key is row_id. The provider assigns event_id independently for each account. A higher revision supersedes a lower revision. Within a revision, the higher row_id wins because this example defines it as the ingestion sequence.

row_idaccount_idevent_idrevisionstatus
10Aevt71pending
11Aevt72settled
12Aevt72settled
13Bevt71pending
14Aevt81settled

The intended survivors are 12, 13 and 14. Partitioning on event_id alone would merge different accounts. Partitioning on status as well would keep a stale pending record for account A. A full-row DISTINCT would retain all five rows because each has a different identifier. The PracHub DISTINCT guide shows how the output columns affect that operation.

Rank before you delete

Run the selection as a query first. PostgreSQL, SQL Server and other engines that support ROW_NUMBER can use this ranking pattern. The outer filter runs after the window calculation.

WITH ranked AS (
    SELECT s.*,
           ROW_NUMBER() OVER (
               PARTITION BY account_id, event_id
               ORDER BY revision DESC, row_id DESC
           ) AS rn
    FROM staging_events AS s
)
SELECT row_id, account_id, event_id, revision, status
FROM ranked
WHERE rn = 1
ORDER BY account_id, event_id;

Change the filter to rn > 1 to preview IDs 10 and 11. The final ORDER BY formats the report. Only the ordering inside the window chooses the survivor. Ask how ties should be resolved when two rows with the same revision disagree on the amount. A unique ID makes the answer repeatable, but business owners may require a conflict queue for that case. Beekeeper Studio’s duplicate-removal guide illustrates the choices between finding repeated rows, returning a distinct result and cleaning stored data.

Rehearse a physical cleanup on a disposable copy

The following PostgreSQL example uses a transaction and returns the exact IDs selected for removal. Run it on a disposable copy of the fixture. ROLLBACK restores its initial state so you can try another survivor rule.

BEGIN;
WITH ranked AS (
    SELECT row_id,
           ROW_NUMBER() OVER (
               PARTITION BY account_id, event_id
               ORDER BY revision DESC, row_id DESC
           ) AS rn
    FROM staging_events
)
DELETE FROM staging_events AS s
USING ranked AS r
WHERE r.rn > 1 AND s.row_id = r.row_id
RETURNING s.row_id;
ROLLBACK;

For a real cleanup, check whether any downstream rows reference a losing ID. Preserve the loser-to-survivor mapping, reconcile dependent rows, and review a recovery plan before committing. A retry arriving between preview and deletion can change which row should win. Coordinate the writers or materialize and validate the exact candidates under an appropriate concurrency policy. For a continuously running feed, also decide how a higher revision arriving tomorrow updates the current record. A history table and a current-state table may need different keys.

Check the result against the business contract

Count duplicate groups and redundant rows separately. One group containing three rows contributes one duplicate group and two redundant rows. In this fixture, account B keeps its evt7 even though A has the same event identifier. Re-running the ranking on the surviving set should identify zero rows for removal.

For an interview follow-up, work through deduplicating activity logs while keeping the latest row per user and activity type. State which fields define one logical activity before adapting the window clause. A unique constraint belongs on the intended current-state key only if the application really allows a single current row for that key.

Keep practicing


Comments (0)