PostgreSQL Delete Duplicate Rows but Keep One: 4 Methods

PostgreSQL Delete Duplicate Rows but Keep One: 4 Methods
In this article
  1. What counts as a duplicate, and which row to keep
  2. Sample setup
  3. Method 1: DELETE USING a self-join (keep the lowest id)
  4. Method 2: row_number() to choose which copy survives
  5. Method 3: no primary key? Use ctid
  6. Method 4: most rows are duplicates? Rebuild the table
  7. Stop duplicates from coming back
  8. Common mistakes
  9. Performance tips
  10. Frequently asked questions
  11. Summary

To delete duplicate rows in PostgreSQL but keep one, delete every row that has a twin with a smaller id: DELETE FROM t a USING t b WHERE a.col = b.col AND a.id > b.id. If you need to choose which copy survives (the newest, the most complete), number the copies with row_number() and delete everything numbered above 1. If the table has no id column at all, use the hidden system column ctid instead.

This tutorial shows all three methods on small sample tables, with the real output from PostgreSQL 18. It also covers the two traps that catch most people, NULL values and upper/lower case, and how to stop duplicates from coming back with a unique constraint.

What counts as a duplicate, and which row to keep

Before you write any DELETE, answer two questions. First, which columns define a duplicate? Two customer rows may be "the same customer" when the email matches, even if the city differs. Second, which copy should survive? The oldest row, the newest row, or any one of them?

PostgreSQL has no special "remove duplicates" command. You write an ordinary DELETE whose WHERE clause picks every row except the one you want to keep. The methods below differ only in how they pick that survivor.

MethodUse it whenKeeps
DELETE ... USING (self-join)The table has a unique id and any copy is fineLowest (or highest) id
row_number() in a subqueryYou must choose the survivor by a rule, such as newest dateRow numbered 1 by your ORDER BY
ctidThe table has no primary key (raw imports, staging tables)The physically first copy
Copy distinct rows, TRUNCATE, reloadMost of a large table is duplicatedOne copy of each distinct row

Sample setup

Create a scratch database and a customers table where the same email was registered more than once. The primary key is an identity column, so every row has its own customer_id even when the rest of the row is a copy.

CREATE TABLE customers (
    customer_id  bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email        text NOT NULL,
    full_name    text NOT NULL,
    city         text,
    signup_date  date NOT NULL
);

INSERT INTO customers (email, full_name, city, signup_date) VALUES
  ('asha@example.com',  'Asha Rao',     'Pune',      '2026-01-05'),
  ('ravi@example.com',  'Ravi Kumar',   'Chennai',   '2026-01-06'),
  ('asha@example.com',  'Asha Rao',     'Pune',      '2026-02-10'),
  ('meera@example.com', 'Meera Iyer',   'Bengaluru', '2026-02-11'),
  ('ravi@example.com',  'Ravi Kumar',   'Hyderabad', '2026-03-01'),
  ('asha@example.com',  'Asha R.',      'Mumbai',    '2026-03-20'),
  ('john@example.com',  'John Mathew',  'Kochi',     '2026-03-22');
Sample table with duplicate emails
CREATE TABLE
INSERT 0 7
Output

Step 1: find the duplicates first

Always look before you delete. GROUP BY the columns that define a duplicate and keep only the groups with more than one row. array_agg lists the ids in each group so you can see exactly what is at stake.

SELECT email, count(*) AS copies, min(customer_id) AS keep_id,
       array_agg(customer_id ORDER BY customer_id) AS all_ids
  FROM customers
 GROUP BY email
HAVING count(*) > 1
 ORDER BY email;
List duplicate emails and their ids
      email       | copies | keep_id | all_ids 
------------------+--------+---------+---------
 asha@example.com |      3 |       1 | {1,3,6}
 ravi@example.com |      2 |       2 | {2,5}
(2 rows)
Output

Two emails are duplicated: asha has three rows and ravi has two. If we keep the lowest id in each group, rows 3, 5 and 6 must go, which is 3 rows. Write that number down; the DELETE should report the same count.

Method 1: DELETE USING a self-join (keep the lowest id)

DELETE ... USING lets the WHERE clause refer to another table. Here the "other table" is the same customers table under a second alias. The documentation for DELETE says that when you repeat the target table in USING for a self-join, it must have an alias, which is why we write customers a and customers b.

