SQL Query to Remove Duplicate Records While Keeping Latest Entry

๐Ÿงน SQL Query to Remove Duplicate Records While Keeping the Latest Entry

Duplicate data is one of the most common problems in database management. In this tutorial, youโ€™ll learn how to remove duplicate records while keeping only the latest entry โ€” based on a timestamp or unique ID. This technique works in MySQL, SQL Server, Oracle, and PostgreSQL.

Weโ€™ll use a practical example with an orders table to demonstrate how to identify duplicates and safely delete older ones using ROW_NUMBER() and CTE (Common Table Expressions).

๐Ÿงฉ Sample Data: Orders Table

order_idcustomer_idorder_dateorder_amount
101C0012025-11-01500
102C0012025-11-03700
103C0022025-10-30450
104C0022025-11-04600

Notice that customer C001 and C002 have duplicate entries โ€” weโ€™ll keep only the most recent one.

๐Ÿ’ป SQL Query: Keep Only Latest Record Using ROW_NUMBER()

WITH ranked_orders AS (
  SELECT order_id, customer_id, order_date, order_amount,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
  FROM orders
)
DELETE FROM ranked_orders
WHERE rn > 1;

๐Ÿ’ก This query assigns a rank to each order grouped by customer_id, ordered by the latest order_date. Then it deletes all records except the first one (rn = 1), effectively removing duplicates.

๐Ÿ“Š Example Result

order_idcustomer_idorder_dateorder_amount
102C0012025-11-03700
104C0022025-11-04600

โœ… Both customers now have only their most recent orders remaining in the table.

โš™๏ธ Bonus: Find Duplicates Without Deleting

If you only want to identify duplicates (not delete them), use this query instead:

SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1;

This will list all customers having duplicate orders so you can manually review before running the delete command.

๐Ÿš€ Performance Tips

  • Always test the SELECT version of your DELETE query before executing it.
  • Add indexes on customer_id and order_date for faster filtering.
  • Use transactions (BEGIN TRANSACTION) when working on production databases.

๐Ÿ“˜ Recommended Books to Master SQL & Data Cleaning

These books are perfect for mastering SQL data management and reporting automation in Power BI.

๐Ÿ”— Related SQL Tutorials

๐Ÿ’ฌ Join the SQL Community

Have a SQL challenge or want to share your query? Join our discussion forum ๐Ÿ‘‰ SQLQueries.in Community Forum Connect with SQL learners, data engineers, and BI professionals.