Duplicate records are one of the most common data quality problems in relational databases. They waste storage, distort reports, confuse customer communications, and can even break business logic that assumes each row is unique. The good news is that SQL offers several clear and powerful techniques for detecting duplicates, from simple GROUP BY queries to advanced window functions. Whether you are cleaning a customer list, reconciling transactions, or preparing data for analytics, knowing how to write a reliable SQL query for finding duplicate records is an essential skill. This guide walks through each approach with practical examples, explains when to use it, and shows how to remove duplicates safely once you find them.
Why Duplicate Records Matter
Duplicate records rarely announce themselves. On the flip side, they creep into databases through repeated imports, missing unique constraints, application bugs, manual data entry, or merges between systems. At first, a few repeated rows may seem harmless That alone is useful..
- Inaccurate reporting: Revenue totals, customer counts, and inventory levels become inflated.
- Poor customer experience: The same customer may receive multiple emails or shipments.
- Wasted resources: Storage, backup time, and query performance suffer.
- Broken joins and aggregations: Duplicates can multiply result sets unexpectedly.
- Compliance risk: Duplicate records in financial or healthcare data can trigger audit issues.
Finding duplicates is therefore not just a technical exercise. It is a data quality practice that protects decision-making and builds trust in the database.
Understanding Duplicate Records in SQL
In SQL, a duplicate record is a row that shares the same values as another row in one or more columns. There are two common definitions:
- Full-row duplicates: Every column value is identical, including all non-key columns.
- Business-key duplicates: One or more meaningful columns are repeated, such as an email address, national ID, or invoice number, even if other columns differ.
Most real-world duplicate detection focuses on business keys. In real terms, for example, two customer rows may have different IDs but the same email address. In real terms, that is still a duplicate from a business perspective. The techniques below can handle both cases depending on which columns you include in the query.
For the examples in this article, imagine a simple table called customers:
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
city VARCHAR(50)
);
Method 1: GROUP BY and HAVING
The most traditional SQL query for finding duplicate records uses GROUP BY with HAVING COUNT(*) > 1. This approach groups rows by the column or columns that define a duplicate and returns only the groups that appear more than once Not complicated — just consistent..
SELECT email, COUNT(*) AS duplicate_count
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;
This query answers a simple question: “Which email addresses appear more than once?” The GROUP BY clause collapses all rows with the same email into one group. The HAVING clause then filters out groups with only one row. The result shows the duplicated value and how many times it occurs Simple as that..
To see the full duplicate rows, not just the duplicated values, you can join the grouped result back to the original table:
SELECT c.*
FROM customers c
JOIN (
SELECT email
FROM customers
GROUP BY email
HAVING COUNT(*) > 1
) dup ON c.email = dup.email
ORDER BY c.email;
This is one of the most readable and widely supported methods. And it works in MySQL, PostgreSQL, SQL Server, Oracle, and SQLite. The main limitation is that it only shows the duplicated values unless you add a join, and it can be slower on very large tables without proper indexes.
Method 2: Window Functions with ROW_NUMBER()
Window functions provide a more flexible and often faster way to find duplicates. Now, the ROW_NUMBER() function assigns a sequential number to each row within a partition. If you partition by the columns that define a duplicate and order by a unique column, duplicate rows will receive row numbers greater than 1 Practical, not theoretical..
SELECT *
FROM (
SELECT
customer_id,
first_name,
last_name,
email,
city,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY customer_id
) AS row_num
FROM customers
) ranked
WHERE row_num > 1;
This query returns every row that is a duplicate based on email, excluding the first occurrence. The PARTITION BY email clause groups rows by email, and ORDER BY customer_id decides which row is considered the “first.” You can change the ordering to keep the most recent record, the highest ID, or any other business rule.
Quick note before moving on.
Window functions are supported in modern versions of PostgreSQL, SQL Server, Oracle, MySQL 8.Worth adding: 0+, and SQLite 3. 25+. They are especially useful when you need to identify duplicates without collapsing the result set. You can see each duplicate row alongside its row number, which makes investigation easier.
Counterintuitive, but true.
Method 3: Self-Join
A self-join compares a table to itself. It is a classic technique for finding duplicate records when you want to see pairs of rows that share the same values Turns out it matters..
SELECT
a.customer_id AS id_1,
b.customer_id AS id_2,
a.email
FROM customers a
JOIN customers b
ON a.email = b.email
AND a.customer_id < b.customer_id;
The condition a.customer_id < b.Here's the thing — customer_id prevents each pair from appearing twice and avoids matching a row to itself. The result shows pairs of customer IDs that share the same email. That said, self-joins are easy to understand, but they can become expensive on large tables because they compare many row combinations. They are best used for smaller datasets or when you specifically need pairwise comparisons Most people skip this — try not to..
Method
Method 4: Using a CTE with COUNT()
A Common Table Expression (CTE) lets you build a temporary named result set that you can reference in your main query. This approach combines the readability of GROUP BY with the flexibility of a reusable intermediate result.
WITH duplicate_emails AS (
SELECT email, COUNT(*) AS occurrences
FROM customers
GROUP BY email
HAVING COUNT(*) > 1
)
SELECT c.*
FROM customers c
JOIN duplicate_emails d ON c.email = d.email
ORDER BY d.occurrences DESC, c.email;
The CTE isolates the duplicate-detection logic into a single, clearly named block. So 8. But 0+, and SQLite 3. This pattern scales well as your criteria grow more complex—you can add additional columns to the GROUP BY clause or layer multiple CTEs without turning the query into an unreadable nest of subqueries. Now, the outer query then joins back to the original table to retrieve full row details. Plus, cTEs are supported in PostgreSQL, SQL Server, Oracle, MySQL 8. 3+.
Not obvious, but once you see it — you'll see it everywhere.
Method 5: Using EXISTS for Correlated Checks
The EXISTS operator tests whether a subquery returns any rows. When correlated to the outer query, it can flag rows that have at least one other match in the table Easy to understand, harder to ignore..
SELECT c.*
FROM customers c
WHERE EXISTS (
SELECT 1
FROM customers c2
WHERE c2.email = c.email
AND c2.customer_id <> c.customer_id
);
This returns every row that shares its email with at least one other row. Day to day, the correlated subquery runs once per outer row, which makes EXISTS intuitive but potentially slow on large tables without a supporting index on the comparison column. Its strength lies in readability and short-circuiting: the database stops scanning as soon as it finds the first match, so it can outperform a COUNT-based approach when duplicates are common.
Choosing the Right Method
Each technique has a place depending on your goal:
- Use GROUP BY with HAVING when you want a quick summary of which values are duplicated and broad database compatibility matters most.
- Use window functions when you need to see every duplicate row, assign priority, or keep the "best" record according to a business rule.
- Use a self-join when you specifically need pairwise comparisons between rows.
- Use a CTE when your detection logic is complex or will be reused and you want to keep the query readable.
- Use EXISTS when you want to flag duplicates inline and can rely on a good index.
Performance Considerations
Regardless of the method, indexes are the single biggest factor in duplicate-detection performance. A composite index on the columns you group or partition by—such as email, or email and created_at together—can turn a full table scan into a fast index scan. On very large tables, run the query during off-peak hours and always test with EXPLAIN (or your database's equivalent) to confirm the execution plan uses the index you expect.
It is also worth deciding what a "duplicate" actually means in your context. Exact matches on every column are rare; more often you care about duplicates on a subset of fields, possibly after normalizing values with LOWER(), TRIM(), or COALESCE(). Defining this rule precisely before you write the query will save you from rework later.
Conclusion
Finding duplicate records is a foundational data-quality task, and SQL gives you several complementary tools to accomplish it. In practice, the GROUP BY/HAVING pattern offers simplicity and portability, window functions provide fine-grained control over which rows to keep, self-joins expose pairwise relationships, CTEs improve readability for complex logic, and EXISTS offers concise inline detection. No single method is universally best—the right choice depends on your data size, your definition of a duplicate, and whether you need a summary or the full rows. Master these patterns, pair them with thoughtful indexing, and you will be able to diagnose and clean duplicate data confidently across virtually any relational database Small thing, real impact..