To count duplicates in SQL, use the GROUP BY clause with the COUNT() function and a HAVING filter, like SELECT column, COUNT(*) FROM table GROUP BY column HAVING COUNT(*) > 1;. This returns each duplicate value along with how many times it appears.
Why You Need to Count Duplicates
Duplicate rows in a database can come from many sources: accidental double entry, merging data from multiple systems, or importing CSV files without a unique key. Knowing which values repeat and how often is the first step toward cleaning your data. For example, a customer table might have the same email address twice, causing marketing emails to be sent twice. Counting duplicates helps you identify these issues, decide whether to delete or merge them, and verify that a unique constraint will work before adding it.
Basic Syntax: GROUP BY and COUNT
The core pattern is simple. Suppose you have a table named orders with a column customer_id. To see how many orders each customer has placed, you would write:
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id;
This lists every customer_id and the number of rows that share it. To show only customers who appear more than once (i.e., have duplicates), add a HAVING clause:
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1;
The HAVING clause filters groups after aggregation, unlike WHERE which filters rows before grouping. You cannot use COUNT(*) in a WHERE clause because the count is not known until after grouping.
Counting Duplicates Across Multiple Columns
Often you need to find duplicates based on more than one column. For instance, in a users table, you might consider a record a duplicate if both first_name and last_name match. Simply group by both columns:
SELECT first_name, last_name, COUNT(*) AS dup_count
FROM users
GROUP BY first_name, last_name
HAVING COUNT(*) > 1;
This returns each combination that appears more than once. Note that grouping by multiple columns treats the combination as a single key. If you want to find rows where one column is duplicated regardless of others, group by only that column.
Using COUNT(DISTINCT) for Unique Counts
Sometimes you need the opposite: how many distinct values exist in a column. The COUNT(DISTINCT column) function returns the number of unique values. For example, to count how many distinct customers have placed orders:
SELECT COUNT(DISTINCT customer_id) AS unique_customers
FROM orders;
This is not the same as counting duplicates, but it is often used alongside duplicate detection. For instance, you might compare the total row count (COUNT(*)) with the distinct count to see how many extra rows exist.
Window Functions: ROW_NUMBER for Duplicate Rows
When you need to see the actual duplicate rows (not just the counts), use a window function like ROW_NUMBER(). This assigns a sequential number to each row within a partition of duplicate keys. For example, to identify all but the first occurrence of each duplicate email:
SELECT id, email,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM contacts;
The rows with rn > 1 are duplicates. You can then delete them or inspect them. This approach works in SQL Server, PostgreSQL, Oracle, and MySQL 8.0+ (which supports window functions). In older MySQL versions, you would need a self-join or a temporary table.
Deleting Duplicates Safely
Once you have identified duplicates, you often want to remove them. A common method uses a self-join or a subquery with ROW_NUMBER(). For example, to delete duplicate emails keeping the lowest id in SQL Server:
WITH cte AS (
SELECT id, email,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM contacts
)
DELETE FROM cte WHERE rn > 1;
In MySQL, you can use a similar CTE (MySQL 8.0+) or a multi-table delete. Before deleting, always back up the table. A safer approach is to first select the rows to be deleted into a temporary table, review them, and then delete. Also, consider adding a unique constraint after cleaning to prevent future duplicates.
Common Pitfalls and Performance Tips
Counting duplicates on large tables can be slow if the columns are not indexed. Adding an index on the grouping columns can speed up the GROUP BY operation. Also, be careful with NULL values: GROUP BY treats all NULLs as a single group, so if a column has many NULLs, they will appear as one duplicate group. If you want to exclude NULLs, add WHERE column IS NOT NULL before grouping. Another pitfall is using HAVING COUNT(*) > 1 when you actually want to count rows that have at least one duplicate elsewhere; that is a different query. Finally, always test your duplicate-counting query on a subset of data before running it on the full table, especially if you plan to delete.
Frequently Asked Questions
How do I count duplicates in SQL without grouping?
You can use a subquery to get the count for each row, like SELECT id, (SELECT COUNT(*) FROM table t2 WHERE t2.col = t1.col) AS dup_count FROM table t1;. This shows the count for every row, but it is inefficient for large tables. The GROUP BY approach is almost always better.
What is the difference between COUNT(*) and COUNT(column)?
COUNT(*) counts all rows in the group, including rows with NULL values. COUNT(column) counts only rows where that column is not NULL. For duplicate detection, you usually want COUNT(*) because you are counting rows, not values.
Can I use HAVING without GROUP BY?
Yes, but it applies to the entire result set as a single group. For example, SELECT COUNT(*) FROM orders HAVING COUNT(*) > 100 returns a single row if the total count exceeds 100. It is rarely used for duplicate detection because you need per-value counts.
How do I find duplicates in a table with no primary key?
You can still use GROUP BY on the columns that define a duplicate. Without a primary key, you cannot easily reference individual rows, so you might need to add an identity column temporarily or use ROW_NUMBER() to assign a unique number.
Does SQL Server have a specific duplicate count function?
No, SQL Server does not have a built-in ‘count duplicates’ function. You use the standard GROUP BY and COUNT(*) pattern. Some tools like MySQL have GROUP BY ... WITH ROLLUP for subtotals, but that is not specifically for duplicates.
How can I count duplicates across two tables?
If you need to count how many times values in one table appear in another, use a LEFT JOIN and GROUP BY. For example, SELECT a.id, COUNT(b.id) FROM table_a a LEFT JOIN table_b b ON a.id = b.id GROUP BY a.id; gives the count of matching rows in table_b for each row in table_a.
Related
- Select a Cell Shortcut: Top Excel Keyboard Shortcuts
- How Much Coding for Data Entry? A Practical Guide
- Google Sheets VLOOKUP: How to Use It Correctly
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- CATIA Convert Product to Part: Steps, Links, and LimitsIn CATIA V5, you can create a CATPart from a CATProduct assembly with the Tools > Generate CATPart…
- Excel Shortcut to Go to the Last Row With Data QuicklyIn Excel for Microsoft 365 on Windows, press Ctrl+Down Arrow from a filled cell to jump to the…
- VLOOKUP with Two Lookup Values in Google Sheets ExplainedYes. To use VLOOKUP with two lookup values in Google Sheets, combine the values into one key on…
- Excel Named Range Scope Greyed Out? Causes and FixesIf the Scope field is greyed out while you edit a named range in Excel, that is usually…
- Excel Split Numbers From Text: 4 Easy WaysTo split numbers from text in Excel, use Flash Fill (Excel 2013 and later) for a quick one-time…
- Cleaning Checklist Template Excel: Setup and Tips for TeamsA cleaning checklist template in Excel is a worksheet that lists cleaning tasks, when they are due, who…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.