Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Created October 30, 2024 17:17
Show Gist options
  • Save trvswgnr/2407923609561a295b9fa36789f63fa1 to your computer and use it in GitHub Desktop.
Save trvswgnr/2407923609561a295b9fa36789f63fa1 to your computer and use it in GitHub Desktop.
query that returns a tree in json (full tree from root or subtree from node n) with RCTE
CREATE OR REPLACE FUNCTION build_tree(parent_id INTEGER DEFAULT NULL)
RETURNS JSONB AS $$
DECLARE
result JSONB;
count INTEGER;
BEGIN
SELECT COUNT(*)
INTO count
FROM nodes n
WHERE n.parent_id IS NOT DISTINCT FROM $1;
WITH children AS (
SELECT
n.id,
n.name,
build_tree(n.id) as child_tree
FROM nodes n
WHERE n.parent_id IS NOT DISTINCT FROM $1
)
SELECT COALESCE(
jsonb_agg(
jsonb_build_object(
'id', name,
'children', COALESCE(child_tree, '[]'::jsonb)
)
),
'[]'::jsonb
)
INTO result
FROM children;
RETURN result;
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment