Finding duplicate rows in SQL is a fundamental skill for database administrators, data analysts, and backend developers. That's why whether you are cleaning a messy dataset, enforcing data integrity constraints, or preparing a migration, identifying redundancy is often the first step toward a healthy database. This guide explores the most effective techniques to locate duplicate records, ranging from basic aggregation methods to advanced window functions, ensuring you can handle scenarios of any complexity.
Understanding What Constitutes a Duplicate
Before writing queries, you must define what "duplicate" means in your specific context. It generally falls into two categories:
- Complete Row Duplicates: Every single column in one row matches every column in another row exactly.
- Partial (Key-Based) Duplicates: Specific columns—such as
email,user_id, or a composite key likefirst_name+last_name+dob—contain identical values, while other columns (like an auto-incrementidorcreated_attimestamp) differ.
Most real-world scenarios involve partial duplicates. Here's one way to look at it: a user might accidentally create two accounts with the same email address but different user_id values. Your query strategy must target the specific columns that define uniqueness for your business logic.
The Classic Approach: GROUP BY and HAVING
The most universal, ANSI-SQL compliant method for finding duplicates uses the GROUP BY clause combined with HAVING. This works on virtually every relational database system (MySQL, PostgreSQL, SQL Server, Oracle, SQLite) It's one of those things that adds up. Surprisingly effective..
Basic Syntax
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 1;
Practical Example
Imagine a customers table where email should be unique It's one of those things that adds up..
SELECT email, COUNT(*) as duplicate_count
FROM customers
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY duplicate_count DESC;
This query returns a list of emails appearing more than once and how many times they appear. It is excellent for reporting the scope of the problem.
Finding Duplicates Across Multiple Columns
Often, uniqueness is defined by a combination of columns (a composite key). Take this case: a orders table might allow the same product_id for a customer_id only once.
SELECT customer_id, product_id, COUNT(*)
FROM orders
GROUP BY customer_id, product_id
HAVING COUNT(*) > 1;
Limitation: This method shows which keys are duplicated and how many times, but it does not return the full rows (like the primary keys id of the specific duplicate records) needed to delete or update them Still holds up..
Retrieving Full Duplicate Rows: Self-Joins and Subqueries
To see the actual rows—including the primary keys—you need to join the table back to the aggregated result or use a subquery.
Method 1: INNER JOIN with Derived Table
This is highly performant on indexed columns.
SELECT c1.id, c1.email, c1.first_name, c1.last_name, c1.created_at
FROM customers c1
INNER JOIN (
SELECT email
FROM customers
GROUP BY email
HAVING COUNT(*) > 1
) c2 ON c1.email = c2.email
ORDER BY c1.email, c1.created_at;
How it works: The subquery (c2) isolates the duplicated emails. The outer query joins this list back to the main table (c1) to fetch all columns for those specific emails Which is the point..
Method 2: Using IN or EXISTS
For smaller datasets or ad-hoc analysis, IN is readable.
SELECT *
FROM customers
WHERE email IN (
SELECT email
FROM customers
GROUP BY email
HAVING COUNT(*) > 1
)
ORDER BY email;
Performance Note: On massive tables (millions of rows), IN can sometimes be slower than a JOIN or EXISTS depending on the query optimizer. EXISTS is often preferred for correlated subqueries, though for duplicate detection, the JOIN approach usually yields the best execution plan.
The Modern Standard: Window Functions (ROW_NUMBER)
If you are using a modern database (PostgreSQL, SQL Server, Oracle, MySQL 8.0+, SQLite 3.25+), Window Functions are the gold standard. They allow you to rank rows within a partition (group) without collapsing the result set Still holds up..
The ROW_NUMBER() Technique
WITH RankedCustomers AS (
SELECT
id,
email,
first_name,
last_name,
created_at,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at) as row_num
FROM customers
)
SELECT *
FROM RankedCustomers
WHERE row_num > 1
ORDER BY email, created_at;
Why This Is Superior
- Identifies the "Original" vs. "Duplicate": By using
ORDER BY created_atinside theOVERclause,row_num = 1becomes the first (oldest) record. Every row withrow_num > 1is a duplicate candidate for deletion. - Returns Full Rows: You get every column instantly, no joins required.
- Flexible Partitioning: You can partition by multiple columns:
PARTITION BY email, phone_number. - Deletion Ready: This CTE (Common Table Expression) structure plugs directly into a
DELETEstatement.
Alternative Window Functions
RANK()/DENSE_RANK(): Use these if you want to keep all rows tied for the first position (e.g., if two rows have the exact samecreated_attimestamp).ROW_NUMBER()arbitrarily picks one as 1 and the other as 2.RANK()would assign both 1, and the next would be 3.
Database-Specific Shortcuts
While standard SQL is portable, some engines offer syntactic sugar Simple as that..
PostgreSQL: DISTINCT ON
PostgreSQL allows a very concise syntax to keep the "first" row per group.
-- To FIND duplicates (rows NOT returned by this query)
SELECT DISTINCT ON (email) *
FROM customers
ORDER BY email, created_at;
To find the duplicates, you would typically use the ROW_NUMBER() CTE approach shown above, as DISTINCT ON is primarily a deduplication tool for SELECT or INSERT.
MySQL: Pre-8.0 Limitations
Before version 8.Also, 0, MySQL did not support Window Functions or CTEs. You were forced to use the GROUP BY / JOIN methods or user-defined variables (which are deprecated and unreliable). If you are on MySQL 5.7 or older, upgrade immediately or stick to the JOIN method.
SQL Server: TOP 1 WITH TIES
A niche but clever trick for finding the "top" duplicate set.
SELECT TOP 1 WITH TIES *
FROM customers
ORDER BY ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at);
This returns only the first row per email. To find duplicates, you would invert the logic or use the standard CTE approach That's the whole idea..
Handling Edge Cases and Performance
NULL Values in Grouping Columns
Standard SQL treats NULL as a distinct value for grouping purposes? On the flip side, actually, GROUP BY groups all NULLs together. If your unique column allows NULLs, you might find a "duplicate" group consisting of multiple NULL emails It's one of those things that adds up. And it works..
-- Exclude NULLs if they aren't considered valid duplicates
SELECT email, COUNT(*)
FROM customers
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;
Case Sensitivity
- PostgreSQL: Case-sensitive by default (`'A'