SQL QuestSQL Interview Questions › Subqueries & CTEs

Delete Duplicate Records, Keep the Original

MediumFreeQuerying BasicsSubqueries & CTEsAggregation & Grouping

Three people signed up twice under slightly different names — Daniel Martinez and Dan Martinez, Emma Wilson and Emma W., John Smith and John Smith Jr — but each pair shares one email address.

Delete the duplicates, keeping the lowest customer_id for each email (the original signup). Then show customer_id, name, email for everyone left, ordered by customer_id.

The pattern is worth memorising, because deleting duplicates is one of the most-searched SQL tasks there is: find the id you want to KEEP per group with MIN(customer_id) ... GROUP BY email, then delete every row whose id is NOT IN that set. You are not deleting duplicates directly — you are keeping the survivors and deleting everything else.

Note what makes these hard in real life: the names differ. Deduplicating on name would find nothing. Picking the right key is the actual skill.

Solve it in the browser editor →

Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".

Schema

customers

customer_idnameemailsignup_datemembershiptotal_orders
1John Smithjohn.smith@email.com2023-01-15Gold15
2Emma Wilsonemma.wilson@email.com2023-03-20Silver8
3Michael Brownmichael.brown@email.com2023-02-10Gold12

Expected output: 13 rows — one row per email, earliest id kept

Hint

The hint for this one spells out most of the query, so it stays in the editor. Reach for DELETE, DML, Subquery, and open the hint there if you stall.

Concepts

DELETE DML Subquery Aggregation

Practise the topic: SQL practice questions · CTE practice · GROUP BY exercises

In these company practice sets

Goldman Sachs

A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.

Related questions

Department Roster with GROUP_CONCATMedium · FreeConsistent Director AnalysisMedium · FreeBelow Department AverageMedium · FreeHighest Total Salary Budget DepartmentMedium · FreeFare Imputation AnalysisMedium · FreeUNION ALL Dedup: Cross-Dataset SearchMedium · Free

Where would this cost you points in an interview?

Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.

Take the readiness test