Sub topic 13
Self-joins: removing duplicate rows
Assume you know basic DELETE, WHERE, INNER JOIN, table aliases, and primary keys. This chapter uses PostgreSQL's DELETE ... USING syntax.
A duplicate row is a row that repeats a value that should identify one logical record. For example, a contacts table might contain the same email address several times. A self-join compares rows in the same table so that you can decide which copy to keep.
Comparing a table with itself
Use two aliases for the same table:
arepresents a possible row to delete.brepresents another row used for comparison.- The join condition identifies duplicates.
- A second condition decides which row survives.
Suppose the row with the smallest id should remain:
CREATE TABLE contacts (
id serial PRIMARY KEY,
email text NOT NULL
);
INSERT INTO contacts (email) VALUES
('[email protected]'),
('[email protected]'),
('[email protected]'),
('[email protected]');
SELECT *
FROM contacts
ORDER BY email, id;The three [email protected] rows have different IDs, but they represent one logical contact. Delete every row whose ID is greater than another row with the same email:
DELETE FROM contacts AS a
USING contacts AS b
WHERE a.email = b.email
AND a.id > b.id
RETURNING a.*;a is the target table alias. PostgreSQL deletes the matching a rows. Alias b is only used to find an earlier copy. The condition a.id > b.id prevents the lowest-ID row from matching as the row to delete.
Choosing the duplicate rule
The email comparison is the definition of a duplicate. You might need to normalize values first, such as comparing lower(email):
DELETE FROM contacts AS a
USING contacts AS b
WHERE lower(a.email) = lower(b.email)
AND a.id > b.id
RETURNING a.id, a.email;This treats [email protected] and [email protected] as duplicates. An expression in the comparison can make the statement slower because PostgreSQL may need to calculate it for many rows. An expression index can help larger tables:
CREATE INDEX contacts_lower_email_idx
ON contacts (lower(email));If email can be NULL, the = operator does not consider two NULL values equal. If NULL should also count as a duplicate, use PostgreSQL's null-safe comparison:
DELETE FROM contacts AS a
USING contacts AS b
WHERE a.email IS NOT DISTINCT FROM b.email
AND a.id > b.id
RETURNING a.*;Preventing duplicates afterward
Deletion fixes existing data. It does not prevent the same problem from returning. After cleaning the table, add a uniqueness rule that matches your business definition. For case-insensitive email values, a unique index is often appropriate:
CREATE UNIQUE INDEX contacts_email_unique
ON contacts (lower(email));Create the constraint only after checking that no duplicates remain.
Exercise
In the condition a.id > b.id, which row is deleted when two rows have the same email?
Show answer
The row represented by a is deleted when its ID is greater, so the row with the lowest ID remains.