Sub topic 14
Removing duplicate rows with ROW_NUMBER
This chapter assumes you can write ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...), use inline views, and run DELETE statements inside a transaction. It applies those pieces to one job: finding duplicate rows, choosing which copy to keep, and deleting the rest.
Why ROW_NUMBER fits this job
Duplicate rows are rows that repeat the same business key, such as the same email address in a customers table. You want to keep one row per key and remove the others.
ROW_NUMBER suits this because it gives every row in a partition a unique number, even when rows tie. If you partition by the business key, the row numbered 1 in each partition is the survivor. Every row numbered 2 or higher is a duplicate.
The plan has three parts:
- Partition by the columns that define "the same row".
- Order each partition so the row you want to keep gets number 1.
- Delete (or filter out) every row whose number is greater than 1.
Sample data
The examples use this table. Run the script to follow along.
CREATE TABLE customers (
customer_id NUMBER PRIMARY KEY,
email VARCHAR2(100),
created_at DATE
);
INSERT INTO customers VALUES (1, '[email protected]', DATE '2024-01-05');
INSERT INTO customers VALUES (2, '[email protected]', DATE '2024-01-06');
INSERT INTO customers VALUES (3, '[email protected]', DATE '2024-02-10');
INSERT INTO customers VALUES (4, '[email protected]', DATE '2024-02-10');
INSERT INTO customers VALUES (5, '[email protected]', DATE '2024-03-01');
INSERT INTO customers VALUES (6, '[email protected]', DATE '2024-03-02');
COMMIT;Rows 1, 3, and 4 share an email, and rows 3 and 4 also share a created_at value. Rows 2 and 5 share another email. Row 6 is unique.
Step 1: preview before you delete
Never start with the DELETE. First write a SELECT that shows the number each row receives.
SELECT customer_id,
email,
created_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at, customer_id
) AS rn
FROM customers
ORDER BY email, rn;The result:
| customer_id | created_at | rn | |
|---|---|---|---|
| 1 | [email protected] | 2024-01-05 | 1 |
| 3 | [email protected] | 2024-02-10 | 2 |
| 4 | [email protected] | 2024-02-10 | 3 |
| 2 | [email protected] | 2024-01-06 | 1 |
| 5 | [email protected] | 2024-03-01 | 2 |
| 6 | [email protected] | 2024-03-02 | 1 |
Rows 3, 4, and 5 have rn > 1, so they are the rows the cleanup will remove. Check this list against your expectations before you go on.
Step 2: delete everything except the first row
You cannot put an analytic function in a WHERE clause, so the numbering must happen in an inline view. The outer query then filters on the computed rn. This is the same structure you used for top-N queries.
DELETE FROM customers
WHERE rowid IN (
SELECT rid
FROM (
SELECT rowid AS rid,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at, customer_id
) AS rn
FROM customers
)
WHERE rn > 1
);After this runs, rows 3, 4, and 5 are gone. Check the result, then COMMIT or ROLLBACK.
The statement identifies rows by ROWID, the physical address of a row in an ordinary table. ROWID is unique per row, so it works even when the table has no primary key and the rows are complete copies of each other. If the table does have a key, as customers does, you can select and match customer_id instead. That is easier to read and to audit.
Choosing which row survives
The ORDER BY inside OVER decides which row gets number 1. This is the only place where you express your keep rule.
| Keep rule | Window ORDER BY |
|---|---|
| Oldest row | `created_at, customer_id` |
| Newest row | `created_at DESC, customer_id DESC` |
| Most complete row | `CASE WHEN phone IS NULL THEN 1 ELSE 0 END, created_at` |
The last rule orders rows that have a phone number before rows that lack one, then falls back to age. ORDER BY puts the smaller sort key first, so rows with key 0 come first and get the lower numbers.
The tiebreaker column matters. Rows 3 and 4 have the same created_at. With ORDER BY created_at alone, Oracle may assign them 2 and 3 in either order, and two runs could delete different rows. Adding customer_id makes the order total, so the result is the same every time. Always end the window ORDER BY with a column, or set of columns, that is unique within the partition.
Defining "duplicate" carefully
The PARTITION BY list defines what counts as a duplicate. Three details cause most mistakes.
- Several columns. To treat rows as duplicates only when both columns match, list both:
PARTITION BY first_name, last_name, birth_date. - NULLs. Rows whose partition column is
NULLare placed in the same partition. IfemailisNULLin 500 rows, the statement keeps one of them and deletes 499. Filter them out when that is not what you want, for example by addingWHERE email IS NOT NULLinside the inline view. - Near-duplicates.
[email protected]and[email protected](with a trailing space) are different strings, so they land in different partitions. Normalize inside the partition list:PARTITION BY LOWER(TRIM(email)).
Why not RANK or DENSE_RANK?
RANK and DENSE_RANK give tied rows the same number. If rows 3 and 4 tie on created_at, both receive the same rank, and a filter on rank > 1 would treat them the same way. A filter on rank = 1 can also keep more than one row per group. Only ROW_NUMBER guarantees exactly one row numbered 1 in each partition. That guarantee is what makes it the right tool for deduplication.
Selecting the unique rows without deleting
Sometimes you only need a clean result set, or you want to build a new table. Keep the rows where rn = 1:
SELECT customer_id, email, created_at
FROM (
SELECT c.*,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at, customer_id
) AS rn
FROM customers c
)
WHERE rn = 1;For a very large table where most rows are duplicates, copying the survivors into a new table with CREATE TABLE ... AS SELECT using this query is often faster than deleting millions of rows. A large DELETE generates undo and redo for every row. After the copy, you swap the tables and rebuild the indexes and constraints.
Preventing the problem
Deduplication is a one-time repair. To stop duplicates from returning, add a constraint once the data is clean:
CREATE UNIQUE INDEX customers_email_uq
ON customers (LOWER(email));The index fails if duplicates still exist, which makes it a useful final check. Because it indexes LOWER(email), it also blocks case-only variants. Your application should compare emails the same way.
Common errors
- ORA-30483: window functions are not allowed here. You put
ROW_NUMBERdirectly in theWHEREclause. Move it into an inline view and filter in the outer query. - Deleting the wrong copy. The window
ORDER BYruns ascending by default, so number 1 is the smallest value. AddDESCwhen you want to keep the newest row. - Different results on each run. The window
ORDER BYhas no unique tiebreaker. - Too many rows deleted. The
PARTITION BYlist is too short, orNULLkeys were not excluded.
Exercise
The table orders(orderid, customerid, orderdate, status) contains repeated rows for the same customerid and orderdate. Write a DELETE that keeps only the row with the highest orderid in each customerid and orderdate group. Which clause of the window decides which row survives?
Show answer
DELETE FROM orders WHERE rowid IN (SELECT rid FROM (SELECT rowid AS rid, ROWNUMBER() OVER (PARTITION BY customerid, orderdate ORDER BY orderid DESC) AS rn FROM orders) WHERE rn > 1); The ORDER BY inside OVER decides the survivor. Sorting orderid in descending order gives the highest orderid the number 1, so it is kept. Because order_id is unique, no further tiebreaker is needed.
Exercise
A colleague replaces ROW_NUMBER with RANK in a deduplication DELETE and finds that some duplicates remain. Why does this happen, and how do you fix it?
Show answer
When two rows tie on the window ORDER BY columns, RANK gives them the same rank. If that rank is 1, the filter rank > 1 does not select either row, so both are kept. Use ROW_NUMBER, which numbers tied rows 1, 2, 3 and so on, and add a unique tiebreaker column to the ORDER BY so the choice of survivor is repeatable.