Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 08 / Topic 2 of 10

Finding and removing duplicates

Real imports bring duplicates. Detecting them is a GROUP BY:

WITH signups AS (
  SELECT * FROM (VALUES
    ('[email protected]',  '2025-01-05'::date),
    ('[email protected]',  '2025-01-20'),
    ('[email protected]',  '2025-02-01'),
    ('[email protected]', '2025-02-11'),
    ('[email protected]',  '2025-03-01')
  ) AS t(email, signup_date)
)
SELECT email, count(*) AS copies
FROM signups
GROUP BY email
HAVING count(*) > 1;
      email       | copies 
------------------+--------
 [email protected] |      3
(1 row)

Keeping one of each is the ROW_NUMBER pattern again — partition by what defines "the same", order by which copy should win, keep rn = 1:

WITH signups AS (
  SELECT * FROM (VALUES
    ('[email protected]',  '2025-01-05'::date),
    ('[email protected]',  '2025-01-20'),
    ('[email protected]',  '2025-02-01'),
    ('[email protected]', '2025-02-11'),
    ('[email protected]',  '2025-03-01')
  ) AS t(email, signup_date)
),
numbered AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY email
                               ORDER BY signup_date) AS rn
  FROM signups
)
SELECT email, signup_date
FROM numbered
WHERE rn = 1
ORDER BY email;
       email       | signup_date 
-------------------+-------------
 [email protected]  | 2025-01-05
 [email protected] | 2025-02-11
 [email protected]  | 2025-01-20
(3 rows)

(Asha keeps her earliest signup.) Deleting the losers from a real table uses the same ranking inside a DELETE ... WHERE id IN (...) — Stage 3 gives you the DELETE; the thinking is already done here.

🧪 Quick quiz — answer from memory, then check.

  1. How do you detect duplicate emails?
  2. In the keep-one pattern, what does the ORDER BY inside the window decide?
Show the answers
  1. GROUP BY email HAVING count(*) > 1.
  2. Which copy survives — rn = 1 goes to the first row in that order.

Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.

Search the guide