← Back to SQL, page 19

sql-0374 · Easy fresher

A duplicate check on customer emails finds no duplicates, although there clearly are some. Fix it.

The query groups by id as well as email, and every id is unique, so each group has one row and HAVING COUNT(*) > 1 never passes. Group by the email only (normalised with lower() if case should not matter).

Full answer
sql
CREATE TABLE signups (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO signups VALUES (1, 'a@x.com'), (2, 'b@x.com'), (3, 'A@x.com'), (4, 'a@x.com');

The query as written:

sql
SELECT id, email, COUNT(*) AS n FROM signups GROUP BY id, email HAVING COUNT(*) > 1;
idemailn

(0 rows)

The result is empty. Adding id to the select list forced it into GROUP BY, which made every group a single row.

A corrected version:

sql
SELECT lower(email) AS email, COUNT(*) AS n, group_concat(id) AS ids FROM signups GROUP BY lower(email) HAVING COUNT(*) > 1;
emailnids
a@x.com31,3,4

Grouping by the normalised email finds the three rows for a@x.com, and group_concat lists their ids so they can be reviewed or merged. The order of ids inside group_concat is not guaranteed without an ORDER BY inside the aggregate. Add a unique index on lower(email) afterwards to stop new duplicates.

sql
CREATE TABLE signups (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO signups VALUES (1, 'a@x.com'), (2, 'b@x.com'), (3, 'A@x.com'), (4, 'a@x.com');

SELECT id, email, COUNT(*) AS n FROM signups GROUP BY id, email HAVING COUNT(*) > 1;

SELECT lower(email) AS email, COUNT(*) AS n, group_concat(id) AS ids FROM signups GROUP BY lower(email) HAVING COUNT(*) > 1;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Group only by the duplicate key
  • Extra GROUP BY columns split groups
  • Normalise case before comparing emails
  • Prevent recurrence with a unique index

Common mistakes

  • Adding id to GROUP BY to satisfy the select list
  • Comparing emails case-sensitively

Follow-ups

  • How would you keep the lowest id and delete the rest?
  • How would you enforce case-insensitive uniqueness?

Tips

  • Explain why each group has one row