Skip to content

Instantly share code, notes, and snippets.

@tlaitinen
Created May 9, 2018 09:31
Show Gist options
  • Select an option

  • Save tlaitinen/0656ce289cc4d7d05dc3ecabb2b57111 to your computer and use it in GitHub Desktop.

Select an option

Save tlaitinen/0656ce289cc4d7d05dc3ecabb2b57111 to your computer and use it in GitHub Desktop.
WITH RECURSIVE folder_tree(id, depth) AS (
SELECT
fo.id,
1
FROM
folder AS fo
WHERE (
(${ids}::bigint[] IS NULL AND fo.parent_folder_id IS NULL)
OR fo.id = ANY (${ids}::bigint[])
) AND fo.user_group_id = ${userGroupId}
UNION ALL
SELECT
fo.id,
ft.depth + 1
FROM
folder AS fo,
folder_tree AS ft
WHERE fo.parent_folder_id = ft.id
)
SELECT
fo.id,
ft.depth,
fo.user_group_id,
fo.user_id,
fo.name,
fo.parent_folder_id,
fo.active,
fo.insertion_time
FROM
folder_tree AS ft,
folder AS fo
WHERE
ft.id = fo.id
ORDER BY ft.depth, fo.name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment