01 / 21

Identifying
Duplicates in SQL

Learn to detect duplicate rows and unexpected multiplicity in your data using GROUP BY, HAVING, and COUNT.

SQL

What Are Duplicates?

A duplicate row is a row that shares the same values for one or more key columns as another row in the same table. Duplicates often appear after messy data imports, faulty JOINs, or missing primary keys.

Exact Duplicate
Every column value is identical across two or more rows.
Partial Duplicate
Only specific key columns match, while other columns differ.

Why Duplicates Matter

Undetected duplicates silently corrupt every calculation downstream. A single duplicated order row can inflate revenue, distort averages, and break dashboard trust.

Inflated Aggregates
SUM, COUNT, and AVG all return wrong numbers when duplicates exist.
Broken Joins
Joining on a non-unique key creates a many-to-many fanout, multiplying rows.
Silent Failures
Queries run without errors: no warning tells you the count is wrong.

Seeing Duplicates in Action

orders (raw) id customer amount 101 Alice 50 102 Bob 75 102 Bob 75 103 Carol 30 102 Bob 75 SUM = 310 (wrong!) GROUP BY duplicates found id customer cnt 101 Alice 1 102 Bob 3 103 Carol 1 HAVING COUNT(*) > 1 finds Bob Duplicate rows Unique rows

The Core Duplicate Detection Pattern

Every duplicate check follows the same three-part template: SELECT the key columns, GROUP BY them, then \(\texttt{HAVING COUNT}(*) > 1\) to keep only groups with more than one row.

SELECT column_a, column_b, COUNT(*) AS cnt FROM your_table GROUP BY column_a, column_b HAVING COUNT(*) > 1 ORDER BY cnt DESC;

GROUP BY + HAVING Explained

SELECT cols Pick key columns GROUP BY cols Collapse into groups
\(\texttt{HAVING cnt > 1}\)
Filter to duplicates Raw Rows Alice, 50 Bob, 75 Bob, 75 Carol, 30 Groups
Alice : \(\texttt{cnt} = 1\)
Bob : \(\texttt{cnt} = 2\)
Carol : \(\texttt{cnt} = 1\)
Result
Bob : \(\texttt{cnt} = 2\)
Only groups with \(\texttt{cnt} > 1\)

WHERE vs HAVING

Students often confuse WHERE and HAVING. Both filter data, but they operate at different stages of query execution.

WHERE HAVING
Filters Individual rows Groups (after GROUP BY)
Runs Before grouping After grouping
Can use aggregates? No Yes
Example WHERE status = 'active' \(\texttt{HAVING COUNT}(*) > 1\)

Unexpected Multiplicity

Multiplicity means a key that you expected to be unique actually maps to multiple rows. This commonly happens when you JOIN tables and a "unique" key turns out to have duplicates in one table.

Expected: 1-to-1
One customer_id per row. JOIN produces the same row count as the original.
Actual: 1-to-Many
Duplicates in the join key cause row counts to explode: a "fanout."

Step-by-Step Approach

1
Identify the grain. Ask: what should each row represent? One order? One customer? One event?
2
SELECT the key columns + \(\texttt{COUNT}(*)\). Choose the columns that should be unique together.
3
GROUP BY those key columns. This collapses identical combinations into one group.
4
\(\texttt{HAVING COUNT}(*) > 1\). This returns only groups with duplicates.
5
Investigate and resolve. Decide whether to DELETE, DISTINCT, or fix the upstream source.

Example 1: Basic Duplicate Check

A students table should have one row per student. Find any email addresses that appear more than once.

SELECT email, COUNT(*) AS cnt FROM students GROUP BY email HAVING COUNT(*) > 1;

Example 2: Multi-Column Key

An enrollments table records which student is enrolled in which course. The combination of (student_id, course_id) should be unique: no student enrolled twice in the same course.

SELECT student_id, course_id, COUNT(*) AS cnt FROM enrollments GROUP BY student_id, course_id HAVING COUNT(*) > 1;

Example 3: Detecting Join Fanout

Before joining two tables, verify the join key is unique in the table you expect to be the "one" side. If it's not unique, the JOIN will multiply rows.

-- Check: is customer_id unique in customers? SELECT customer_id, COUNT(*) AS cnt FROM customers GROUP BY customer_id HAVING COUNT(*) > 1;

Quick Check: Row Count Validation

A fast sanity check compares the total row count against the count of distinct key values. If they differ, duplicates exist.

SELECT COUNT(*) AS total_rows, COUNT(DISTINCT id) AS unique_ids FROM orders;
Match
\(\texttt{total\_rows} = \texttt{unique\_ids}\): no duplicates on that key.
Mismatch
\(\texttt{total\_rows} > \texttt{unique\_ids}\): duplicates exist. The difference tells you how many extra rows.

DISTINCT vs GROUP BY

Both can remove duplicates from output, but they serve different purposes. Understanding when to use each is essential.

SELECT DISTINCT GROUP BY + HAVING
Purpose Remove duplicate rows from output Find and count duplicate groups
Shows count? No Yes
Filters duplicates? Hides them silently Exposes them explicitly
Best for Quick dedup of output Data quality investigation

Common Mistakes

✕ Using WHERE instead of HAVING
Writing \(\texttt{WHERE COUNT}(*) > 1\) causes an error. Aggregate functions can only appear in HAVING.
✕ Grouping by too many columns
Including every column in GROUP BY makes each row unique, hiding true duplicates. Only group by the key columns.
✕ Ignoring NULLs
GROUP BY treats all NULLs as one group. Two rows with NULL email are flagged as duplicates, even if that's intentional.

Summary: Your Toolkit

Task SQL Pattern When to Use
Find duplicates \(\texttt{GROUP BY} \dots \texttt{HAVING} > 1\) Data quality audit
Quick count check \(\texttt{COUNT}(*) \text{ vs } \texttt{COUNT(DISTINCT)}\) Before any join
Remove from output SELECT DISTINCT Clean report output
Find join fanout \(\texttt{GROUP BY join\_key + HAVING}\) Debugging row explosion
Delete duplicates \(\texttt{ROW\_NUMBER}() + \texttt{DELETE}\) Permanent data cleanup

Question 1 of 5

Which SQL clause is used to filter groups based on an aggregate function like \(\texttt{COUNT}(*)\)?

Question 2 of 5

A table has 1,000 rows but only 950 distinct values for order_id. What does this tell you?

Question 3 of 5

What happens if you write \(\texttt{WHERE COUNT}(*) > 1\) instead of \(\texttt{HAVING COUNT}(*) > 1\)?

Question 4 of 5

What is the most likely result of this JOIN?

Question 5 of 5

The query returns zero rows, but you know there are students enrolled in the same course twice. What is the most likely problem?