SQL · Module 16 · Lesson 21 min read

Finding & Deleting Duplicates

1. Find duplicate values

SQL
SELECT email, count(*) FROM users GROUP BY email HAVING count(*) > 1;

For "duplicate rows", group by all the columns that define a duplicate (not the id).

2. See the full duplicate rows

  • Window count: count(*) OVER (PARTITION BY cols) > 1
  • Or join back to the grouped result

3. Delete duplicates, keeping one

Method A: row_number() ⭐ (most flexible — choose which one to keep)

SQL
DELETE FROM t WHERE id IN (
  SELECT id FROM (
    SELECT id, row_number() OVER (PARTITION BY dup_cols ORDER BY id) AS rn FROM t
  ) x WHERE rn > 1
);

ORDER BY id keeps the oldest; ORDER BY created_at DESC keeps the newest.

Method B: self-join DELETE … USING

CSS
DELETE FROM t a USING t b
WHERE a.id > b.id AND a.col1 = b.col1 AND a.col2 = b.col2;

Method C: rebuild with DISTINCT ON

CREATE TABLE t_clean AS SELECT DISTINCT ON (cols) * FROM t ORDER BY cols, id; (then swap tables)

4. Prevent them from coming back ⭐

  • Add a UNIQUE constraint on the duplicate-defining columns (after cleaning)
  • Use INSERT … ON CONFLICT DO NOTHING for imports
  • Case/space-insensitive duplicates: unique index on lower(trim(email))

Gotchas

  • NULLs: GROUP BY treats NULLs as equal, but UNIQUE constraints don't (unless NULLS NOT DISTINCT)
  • "Near duplicates" ('Asha ' vs 'asha') → normalize first with lower(trim(...))
  • Always run the SELECT version first and do the DELETE inside a transaction

Example

SQL
-- Create some duplicates (a double import)
INSERT INTO expenses (user_id, category_id, title, amount, spent_on, tags)
SELECT user_id, category_id, title, amount, spent_on, tags FROM expenses WHERE id IN (1, 5, 12);
INSERT INTO expenses (user_id, category_id, title, amount, spent_on, tags)
SELECT user_id, category_id, title, amount, spent_on, tags FROM expenses WHERE id = 1;   -- a third copy

-- 1. Find duplicate groups
SELECT user_id, title, amount, spent_on, count(*) AS copies
FROM expenses
GROUP BY user_id, title, amount, spent_on
HAVING count(*) > 1
ORDER BY copies DESC;
-- Weekly groceries 3 | Vegetables 2 | Fuel 2

-- 2. See every duplicate row with its position
SELECT id, title, amount, spent_on, rn FROM (
  SELECT id, title, amount, spent_on,
         row_number() OVER (PARTITION BY user_id, title, amount, spent_on ORDER BY id) AS rn,
         count(*)     OVER (PARTITION BY user_id, title, amount, spent_on)             AS copies
  FROM expenses
) t WHERE copies > 1 ORDER BY title, rn;

-- 3A. Delete, keeping the oldest (lowest id)
BEGIN;
DELETE FROM expenses WHERE id IN (
  SELECT id FROM (
    SELECT id, row_number() OVER (PARTITION BY user_id, title, amount, spent_on ORDER BY id) AS rn
    FROM expenses
  ) x WHERE rn > 1
);                                                  -- DELETE 4
SELECT count(*) FROM expenses;                      -- 31 ✅
ROLLBACK;                                           -- (undo so we can try method B)

-- 3B. Self-join DELETE … USING
DELETE FROM expenses a
USING expenses b
WHERE a.id > b.id
  AND a.user_id = b.user_id AND a.title = b.title
  AND a.amount = b.amount AND a.spent_on = b.spent_on;   -- DELETE 4
SELECT count(*) FROM expenses;                      -- 31

-- 4. Prevent future duplicates
ALTER TABLE expenses ADD CONSTRAINT no_duplicate_expense
  UNIQUE (user_id, title, amount, spent_on);
INSERT INTO expenses (user_id, title, amount, spent_on)
VALUES (1, 'Weekly groceries', 2450, '2026-09-03')
ON CONFLICT ON CONSTRAINT no_duplicate_expense DO NOTHING;   -- INSERT 0 0 (skipped)

-- Near-duplicates: normalize before comparing
SELECT lower(trim(title)) AS normalized, count(*)
FROM (VALUES ('Groceries'), (' groceries'), ('GROCERIES ')) t(title)
GROUP BY 1;                                         -- groceries | 3