Sub topic 13
Self-joins: removing duplicate rows
This chapter assumes you can write DELETE ... USING and UPDATE ... FROM statements, know why table aliases matter, and can run transactions in psql. It applies those tools to one common job: deleting duplicate rows from a single table while keeping one row per group.
Why a self-join fits
A duplicate is a row that has the same value as another row in the same table. To decide which rows to delete, each row has to be compared with other rows of that table. That comparison is a self-join: the table joined to itself under two different aliases.
DELETE ... USING allows this. The target table gets one alias and the USING table gets another, even though both are the same table.
CREATE TABLE contacts (
id serial PRIMARY KEY,
email text NOT NULL
);
INSERT INTO contacts (email) VALUES
('[email protected]'), -- id 1
('[email protected]'), -- id 2
('[email protected]'), -- id 3
('[email protected]'), -- id 4
('[email protected]'), -- id 5
('[email protected]'); -- id 6The statement that removes the duplicates:
DELETE FROM contacts AS a
USING contacts AS b
WHERE a.email = b.email
AND a.id > b.id;After it runs, contacts holds ids 1, 2 and 4. For each email, the row with the lowest id survives.
How the statement works
The WHERE clause defines pairs of rows (a, b). A pair qualifies when both rows share an email and a has a larger id than b. Every row a that appears in at least one qualifying pair is deleted.
The condition a.id > b.id is what protects one row per group. The row with the lowest id in a group can never be a, because no other row in the group has a smaller id. It is therefore never deleted.
Here are the qualifying pairs for the sample data:
| a.id (deleted) | b.id (compared with) | |
|---|---|---|
| 3 | 1 | [email protected] |
| 6 | 1 | [email protected] |
| 6 | 3 | [email protected] |
| 5 | 2 | [email protected] |
Row 6 appears in two pairs. That is harmless for DELETE, because the statement removes each target row once, however many pairs match it. This differs from UPDATE ... FROM, where several matches make the result depend on an arbitrary choice. For deduplication, the extra pairs only cost time.
Choosing which row survives
The comparison on the second column picks the survivor.
| Condition | Row kept in each group |
|---|---|
| `a.id > b.id` | Lowest id (oldest) |
| `a.id < b.id` | Highest id (newest) |
| `a.created_at < b.created_at OR (a.created_at = b.created_at AND a.id < b.id)` | Latest `created_at`, ties broken by id |
Always include a tie-breaker on a unique column. If two rows tie on the ordering column and you compare only that column, neither is "greater". Both survive, and the duplicates remain.
Preview before you delete
Delete statements should be inspected first. A plain SELECT over the same self-join shows duplicate rows for ids like 6, so use EXISTS to list each doomed row once:
SELECT a.id, a.email
FROM contacts AS a
WHERE EXISTS (
SELECT 1
FROM contacts AS b
WHERE b.email = a.email
AND b.id < a.id
)
ORDER BY a.id;This asks the same question as the delete: does an older row with the same email exist? The EXISTS form returns ids 3, 5 and 6. Run the real delete inside a transaction with RETURNING and check that it returns the same rows:
BEGIN;
DELETE FROM contacts AS a
USING contacts AS b
WHERE a.email = b.email
AND a.id > b.id
RETURNING a.id, a.email;
-- Compare with the preview, then COMMIT; or ROLLBACK;
ROLLBACK;Defining what counts as a duplicate
The equality in the join decides what "duplicate" means. Plain a.email = b.email is exact. It treats [email protected] and [email protected] (with a trailing space) as different people. Normalize both sides when that matters:
DELETE FROM contacts AS a
USING contacts AS b
WHERE lower(btrim(a.email)) = lower(btrim(b.email))
AND a.id > b.id;Several columns can define a duplicate. Add one equality per column, such as a.last_name = b.last_name AND a.birth_date = b.birth_date.
NULL values
NULL = NULL is not true in SQL, so rows with a null in the compared column never match each other. In our table email is NOT NULL, so this does not arise. If the column allows nulls and you want null rows treated as duplicates of each other, use IS NOT DISTINCT FROM:
WHERE a.email IS NOT DISTINCT FROM b.email
AND a.id > b.idThink about whether that is what you want. Many nulls usually mean "unknown", not "the same".
Repoint references before deleting
Suppose another table refers to contacts:
CREATE TABLE messages (
id serial PRIMARY KEY,
contact_id integer NOT NULL REFERENCES contacts (id),
body text NOT NULL
);Deleting a duplicate that has messages fails with a foreign key error, unless the constraint cascades. If it cascades, you silently lose the messages. Move the references to the surviving row first, using UPDATE ... FROM with a subquery that maps each duplicate to its survivor:
BEGIN;
UPDATE messages AS m
SET contact_id = k.keep_id
FROM (
SELECT a.id AS dup_id, min(b.id) AS keep_id
FROM contacts AS a
JOIN contacts AS b
ON a.email = b.email
AND b.id < a.id
GROUP BY a.id
) AS k
WHERE m.contact_id = k.dup_id;
DELETE FROM contacts AS a
USING contacts AS b
WHERE a.email = b.email
AND a.id > b.id;
COMMIT;The GROUP BY a.id makes each duplicate appear once in k, so every message row has exactly one match. Using min(b.id) gives the lowest id in the group, which is the row the delete keeps. Both statements must use the same duplicate definition. If they disagree, messages can end up pointing at a row that gets deleted.
When the self-join is slow
A group of n identical rows produces about n(n-1)/2 pairs. Ten rows per group is trivial. A group of 10,000 produces roughly 50 million pairs. If your data has a few very large duplicate groups, use a window function instead. It numbers the rows in each group once:
DELETE FROM contacts
WHERE id IN (
SELECT id
FROM (
SELECT id,
row_number() OVER (PARTITION BY email ORDER BY id) AS rn
FROM contacts
) AS numbered
WHERE rn > 1
);Rows numbered 2 and higher are the extras, so this has the same effect as a.id > b.id. The cost grows with the number of rows, not with pairs.
| Approach | Strength | Weakness |
|---|---|---|
| Self-join with `USING` | Short, easy to read, fine for small groups | Pair count grows quadratically within a group |
| `row_number()` in a subquery | Linear work, flexible `ORDER BY` | Longer, needs a unique `id` column to delete by |
Tables with no unique column
If the table has no primary key, there is no id to compare. PostgreSQL's physical row address, ctid, can stand in:
DELETE FROM events AS a
USING events AS b
WHERE a.payload = b.payload
AND a.ctid > b.ctid;Prevent the duplicates from coming back
Once the data is clean, a unique index stops new duplicates. If you normalized the comparison, index the same expression:
CREATE UNIQUE INDEX contacts_email_unique
ON contacts (lower(btrim(email)));Inserts that would create a duplicate now fail, or can be handled with INSERT ... ON CONFLICT. Creating this index before cleaning the data fails, because the existing duplicates violate it. Clean first, then index.
Common mistakes
- Using
>=or<=instead of>or<. A row then matches itself, and every row in the table is deleted. - Forgetting the equality on the duplicate column. The delete then removes everything except the lowest id in the whole table.
- Deleting before moving foreign key references.
- Deduplicating on raw text when values differ only by case or whitespace.
Exercise
The contacts table now has a created_at timestamptz NOT NULL column. Write a DELETE that keeps the most recently created row for each email, and breaks ties on created_at by keeping the higher id.
Show answer
DELETE FROM contacts AS a
USING contacts AS b
WHERE a.email = b.email
AND (a.createdat < b.createdat
OR (a.createdat = b.createdat AND a.id < b.id));
Row a is deleted when some row b with the same email is newer, or has the same timestamp and a higher id. The newest row (highest created_at, then highest id) is never a, so it survives. Run it inside a transaction with RETURNING first to check.
Exercise
A teammate wrote DELETE FROM contacts AS a USING contacts AS b WHERE a.email = b.email AND a.id >= b.id;. What does it do, and why?
Show answer
It deletes every row in the table. With >=, each row pairs with itself (a.id = b.id and the emails are equal), so every row qualifies as a in at least one pair. Use a strict > so a row never matches itself.