UPDATE requests SET patient_id = id_map.new_id FROM ( SELECT id AS old_id, MIN(id) OVER (PARTITION BY participant_id, external_id) AS new_id FROM patients ) AS id_map WHERE patient_id = id_map.old_id AND id_map.old_id != id_map.new_id; DELETE FROM patients WHERE id NOT IN ( SELECT MIN(id) FROM patients GROUP BY participant_id, external_id );