CREATE TEMPORARY TABLE ad_to_delete AS
(
    --regions
    SELECT ad_id
    FROM ad
    WHERE level_kind = 0

    UNION

    --ad_neutrals
    SELECT ad_id
    FROM ad_isocode
    WHERE isocode BETWEEN '500' AND '999'
);

ALTER TABLE ad_to_delete ADD PRIMARY KEY(ad_id);

DELETE FROM node_isocode
USING ad_center, ad_to_delete
WHERE node_isocode.node_id = ad_center.node_id
AND ad_center.ad_id = ad_to_delete.ad_id;

DELETE FROM node_isocode
USING edge, face_edge, ad_face, ad_to_delete
WHERE (node_id = f_node_id OR node_id = t_node_id)
AND edge.edge_id = face_edge.edge_id
AND face_edge.face_id = ad_face.face_id
AND ad_face.ad_id = ad_to_delete.ad_id;

DELETE FROM edge_isocode
USING face_edge, ad_face, ad_to_delete
WHERE edge_isocode.edge_id = face_edge.edge_id
AND face_edge.face_id = ad_face.face_id
AND ad_face.ad_id = ad_to_delete.ad_id;

DELETE FROM face_isocode
USING ad_face, ad_to_delete
WHERE face_isocode.face_id = ad_face.face_id
AND ad_face.ad_id = ad_to_delete.ad_id;

DELETE FROM ad_isocode
USING ad_to_delete
WHERE ad_isocode.ad_id = ad_to_delete.ad_id;

