Delete p1 from person p1 join person p2 on p1.email = p2.email and p1.id > p2.id find…
- User
Delete p1 from person p1 join person p2 on p1.email = p2.email and p1.id > p2.id find using window functions
- Assistant
To find and delete duplicate records using window functions, you can use the following query:
WITH cte AS ( SELECT p1.*, ROW_NUMBER() OVER (PARTITION BY p1.email ORDER BY p1.id) AS row_num FROM person p1 JOIN person p2 ON p1.email = p2.email AND p1.id > p2.id ) DELETE FROM cte WHERE row_num > 1;This query will assign a row number to each record within each email group, ordering them by their respective ID values. Then, it will delete all but the first record within each email group.
- User
View or function 'cte' is not updatable because the modification affects multiple base tables.
- Assistant
Apologies for the confusion. You're right, the previous approach using a Common Table Expression (CTE) is not directly updatable. Instead, we can use a subquery with a window function to identify the duplicate records and delete them.
Here's an alternative approach:
DELETE FROM person WHERE id IN ( SELECT id FROM ( SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS row_num FROM person ) subquery WHERE row_num > 1 );In this query, the inner subquery assigns a row number to each record within each email group, ordered by their respective ID values. Then, the outer query deletes all records where the row number is greater than 1, effectively deleting the duplicate records.
Please note that running this query directly will delete the duplicate records without any further confirmation, so please make sure to backup your data or proceed with caution.