CREATE OR REPLACE FUNCTION tag_path(in_tag_id INTEGER) RETURNS text AS $$ DECLARE r text; id INTEGER; BEGIN IF in_tag_id IS NULL THEN RETURN null; END IF; SELECT name, parent_id INTO r,id FROM tags WHERE tag_id=in_tag_id; IF (id IS NULL) THEN RETURN r; ELSE RETURN tag_path(id)||'->'||coalesce(r,''); END IF; END; $$ LANGUAGE plpgsql STABLE;