 					(SELECT COUNT(1)
 					FROM ip_net_plan
 					WHERE vrf_id = OLD.vrf_id
-						AND prefix << old_parent.prefix
+						AND iprange(prefix) << iprange(old_parent.prefix)
 						AND indent = old_parent.indent+1)
 				WHERE id = old_parent.id;
 		END IF;

	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;

		-- 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 iprange(prefix) >> iprange(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 iprange(prefix) >> iprange(OLD.prefix) ORDER BY prefix DESC LIMIT 1;
		END IF;

		IF old_parent.id IS NOT NULL THEN
