BBampaa

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

Example

Keep one copy, delete the rest

SELECT *,
       ROW_NUMBER() OVER (
         PARTITION BY order_id
         ORDER BY line_id
       ) AS rn
FROM orders_raw

Result:

line_idorder_idcustomer_idrevenuern
L1O2001C10189.991
L2O2001C10189.992
L3O2002C10245.51
L4O2003C103120.01
L5O2003C103120.02

Step by step

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

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

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_raw
2. 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_raw
3. 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_raw

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