Bugfix: move DELETE queries to the end to prevent foreign key constraint conflicts