BBampaa

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 →
About 5–10 minutes · no sign-up needed

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

Result:

order_idcustomer_idproduct_idorder_dateoccurrence_count
O2001C101P552024-03-102
O2002C102P882024-03-112

Step by step

  1. 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
  2. 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
  3. 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
  4. 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

Try each one in your head first, then open the answer.

1. Using customers, find the email values that appear more than once.
SELECT email, COUNT(*) FROM customers GROUP BY email HAVING COUNT(*) > 1
2. Using products, find the product_id values that appear more than once.
SELECT product_id, COUNT(*) FROM products GROUP BY product_id HAVING COUNT(*) > 1
3. 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(*) > 1
4. Using orders, find the order_id values that appear more than once.
SELECT order_id, COUNT(*) FROM orders GROUP BY order_id HAVING COUNT(*) > 1
5. Using inventory, find the product_id values that appear more than once.
SELECT product_id, COUNT(*) FROM inventory GROUP BY product_id HAVING COUNT(*) > 1

Learn 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 →
About 5–10 minutes · no sign-up needed