← Back to SQL, page 13

sql-0252 · Easy fresher

Write a query that finds email addresses that appear more than once, with how many times each appears.

Group by the email and keep groups with more than one row: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1. Normalize first, for example with lower(trim(email)), if 'Ana@x.com' and 'ana@x.com ' should count as the same address.

Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users VALUES (1,'Ana@x.com'),(2,'ana@x.com '),(3,'b@x.com'),(4,'b@x.com'),(5,'c@x.com');
SELECT email, COUNT(*) AS n FROM users GROUP BY email HAVING COUNT(*) > 1;
emailn
b@x.com2

Exact matching finds only b@x.com. Normalizing reveals a second duplicate group:

sql
SELECT lower(trim(email)) AS email, COUNT(*) AS n FROM users GROUP BY lower(trim(email)) HAVING COUNT(*) > 1 ORDER BY email;
emailn
ana@x.com2
b@x.com2

To see the full duplicate rows rather than just the emails, join back or use a window count:

sql
SELECT id, email FROM (
  SELECT id, email, COUNT(*) OVER (PARTITION BY lower(trim(email))) AS n FROM users
) WHERE n > 1 ORDER BY lower(trim(email)), id;
idemail
1Ana@x.com
2ana@x.com
3b@x.com
4b@x.com

The window version keeps every column of the duplicate rows, which helps decide which one to keep.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users VALUES (1,'Ana@x.com'),(2,'ana@x.com '),(3,'b@x.com'),(4,'b@x.com'),(5,'c@x.com');
SELECT email, COUNT(*) AS n FROM users GROUP BY email HAVING COUNT(*) > 1;

SELECT lower(trim(email)) AS email, COUNT(*) AS n FROM users GROUP BY lower(trim(email)) HAVING COUNT(*) > 1 ORDER BY email;

SELECT id, email FROM (
  SELECT id, email, COUNT(*) OVER (PARTITION BY lower(trim(email))) AS n FROM users
) WHERE n > 1 ORDER BY lower(trim(email)), id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • GROUP BY plus HAVING COUNT(*) > 1 finds duplicates
  • Normalize values before grouping when needed
  • COUNT(*) OVER (PARTITION BY ...) shows full duplicate rows
  • Decide which copy to keep before deleting

Common mistakes

  • Using WHERE COUNT(*) > 1
  • Missing duplicates that differ only in case or spaces

Follow-ups

  • How would you delete all but one copy?
  • How would you prevent duplicates in future?

Tips

  • Ask whether case and spaces matter