How to find duplicates in SQL: count, list, clean up

Every company ends up with duplicate customers sooner or later: an import runs twice, or someone creates an account instead of searching for the existing one. Three queries get it under control. First you count which records appear more than once, then you list them in full, and finally you build a clean list where every customer appears exactly once.

In short: SELECT name, city, COUNT(*) FROM customers GROUP BY name, city HAVING COUNT(*) > 1 lists each duplicated combination once. ROW_NUMBER() OVER (PARTITION BY name, city ORDER BY customer_id) numbers the copies, and WHERE rn = 1 keeps just the first of each.

What you should know first: HAVING, subqueries and ROW_NUMBER and RANK.

Try it now

In the exercises on this page, the customers table has a few extra rows starting at customer_id 50. They came from a botched import out of the old system, and you'll find them at the bottom of the table above the editor.

Task When customers were imported from the old order system, some of them were created twice. A customer counts as a duplicate when name and city are the same. Show each duplicated combination once: name, city and how_many (how often it occurs).

customers 18 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
50Harbor Fremont PartnersBostonUSA2025-09-10Business617-555-0142
51Emily CarterChicagoUSA2025-03-02Consumer312-555-0178
52Riverside County OfficeRiversideUSA2026-02-14Government951-555-0110
53Harbor Fremont PartnersBostonUSA2026-04-01BusinessNULL
54Emily CarterDenverUSA2026-05-20Consumer720-555-0136
57Harbor FremontBostonUSA2026-05-27Business617-555-0142

How to find duplicate rows

Before you search, decide what "duplicate" means. The customer_id is always different, so it's no help. You're looking for rows that match in the columns that matter to the business. Try it with the name alone first:

SELECT name, COUNT(*) AS how_many
FROM customers
GROUP BY name
HAVING COUNT(*) > 1;
namehow_many
Emily Carter3
Harbor Fremont Partners3
Riverside County Office2

GROUP BY collects all rows with the same name, COUNT(*) counts them, and HAVING keeps only the groups with more than one row. There's a catch, though: one of the three Emily Carters lives in Denver, the other two in Chicago. Two people who share a name aren't a duplicate. That's why the exercise compares name and city together. For companies you'd often add a ZIP or postcode or a tax ID, and for products the manufacturer's part number.

Listing every duplicate row

The count tells you which combinations are duplicated, but not which records are behind them. Before anyone cleans up, they want to see the individual rows with their IDs and dates. So you connect the count back to the table:

SELECT c.customer_id, c.name, c.city, c.customer_since
FROM customers c
JOIN (SELECT name, city
      FROM customers
      GROUP BY name, city
      HAVING COUNT(*) > 1) d
  ON d.name = c.name AND d.city = c.city
ORDER BY c.name, c.customer_id;
customer_idnamecitycustomer_since
2Emily CarterChicago2022-07-01
51Emily CarterChicago2025-03-02
1Harbor Fremont PartnersBoston2021-03-15
50Harbor Fremont PartnersBoston2025-09-10
53Harbor Fremont PartnersBoston2026-04-01
3Riverside County OfficeRiverside2020-11-20
52Riverside County OfficeRiverside2026-02-14

The query in brackets is the count from above without the number. The JOIN keeps every customer row whose name and city are on that list. The ON needs both columns, or Emily Carter from Denver slips in. Instead of the JOIN you can also use COUNT(*) OVER (PARTITION BY name, city) in a CTE: the window function writes the group size onto every row, and outside you keep everything above 1.

One gap remains: customer 57 is called "Harbor Fremont", without Partners. Compared by name, that's a different customer. For businesses a second key that is spelled differently less often helps, such as the phone number. That's what the next exercise checks.

Task During the import, names weren't always spelled the same way, sometimes with Partners, sometimes without. The phone number is more reliable. Before anyone merges duplicates, accounting wants to see every affected record: show customer_id, name, city and phone for every customer whose phone number is also on file for another customer. Customers without a phone number don't belong on the list. Sort by phone, and for the same number by customer_id.

customers 18 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
50Harbor Fremont PartnersBostonUSA2025-09-10Business617-555-0142
51Emily CarterChicagoUSA2025-03-02Consumer312-555-0178
52Riverside County OfficeRiversideUSA2026-02-14Government951-555-0110
53Harbor Fremont PartnersBostonUSA2026-04-01BusinessNULL
54Emily CarterDenverUSA2026-05-20Consumer720-555-0136
57Harbor FremontBostonUSA2026-05-27Business617-555-0142

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Keeping only the first record

For a clean list, every customer should appear exactly once. You decide which copy stays, usually the oldest, because existing orders point to it. ROW_NUMBER numbers the rows inside each group:

SELECT customer_id, name, city,
       ROW_NUMBER() OVER (PARTITION BY name, city ORDER BY customer_id) AS rn
FROM customers
WHERE name IN ('Emily Carter', 'Harbor Fremont Partners')
ORDER BY name, city, rn;
customer_idnamecityrn
2Emily CarterChicago1
51Emily CarterChicago2
54Emily CarterDenver1
1Harbor Fremont PartnersBoston1
50Harbor Fremont PartnersBoston2
53Harbor Fremont PartnersBoston3

