SQL Guide · Prompt: “Select unique customers and latest signup count from the customers table”
Delete Duplicate Rows in SQL While Keeping One Record
Verified by LiveFormulaLab Engineering Team • Updated November 2026
Safely deduplicate SQL tables using a CTE and ROW_NUMBER() window function while preserving the newest or lowest ID record cleanly.
Verified SQL Syntax
SELECT email, COUNT(*) AS rows_found
FROM customers
GROUP BY email;How This Formula Works (Step-by-Step)
Before deleting duplicates in production, preview them with GROUP BY or ROW_NUMBER() inside a CTE.
Step 1: Assign rn = ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC) so the newest record gets rn = 1.
Step 2: Delete rows where rn > 1 (or filter WHERE rn = 1 in a SELECT view) to retain one clean copy.
Formula Syntax & Arguments Breakdown
Identifies duplicate records cleanly by numbering each occurrence inside a CTE with ROW_NUMBER() OVER (PARTITION BY key ORDER BY keep_priority) before removing rows where rn > 1.
| Argument / Clause | Requirement | Data Type | Role & Behavior |
|---|---|---|---|
PARTITION BY email | Required | Deduplication Key | Groups rows sharing the identical email or natural key so one survivor can be kept. |
ORDER BY id ASC (or created_at DESC) | Required | Survivor Rule | Determines which duplicate row receives rn = 1 and survives deletion (oldest vs newest). |
WHERE rn > 1 | Required | Deletion Filter | Targets only redundant copies for deletion while preserving every unique row and the #1 copy. |
3 Real-World Use Cases
- Deduplicating imported CRM contacts after a double CSV upload.
- Cleaning historical event logs where network retries created twin records.
- Preparing clean user tables before applying a UNIQUE email index.
Cross-Platform Equivalents
- Excel
=UNIQUE(B2:B6)- SQL
DELETE FROM customers WHERE id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC) AS rn FROM customers) t WHERE rn > 1);- Python Pandas
df.sort_values('created_at', ascending=False).drop_duplicates(subset=['email'], keep='first')
Common Mistakes & Pro Tips
Pitfalls & How to Fix Them
Mistake: Running DELETE without first previewing the CTE with SELECT * risks wiping valid data if PARTITION BY misses a column.
Fix: Always run a read-only SELECT preview of rows where rn > 1 (and wrap DELETE in BEGIN; ... ROLLBACK/COMMIT;) before deleting.
Mistake: Attempting DELETE FROM cte_name directly fails in PostgreSQL because Postgres CTEs are not directly updatable targets.
Fix: In Postgres, run DELETE FROM customers WHERE id IN (SELECT id FROM ranked WHERE rn > 1); in SQL Server/Snowflake, DELETE FROM cte works directly.
Mistake: Ignoring foreign-key references on duplicate IDs causes constraint violations during cleanup.
Fix: Re-point child foreign keys (orders.customer_id) to the surviving rn = 1 ID before deleting duplicate parent records.
Engineering Pro Tips
- Add a deterministic primary-key tiebreaker (ORDER BY updated_at DESC, id DESC) so tied timestamps never choose randomly.
- When auditing table size before deleting, SELECT email, COUNT(*) AS rows_found GROUP BY email HAVING COUNT(*) > 1 shows scope safely.
- Back up affected rows into a staging table (CREATE TABLE customers_dups_backup AS ...) before large production cleanups.
Frequently Asked Questions
- How do I test a deduplication DELETE safely?
- Always run the CTE with a SELECT * FROM cte WHERE rn > 1 first inside a transaction before running DELETE.
- Does DELETE FROM cte work in MySQL?
- In MySQL, join the table against the subquery or use DELETE c FROM customers c JOIN ... WHERE rn > 1.
- Should I keep the oldest or newest duplicate?
- Order by id ASC to keep the original record, or created_at DESC to keep the latest update.
Related Formulas & Guides
- Pivot Rows to Columns in SQL with Conditional Aggregation — Turn row categories into cross-tab columns in standard ANSI SQL using conditional aggregation SUM(CASE WHEN). Works in Postgres, MySQL, and Snowflake.
- Build Customer First-Purchase Cohorts in SQL — Find each customer first purchase date and segment orders into cohorts in SQL using MIN() OVER (PARTITION BY) or GROUP BY.
- Handle NULL Values Cleanly in SQL with COALESCE — Replace NULL values cleanly with 0 or fallback text in SQL LEFT JOIN queries using COALESCE. Includes Excel and Pandas equivalents.
- How to Find Duplicate Rows in SQL Using GROUP BY — Find duplicate emails, IDs, or records in any SQL table using GROUP BY and HAVING COUNT(*) > 1. Test live in the interactive SQL sandbox.