 	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

	-- if an assignment contains hosts, we block the delete
	IF OLD.type = 'assignment' THEN
		-- contains one child prefix
		IF (SELECT COUNT(1) FROM ip_net_plan WHERE iprange(prefix) << iprange(OLD.prefix) AND vrf_id = OLD.vrf_id LIMIT 1) > 0 THEN
			RAISE EXCEPTION '1200:Prohibited delete, prefix (%) contains hosts.', OLD.prefix;
		END IF;
	END IF;