PARTITION BY restarts the count in every group, and the ORDER BY inside OVER decides who gets 1. Emily Carter from Denver has a group of her own, so she gets a 1 too. Everything numbered 1 stays; anything higher is a copy. Window functions are calculated after WHERE, so you filter on rn in an outer query or a CTE.

Task For the cleaned-up customer list, keep only the record that was created first for each combination of name and city, meaning the one with the lowest customer_id. Customers without a duplicate stay on the list as well. Show customer_id, name, city and customer_since, sorted by customer_id. Number the rows within each combination with ROW_NUMBER().

customers 18 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
50Harbor Fremont PartnersBostonUSA2025-09-10Business617-555-0142
51Emily CarterChicagoUSA2025-03-02Consumer312-555-0178
52Riverside County OfficeRiversideUSA2026-02-14Government951-555-0110
53Harbor Fremont PartnersBostonUSA2026-04-01BusinessNULL
54Emily CarterDenverUSA2026-05-20Consumer720-555-0136
57Harbor FremontBostonUSA2026-05-27Business617-555-0142

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

None of these exercises change the table; they only show what would remain. To actually remove rows you use DELETE from level 4. The ROW_NUMBER query is the safe first step: look at what's going to go, and only then delete it.

Common mistakes

COUNT(*) in WHERE

WHERE COUNT(*) > 1 fails, because WHERE checks single rows before anything is counted. The exercise tells you that functions like COUNT don't belong in WHERE and points you to HAVING.

Comparing too few columns

Group or join on name alone and Emily Carter from Denver counts as a duplicate. In the first exercise not all values match, and in the third one row goes missing. Make sure GROUP BY, ON and PARTITION BY all use the same columns.

Empty phone numbers counted as duplicates

COUNT(*) OVER (PARTITION BY phone) puts every customer without a number into one shared group. That group has more than one row, so the four customers without a phone end up on your duplicate list, and the exercise reports too many rows. Exclude NULL with WHERE phone IS NOT NULL or count with COUNT(phone), which skips NULL. The JOIN route doesn't have this problem, because NULL = NULL is never true.

ROW_NUMBER straight in WHERE

The database rejects WHERE ROW_NUMBER() OVER (…) = 1, and also WHERE rn = 1 in the same query that creates rn. The exercise then tells you that window functions like ROW_NUMBER can't go in WHERE, because they're computed after it. Work the number out in a CTE or subquery and filter outside.

Spellings that are almost the same

"Harbor Fremont Partners" and "Harbor Fremont Partners " with a trailing space are two different strings to SQL. With real data it helps to tidy up before comparing, for example GROUP BY lower(trim(name)), lower(trim(city)). That won't catch "Harbor Fremont" without Partners, though; for that you need a second key such as the phone number from the second exercise.

Duplicates in MySQL, PostgreSQL, SQL Server and SQLite

GROUP BY with HAVING works the same in all four. ROW_NUMBER needs window functions, and those haven't been around equally long everywhere:

DatabaseROW_NUMBERWorth knowing
MySQLfrom version 8.0older versions have no window functions
PostgreSQLyesSELECT DISTINCT ON (name, city) … ORDER BY name, city, customer_id keeps the first row of each group
SQL ServeryesORDER BY inside OVER is required for ROW_NUMBER
SQLite (these exercises)from version 3.25.0nothing special

With DISTINCT ON in PostgreSQL, the expressions in the parentheses must come first in ORDER BY; the columns after them decide which row counts as first in each group.

Sources: MySQL Reference Manual (What Is New in MySQL 8.0, Window Functions), PostgreSQL documentation (SELECT, DISTINCT Clause), Microsoft Learn (ROW_NUMBER), sqlite.org (Window Functions).

FAQ

Why not just use SELECT DISTINCT?

DISTINCT only removes rows that match in every selected column. Include customer_id or customer_since and the copies already differ, so DISTINCT leaves them alone. Leave those columns out and you no longer know which record survives. To find duplicates and clean them up on purpose, you need GROUP BY or ROW_NUMBER.

Which record should I keep?

That's a business decision. Often it's the oldest, because orders and invoices point to it. Sometimes it's the newest, because it has the current phone number. The ORDER BY inside OVER decides who gets 1, for example ORDER BY customer_since DESC for the newest.

How do I find rows that match in every column?

Put every column except the ID into GROUP BY. For a table without an ID column, that catches every row that appears more than once.

How do I stop duplicates from getting in?

Add a UNIQUE constraint on the columns that must be unique. The database then rejects a second row with the same values. You know it from creating tables in level 4.

Up next: level 5 project, customer analysis

To finish level 5 you combine CTEs, RANK and LAG in two reports: a ranking of the top customers in each segment and the ordering rhythm of repeat customers, with their longest gap and a follow-up flag.

Go to the customer analysis project

Write to us

Choose language

Select your preferred language