Lessons › SQL › Chapter 9: Data Cleaning
SQL lesson
Removing duplicates with ROW_NUMBER() and DELETE
Last level found the duplicates. Now remove them, but keep one copy of each. ROW_NUMBER numbers each copy: the first is 1, the extra copies are 2, 3 and so on. Then DELETE removes every row numbered above 1. DELETE changes the table for good, so you look at the numbers with SELECT first.
Try this lesson free →Example
Keep one copy, delete the rest
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY line_id
) AS rn
FROM orders_raw| line_id | order_id | customer_id | revenue | rn |
|---|---|---|---|---|
| L1 | O2001 | C101 | 89.99 | 1 |
| L2 | O2001 | C101 | 89.99 | 2 |
| L3 | O2002 | C102 | 45.5 | 1 |
| L4 | O2003 | C103 | 120.0 | 1 |
| L5 | O2003 | C103 | 120.0 | 2 |
Step by step
- Each order's copies get 1, 2, and so on. Anything above 1 is an extra copy.
SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY line_id) AS rn FROM orders_raw - Put the numbering in a CTE, then delete the rows numbered above 1.
WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY line_id) AS rn FROM orders_raw) DELETE FROM orders_raw WHERE line_id IN (SELECT line_id FROM ranked WHERE rn > 1)
Practice
1. Using orders_raw, number each copy of every order, first line_id first. Name it rn.
SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY line_id) AS rn FROM orders_raw2. Using sales_raw, number each copy: rows that match in every column except sale_id. Lowest sale_id first. Name it rn.
SELECT *, ROW_NUMBER() OVER (PARTITION BY store, product, qty, sold_on ORDER BY sale_id) AS rn FROM sales_raw3. Using customers_raw, number each email's rows, earliest signup_date first. Name it rn.
SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY signup_date) AS rn FROM customers_rawLearn 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 →