Skip to content

Instantly share code, notes, and snippets.

@lucassmacedo
Last active February 22, 2019 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucassmacedo/deebace1dad9a428b412643aada61825 to your computer and use it in GitHub Desktop.
Save lucassmacedo/deebace1dad9a428b412643aada61825 to your computer and use it in GitHub Desktop.
Recursive Parent ID PGSQL
# https://wiki.postgresql.org/wiki/Getting_list_of_all_children_from_adjacency_tree
# https://www.depesz.com/2009/03/23/getting-list-of-all-children-in-adjacency-list-tree-structure/
CREATE OR REPLACE FUNCTION get_all_children_array(use_parent INT4) RETURNS INT4[] AS
$$
DECLARE
process_parents INT4[] := ARRAY [ use_parent ];
children INT4[] := '{}';
new_children INT4[];
BEGIN
WHILE (array_upper(process_parents, 1) IS NOT NULL)
LOOP
new_children :=
ARRAY(SELECT id FROM ferramentas WHERE parent_id = ANY (process_parents) AND id <> ALL (children));
children := children || new_children;
process_parents := new_children;
END LOOP;
RETURN children;
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment