Skip to content

Instantly share code, notes, and snippets.

@fabiojwalter
Created August 4, 2020 17:12
Show Gist options
  • Save fabiojwalter/0692f26a97101c4c15ef564e42b99850 to your computer and use it in GitHub Desktop.
Save fabiojwalter/0692f26a97101c4c15ef564e42b99850 to your computer and use it in GitHub Desktop.
SQL Query - Hierarchical user structure
WITH RECURSIVE subordinates AS (
SELECT
ur.user_id,
ur.owner_id
FROM
users.user_roles ur
WHERE
ur.user_id = 87 --DESIRED USER ID
UNION
SELECT
ur2.user_id,
ur2.owner_id
FROM
users.user_roles ur2
INNER JOIN subordinates s ON s.user_id = ur2.owner_id
) SELECT
*
FROM
subordinates;
@pedro-finamore
Copy link

TOP!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment