Lessons › SQL › Deep Dive: Data Cleaning
SQL lesson
Detecting duplicates with GROUP BY and HAVING COUNT(*) > 1
Grouping rows by a shared value and then filtering for groups where the count exceeds one is how you surface duplicates hiding in a dataset.
Try this lesson free →Example
Detecting Duplicate Retail Orders
SELECT order_id, customer_id, product_id, order_date, COUNT(*) AS occurrence_count
FROM orders
GROUP BY order_id, customer_id, product_id, order_date
HAVING COUNT(*) > 1| order_id | customer_id | product_id | order_date | occurrence_count |
|---|---|---|---|---|
| O2001 | C101 | P55 | 2024-03-10 | 2 |
| O2002 | C102 | P88 | 2024-03-11 | 2 |
Step by step
- Run the query without COUNT so you can see what the unfiltered values look like.
SELECT order_id, customer_id, product_id, order_date, * FROM orders GROUP BY order_id, customer_id, product_id, order_date HAVING COUNT(*) > 1; - COUNT tells you how many rows match - perfect for sizing a table.
SELECT order_id, customer_id, product_id, order_date, COUNT(*) FROM orders GROUP BY order_id, customer_id, product_id, order_date HAVING COUNT(*) > 1; - AS gives the COUNT result a friendly column name so the output reads cleanly.
SELECT order_id, customer_id, product_id, order_date, COUNT(*) AS occurrence_count FROM orders GROUP BY order_id, customer_id, product_id, order_date HAVING COUNT(*) > 1;
Practice
1. Using customers, write a query to find email values that appear more than once.
SELECT email, COUNT(*) FROM customers GROUP BY email HAVING COUNT(*) > 12. Using products, write a query to find product_id values that appear more than once.
SELECT product_id, COUNT(*) FROM products GROUP BY product_id HAVING COUNT(*) > 13. Using orders, write a query to find order_id values that appear more than once.
SELECT order_id, COUNT(*) FROM orders GROUP BY order_id HAVING COUNT(*) > 14. Using inventory, write a query to find product_id values that appear more than once.
SELECT product_id, COUNT(*) FROM inventory GROUP BY product_id HAVING COUNT(*) > 15. Using reviews, write a query to find customer_id values that appear more than once.
SELECT customer_id, COUNT(*) FROM reviews GROUP BY customer_id HAVING COUNT(*) > 1Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →