create function child_tags(top_id integer) returns setof integer as $$ WITH RECURSIVE tagr(_tag_id) as ( select tag_id from tags where parent_id is not distinct from top_id UNION ALL select tag_id FROM tags JOIN tagr ON tagr._tag_id=tags.parent_id ) select _tag_id FROM tagr; $$ language sql stable