Lessons › SQL › Chapter 9: Data Cleaning
SQL lesson
Detecting duplicates with GROUP BY and HAVING COUNT(*) > 1
GROUP BY puts rows with the same value together, and COUNT(*) counts each group. HAVING COUNT(*) > 1 keeps only the groups with more than one row: the duplicates.
Try this lesson free →Example
Find repeated rows
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
- Rows with the same order_id end up together.
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 - How many rows each order_id has.
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 - Only groups with more than one row: the duplicates.
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 - No repeated id? A copy matches on every value. List those columns.
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, find the email values that appear more than once.
SELECT email, COUNT(*) FROM customers GROUP BY email HAVING COUNT(*) > 12. Using products, find the product_id values that appear more than once.
SELECT product_id, COUNT(*) FROM products GROUP BY product_id HAVING COUNT(*) > 13. Using sales_raw, find the sales typed in twice: rows that match in every column except sale_id. Show the matching columns and times.
SELECT store, product, qty, sold_on, COUNT(*) AS times FROM sales_raw GROUP BY store, product, qty, sold_on HAVING COUNT(*) > 14. Using orders, find the order_id values that appear more than once.
SELECT order_id, COUNT(*) FROM orders GROUP BY order_id HAVING COUNT(*) > 15. Using inventory, find the product_id values that appear more than once.
SELECT product_id, COUNT(*) FROM inventory GROUP BY product_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 →