CREATE OR REPLACE FUNCTION tag_id(in_tag_path text) RETURNS integer AS $$ DECLARE id INTEGER:=null; component text; BEGIN FOR component IN SELECT regexp_split_to_table(in_tag_path, '->') LOOP SELECT tag_id FROM tags WHERE upper(NAME)=upper(component) AND parent_id is not distinct from id INTO id; END LOOP; RETURN id; END; $$ LANGUAGE plpgsql STABLE STRICT;