The condition reads: delete row a if there is another row b with the same email and a smaller id. The row with the smallest id never has a smaller twin, so it survives.

BEGIN;

DELETE FROM customers a
 USING customers b
 WHERE a.email = b.email
   AND a.customer_id > b.customer_id
RETURNING a.customer_id, a.email;
Delete duplicates inside a transaction
BEGIN
 customer_id |      email       
-------------+------------------
           3 | asha@example.com
           5 | ravi@example.com
           6 | asha@example.com
(3 rows)

DELETE 3
Output

RETURNING prints every deleted row, and the command tag DELETE 3 matches the count we expected from Step 1. Because we started with BEGIN, nothing is final yet. Check the table, then decide.

SELECT customer_id, email, city FROM customers ORDER BY customer_id;
Check what is left
 customer_id |       email       |   city    
-------------+-------------------+-----------
           1 | asha@example.com  | Pune
           2 | ravi@example.com  | Chennai
           4 | meera@example.com | Bengaluru
           7 | john@example.com  | Kochi
(4 rows)
Output

One row per email, and the oldest ids survived. Run COMMIT; to keep the change, or ROLLBACK; if anything looks wrong. To keep the highest id instead, flip the comparison to a.customer_id < b.customer_id.

Method 2: row_number() to choose which copy survives

The lowest id is not always the right survivor. In our data, Ravi's newer row says Hyderabad and Asha's newest row says Mumbai, which may be their current cities. To keep the newest signup for each email, you need a rule, and that is what a window function gives you.

row_number() "returns the number of the current row within its partition, counting from 1" (PostgreSQL documentation). PARTITION BY email starts a new count for each email, and the ORDER BY inside OVER decides which row gets number 1.

Step 1: preview the numbering

SELECT customer_id, email, signup_date,
       row_number() OVER (PARTITION BY email
                          ORDER BY signup_date DESC, customer_id DESC) AS rn
  FROM customers
 ORDER BY email, rn;
Number the copies, newest first (run on fresh sample data)
 customer_id |       email       | signup_date | rn 
-------------+-------------------+-------------+----
           6 | asha@example.com  | 2026-03-20  |  1
           3 | asha@example.com  | 2026-02-10  |  2
           1 | asha@example.com  | 2026-01-05  |  3
           7 | john@example.com  | 2026-03-22  |  1
           4 | meera@example.com | 2026-02-11  |  1
           5 | ravi@example.com  | 2026-03-01  |  1
           2 | ravi@example.com  | 2026-01-06  |  2
(7 rows)
Output

The newest row of each email gets rn = 1. Every row with rn greater than 1 is a copy to delete. customer_id DESC is a tie-breaker: if two copies share the same signup_date, the numbering is still predictable instead of random.

Step 2: delete the rows numbered above 1

You cannot put a window function straight into WHERE. PostgreSQL rejects it:

