← Back to SQL, page 25

sql-0500 · Hard senior

A team wants to add a UNIQUE constraint on (customer_id, product) to a table that already contains duplicates. How do you find the duplicates, clean them safely and add the constraint?

Find duplicate groups with GROUP BY and HAVING COUNT(*) > 1, decide which row survives (often the newest or the lowest id), and merge any values that need combining, such as quantities, before deleting the rest. Do it in a transaction after a backup, then add the unique index, in PostgreSQL concurrently on large tables. Verify with a duplicate query that returns no rows.

Full answer
sql
CREATE TABLE cart_lines (id INTEGER PRIMARY KEY, customer_id INTEGER, product TEXT, qty INTEGER);
INSERT INTO cart_lines VALUES (1,1,'Pen',2),(2,1,'Pen',3),(3,1,'Bag',1),(4,2,'Bag',1),(5,2,'Bag',1),(6,2,'Bag',2);

Find the duplicate groups:

sql
SELECT customer_id, product, COUNT(*) AS copies, SUM(qty) AS total_qty FROM cart_lines GROUP BY customer_id, product HAVING COUNT(*) > 1 ORDER BY customer_id;
customer_idproductcopiestotal_qty
1Pen25
2Bag34

Merge quantities into the surviving row, keeping the lowest id, then delete the others:

sql
UPDATE cart_lines SET qty = (SELECT SUM(c.qty) FROM cart_lines c WHERE c.customer_id = cart_lines.customer_id AND c.product = cart_lines.product) WHERE id IN (SELECT MIN(id) FROM cart_lines GROUP BY customer_id, product);
DELETE FROM cart_lines WHERE id NOT IN (SELECT MIN(id) FROM cart_lines GROUP BY customer_id, product);
SELECT id, customer_id, product, qty FROM cart_lines ORDER BY id;
idcustomer_idproductqty
11Pen5
31Bag1
42Bag4

Add the constraint and confirm it now protects the table:

sql
CREATE UNIQUE INDEX cart_lines_unique ON cart_lines (customer_id, product);
SELECT COUNT(*) AS duplicate_groups FROM (SELECT 1 FROM cart_lines GROUP BY customer_id, product HAVING COUNT(*) > 1);
duplicate_groups
0
sql
INSERT INTO cart_lines (customer_id, product, qty) VALUES (1, 'Pen', 1);  -- error on purpose
text
Error: UNIQUE constraint failed: cart_lines.customer_id, cart_lines.product

The duplicate check shows customer 1's two Pen rows and customer 2's three Bag rows. The merge sums the quantities onto the lowest id in each group, so no information is lost, and the delete removes the other rows. With the unique index in place, a repeat insert fails with a constraint error naming the columns (the exact wording depends on the database), which is the point of the exercise. On PostgreSQL, build the index with CREATE UNIQUE INDEX CONCURRENTLY first and then attach it as a constraint, so writes are not blocked, and decide with the business whether duplicates should be merged or the application should switch to an upsert (INSERT ... ON CONFLICT DO UPDATE) going forward.

sql
CREATE TABLE cart_lines (id INTEGER PRIMARY KEY, customer_id INTEGER, product TEXT, qty INTEGER);
INSERT INTO cart_lines VALUES (1,1,'Pen',2),(2,1,'Pen',3),(3,1,'Bag',1),(4,2,'Bag',1),(5,2,'Bag',1),(6,2,'Bag',2);

SELECT customer_id, product, COUNT(*) AS copies, SUM(qty) AS total_qty FROM cart_lines GROUP BY customer_id, product HAVING COUNT(*) > 1 ORDER BY customer_id;

UPDATE cart_lines SET qty = (SELECT SUM(c.qty) FROM cart_lines c WHERE c.customer_id = cart_lines.customer_id AND c.product = cart_lines.product) WHERE id IN (SELECT MIN(id) FROM cart_lines GROUP BY customer_id, product);
DELETE FROM cart_lines WHERE id NOT IN (SELECT MIN(id) FROM cart_lines GROUP BY customer_id, product);
SELECT id, customer_id, product, qty FROM cart_lines ORDER BY id;

CREATE UNIQUE INDEX cart_lines_unique ON cart_lines (customer_id, product);
SELECT COUNT(*) AS duplicate_groups FROM (SELECT 1 FROM cart_lines GROUP BY customer_id, product HAVING COUNT(*) > 1);

-- error on purpose
INSERT INTO cart_lines (customer_id, product, qty) VALUES (1, 'Pen', 1);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Find duplicates with GROUP BY and HAVING
  • Choose a survivor and merge values
  • Clean up in a transaction
  • Add the unique index afterwards
  • Use upserts to stop new duplicates

Common mistakes

  • Deleting duplicates before deciding what to merge
  • Adding the constraint without a verification query

Follow-ups

  • How would you keep the newest row instead of the oldest?
  • How would you find near-duplicates that differ in case or spacing?

Tips

  • Describe the survivor rule before writing SQL