 	new_parent record;
 BEGIN
 	IF TG_OP = 'DELETE' THEN
-		SELECT * INTO old_parent FROM ip_net_plan WHERE vrf_id = OLD.vrf_id AND prefix >> OLD.prefix ORDER BY prefix DESC LIMIT 1;
+		SELECT * INTO old_parent FROM ip_net_plan WHERE vrf_id = OLD.vrf_id AND iprange(prefix) >> iprange(OLD.prefix) ORDER BY prefix DESC LIMIT 1;
 
 		-- parent is NULL if we are top level
 		IF old_parent.id IS NULL THEN

		-- table has already been updated and we risk getting ourself as
		-- old_parent.
		IF TG_OP = 'UPDATE' THEN
			SELECT * INTO old_parent FROM ip_net_plan WHERE vrf_id = OLD.vrf_id AND prefix >> OLD.prefix AND prefix != NEW.prefix ORDER BY prefix DESC LIMIT 1;
		ELSE
			SELECT * INTO old_parent FROM ip_net_plan WHERE vrf_id = OLD.vrf_id AND prefix >> OLD.prefix ORDER BY prefix DESC LIMIT 1;
		END IF;

		IF old_parent.id IS NOT NULL THEN

		-- This only sets number of children prefixes for the new parent
		-- prefix. The number of children for the prefix being modified is
		-- calculated in the before trigger.
		SELECT * INTO new_parent FROM ip_net_plan WHERE vrf_id = NEW.vrf_id AND iprange(prefix) >> iprange(NEW.prefix) ORDER BY prefix DESC LIMIT 1;
		IF new_parent.id IS NOT NULL THEN
			UPDATE ip_net_plan SET children =
					(SELECT COUNT(1)
					FROM ip_net_plan
					WHERE vrf_id = NEW.vrf_id
						AND iprange(prefix) << iprange(new_parent.prefix)
						AND indent = new_parent.indent+1)
				WHERE id = new_parent.id;
		END IF;