SELECT customer_id FROM customers WHERE row_number() OVER (PARTITION BY email ORDER BY customer_id) > 1;
This fails
ERROR:  window functions are not allowed in WHERE
LINE 1: SELECT customer_id FROM customers WHERE row_number() OVER (P...
                                                ^
Output

The documentation explains why: window functions run after WHERE, GROUP BY and HAVING have been processed. The fix is to compute the number in a subquery and filter it outside:

BEGIN;

DELETE FROM customers
 WHERE customer_id IN (
       SELECT customer_id
         FROM (SELECT customer_id,
                      row_number() OVER (PARTITION BY email
                                         ORDER BY signup_date DESC, customer_id DESC) AS rn
                 FROM customers) ranked
        WHERE rn > 1)
RETURNING customer_id, email, city, signup_date;
Keep the newest row per email
BEGIN
 customer_id |      email       |  city   | signup_date 
-------------+------------------+---------+-------------
           1 | asha@example.com | Pune    | 2026-01-05
           2 | ravi@example.com | Chennai | 2026-01-06
           3 | asha@example.com | Pune    | 2026-02-10
(3 rows)

DELETE 3
Output
SELECT customer_id, email, city, signup_date FROM customers ORDER BY email;
Verify, then COMMIT
 customer_id |       email       |   city    | signup_date 
-------------+-------------------+-----------+-------------
           6 | asha@example.com  | Mumbai    | 2026-03-20
           7 | john@example.com  | Kochi     | 2026-03-22
           4 | meera@example.com | Bengaluru | 2026-02-11
           5 | ravi@example.com  | Hyderabad | 2026-03-01
(4 rows)
Output

This time the newest rows survived (ids 6 and 5). To define duplicates by more than one column, list them all in PARTITION BY, for example PARTITION BY email, full_name. If you only want to read one row per group without deleting anything, DISTINCT ON is shorter; see PostgreSQL DISTINCT ON: one row per group.

Method 3: no primary key? Use ctid

Raw imports and staging tables often have no id at all, and the copies are identical in every column. There is no column that tells them apart, so Methods 1 and 2 have nothing to compare. PostgreSQL still has one: every table has a hidden system column called ctid.

ctid is the physical location of a row version inside the table: a page number and a position on that page, such as (0,2). You do not see it with SELECT *, but you can ask for it by name.

CREATE TABLE payment_import (
    payment_ref  text,
    order_no     integer,
    amount       numeric(10,2),
    paid_via     text
);

INSERT INTO payment_import VALUES
  ('PAY-101', 5001, 1499.00, 'UPI'),
  ('PAY-101', 5001, 1499.00, 'UPI'),
  ('PAY-102', 5002,  899.50, 'Card'),
  ('PAY-103', 5003,  250.00, NULL),
  ('PAY-103', 5003,  250.00, NULL),
  ('PAY-103', 5003,  250.00, NULL),
  ('PAY-104', 5004, 3200.00, 'NetBanking');
A payment import table with no primary key
SELECT ctid, * FROM payment_import;
Show the hidden ctid column
 ctid  | payment_ref | order_no | amount  |  paid_via  
-------+-------------+----------+---------+------------
 (0,1) | PAY-101     |     5001 | 1499.00 | UPI
 (0,2) | PAY-101     |     5001 | 1499.00 | UPI
 (0,3) | PAY-102     |     5002 |  899.50 | Card
 (0,4) | PAY-103     |     5003 |  250.00 | 
 (0,5) | PAY-103     |     5003 |  250.00 | 
 (0,6) | PAY-103     |     5003 |  250.00 | 
 (0,7) | PAY-104     |     5004 | 3200.00 | NetBanking
(7 rows)
Output

PAY-101 appears twice and PAY-103 three times, so 3 rows should be deleted. PAY-103 has no paid_via value: it is NULL. That detail matters.

The NULL trap

Here is the self-join from Method 1 with ctid in place of the id:

BEGIN;

DELETE FROM payment_import a
 USING payment_import b
 WHERE a.payment_ref = b.payment_ref
   AND a.order_no    = b.order_no
   AND a.amount      = b.amount
   AND a.paid_via    = b.paid_via
   AND a.ctid > b.ctid;

ROLLBACK;
Looks right, but misses rows
BEGIN
DELETE 1
ROLLBACK
Output

Only 1 row was deleted, not 3. The PAY-103 copies survived because NULL = NULL is not true; it is NULL, meaning "unknown", and WHERE only keeps rows where the condition is true. The documentation's fix is IS NOT DISTINCT FROM, which works like = but treats two NULLs as equal.

BEGIN;

DELETE FROM payment_import a
 USING payment_import b
 WHERE a.payment_ref IS NOT DISTINCT FROM b.payment_ref
   AND a.order_no    IS NOT DISTINCT FROM b.order_no
   AND a.amount      IS NOT DISTINCT FROM b.amount
   AND a.paid_via    IS NOT DISTINCT FROM b.paid_via
   AND a.ctid > b.ctid
RETURNING a.ctid, a.payment_ref;
NULL-safe comparison
BEGIN
 ctid  | payment_ref 
-------+-------------
 (0,2) | PAY-101
 (0,5) | PAY-103
 (0,6) | PAY-103
(3 rows)

DELETE 3
Output

Now all 3 copies are found. Notice that the GROUP BY check from Step 1 would have counted PAY-103 correctly, because GROUP BY and PARTITION BY put NULLs in the same group. That makes the row_number() version NULL-safe without any extra work:

DELETE FROM payment_import
 WHERE ctid IN (
       SELECT ctid
         FROM (SELECT ctid,
                      row_number() OVER (PARTITION BY payment_ref, order_no, amount, paid_via
                                         ORDER BY ctid) AS rn
                 FROM payment_import) ranked
        WHERE rn > 1);
row_number() with ctid (NULLs grouped together)
DELETE 3
Output
SELECT ctid, * FROM payment_import;
Verify
 ctid  | payment_ref | order_no | amount  |  paid_via  
-------+-------------+----------+---------+------------
 (0,1) | PAY-101     |     5001 | 1499.00 | UPI
 (0,3) | PAY-102     |     5002 |  899.50 | Card
 (0,4) | PAY-103     |     5003 |  250.00 | 
 (0,7) | PAY-104     |     5004 | 3200.00 | NetBanking
(4 rows)
Output

Method 4: most rows are duplicates? Rebuild the table

When a large share of a big table is duplicated, deleting row by row leaves many dead rows behind and can take a long time. Copying the distinct rows out, emptying the table and loading them back is often simpler. Using TRUNCATE on the original table (instead of dropping it) keeps its grants, indexes, views and triggers in place.

BEGIN;

CREATE TEMP TABLE payment_dedup AS
SELECT DISTINCT * FROM payment_import;

TRUNCATE payment_import;

INSERT INTO payment_import SELECT * FROM payment_dedup;

COMMIT;
Rebuild with only distinct rows (run on fresh sample data)
BEGIN
SELECT 4
TRUNCATE TABLE
INSERT 0 4
COMMIT
Output

SELECT 4 means four distinct rows were saved, and INSERT 0 4 means all four went back. SELECT DISTINCT also treats NULLs as equal, so the three PAY-103 copies became one.

Stop duplicates from coming back

Cleaning up is half the job. If the application can still insert the same email twice, you will be back here next month. A unique constraint makes PostgreSQL reject the duplicate at insert time. Adding one creates a unique B-tree index on the columns.

If you try to add it before cleaning up, it fails and tells you one of the offending values:

ALTER TABLE customers ADD CONSTRAINT customers_email_key UNIQUE (email);
Before cleanup (fresh sample data)
ERROR:  could not create unique index "customers_email_key"
DETAIL:  Key (email)=(ravi@example.com) is duplicated.
Output

After running Method 1 and committing, the same statement succeeds, and a repeated email is rejected:

ALTER TABLE customers ADD CONSTRAINT customers_email_key UNIQUE (email);

INSERT INTO customers (email, full_name, city, signup_date)
VALUES ('asha@example.com', 'Asha Rao', 'Pune', '2026-04-01');
After cleanup
ALTER TABLE
ERROR:  duplicate key value violates unique constraint "customers_email_key"
DETAIL:  Key (email)=(asha@example.com) already exists.
Output

If the application should update the existing row instead of failing, use INSERT ... ON CONFLICT, explained in PostgreSQL upsert with ON CONFLICT.

Unique constraints and NULLs

By default, a unique constraint treats NULLs as different from each other, so the duplicate PAY-103 rows (paid_via is NULL) would still be allowed. Since PostgreSQL 15 you can add NULLS NOT DISTINCT so that NULLs count as equal:

ALTER TABLE payment_import
  ADD CONSTRAINT payment_import_uq
  UNIQUE NULLS NOT DISTINCT (payment_ref, order_no, amount, paid_via);

INSERT INTO payment_import VALUES ('PAY-103', 5003, 250.00, NULL);
Treat NULLs as equal (PostgreSQL 15 and later)
ALTER TABLE
ERROR:  duplicate key value violates unique constraint "payment_import_uq"
DETAIL:  Key (payment_ref, order_no, amount, paid_via)=(PAY-103, 5003, 250.00, null) already exists.
Output

Without NULLS NOT DISTINCT, the same INSERT succeeded in our test and created a new duplicate.

Common mistakes

Deleting every copy, including the one to keep

DELETE FROM customers WHERE email IN (SELECT email FROM customers GROUP BY email HAVING count(*) > 1) removes all rows for those emails, not just the extras. The query must leave one row per group untouched, which is what a.customer_id > b.customer_id or rn > 1 does.

Using <> instead of > in the self-join

With a.customer_id <> b.customer_id, every row in a group has a different twin, so every copy matches and all of them are deleted. Always use > or <, never <>.

Missing duplicates that differ only in case

To text comparison, Asha@Example.com and asha@example.com are different values, so the unique constraint above lets both in:

INSERT INTO customers (email, full_name, city, signup_date)
VALUES ('Asha@Example.com', 'Asha Rao', 'Pune', '2026-04-01');
Accepted, although it is the same person
INSERT 0 1
Output

Group by an expression to find such duplicates:

SELECT lower(email) AS email_key, array_agg(customer_id ORDER BY customer_id) AS ids
  FROM customers
 GROUP BY lower(email)
HAVING count(*) > 1;
Find case-insensitive duplicates
    email_key     |  ids  
------------------+-------
 asha@example.com | {1,9}
(1 row)
Output

Id 8 is missing because the rejected INSERT earlier still used up an identity value; failed inserts leave gaps. Delete with the same expression, then protect the table with a unique index on the expression:

DELETE FROM customers a
 USING customers b
 WHERE lower(a.email) = lower(b.email)
   AND a.customer_id > b.customer_id;

CREATE UNIQUE INDEX customers_email_lower_key ON customers (lower(email));

INSERT INTO customers (email, full_name, city, signup_date)
VALUES ('ASHA@example.com', 'Asha Rao', 'Pune', '2026-04-02');
Clean up and prevent case-insensitive duplicates
DELETE 1
CREATE INDEX
ERROR:  duplicate key value violates unique constraint "customers_email_lower_key"
DETAIL:  Key (lower(email))=(asha@example.com) already exists.
Output

Forgetting the child tables

If orders reference customer_id 3 and you delete customer 3, the foreign key either blocks the DELETE or, with ON DELETE CASCADE, silently deletes those orders. Before removing duplicate parents, point the child rows at the surviving id with an UPDATE, in the same transaction.

Performance tips

  • Index the columns that define a duplicate (here email) before running the self-join on a large table. Without an index, PostgreSQL may have to compare the table with itself the hard way.
  • The row_number() method reads the table once and sorts it, which usually behaves well when there are many duplicates.
  • DELETE does not shrink the table. Deleted rows become dead row versions that VACUUM cleans up later; see MVCC and row visibility. After a large cleanup, run VACUUM (ANALYZE) customers; and check for bloat as shown in Part 13: table and index bloat.
  • For millions of rows on a busy system, delete in batches (for example, one range of ids per transaction) so each transaction holds row locks for a short time and VACUUM can keep up.
  • DELETE lets other sessions keep reading and writing the table; TRUNCATE (Method 4) blocks them all. Pick the method that fits the time window you have.

Frequently asked questions

How do I delete duplicate rows in PostgreSQL without an id?

Use the ctid system column as a temporary tie-breaker: DELETE FROM t a USING t b WHERE a.col IS NOT DISTINCT FROM b.col AND a.ctid > b.ctid, listing every column. Use it only within that one statement, and add a primary key afterwards.

How do I delete duplicates based on multiple columns?

List all the columns in the join condition (a.email = b.email AND a.full_name = b.full_name) or in PARTITION BY email, full_name. Columns you leave out are allowed to differ between the copies.

How do I keep the latest duplicate row instead of the first?

Use row_number() with ORDER BY signup_date DESC, customer_id DESC in the OVER clause and delete rows where rn > 1, as in Method 2. With the self-join, a.customer_id < b.customer_id keeps the highest id.

Can I undo a DELETE of duplicates?

Only before COMMIT. Inside BEGIN, a ROLLBACK restores everything. After COMMIT, the rows can only come back from a backup, which is why every example here runs in a transaction and is checked first.

Summary

  • Decide which columns define a duplicate and which copy should survive.
  • Find the duplicates first with GROUP BY ... HAVING count(*) > 1 and note how many rows should go.
  • Use DELETE ... USING with a.id > b.id to keep the lowest id.
  • Use row_number() in a subquery when the survivor depends on a rule, such as the newest date.
  • Use ctid for tables without a key, only inside a single statement.
  • Compare nullable columns with IS NOT DISTINCT FROM, never with =.
  • Run the DELETE inside BEGIN, check the count and the remaining rows, then COMMIT.
  • Add a UNIQUE constraint (NULLS NOT DISTINCT, or a unique index on lower(email), if needed) so duplicates cannot return.
  • Run VACUUM (ANALYZE) after a large cleanup.
PT Ganesh

An experienced PostgreSQL DBA/SQL developer with years of expertise in designing and implementing robust database solutions. Proficient in writing complex queries, developing stored procedures, and conducting performance tuning to deliver highly efficient data-driven applications that meet business requirements.

Home
SQL
PLSQL
Interview Q&A