Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PostgreSQL: Run CTE and then Recursive query on the CTE

I am trying to run a recursive query in PostgreSQL. I need it to find all people that belong under a team. The query is the following:

WITH TAB AS (
SELECT id as user_id, team_id
from users

union

select user_id,team_id
from team_units
),
RECURSIVE recuree AS (
    SELECT user_id, team_id
    from TAB
    
    UNION
    
    SELECT E.user_id, E.team_id
    from TAB E
    JOIN recuree S on E.team_id = S.team_id)

SELECT * FROM recuree

I read that RECURSIVE must always followed from WITH.
But how can that happen since the TAB table doesn’t actually exist?

Thank you in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You might need to use WITH RECURSIVE, so you can try to use a subquery to instead TAB

RECURSIVE need to use UNION ALL instead of UNION

WITH RECURSIVE recuree AS (
    SELECT user_id, team_id
    from (
        SELECT id as user_id, team_id
        from users
        union
        select user_id,team_id
        from team_units
    ) t1
    UNION ALL
    SELECT E.user_id, E.team_id
    from (
        SELECT id as user_id, team_id
        from users
        union
        select user_id,team_id
        from team_units
    ) E
    JOIN recuree S on E.team_id = S.team_id
)
SELECT * 
FROM recuree

otherwise, you can try to create a view first

CREATE VIEW v_TAB AS 
SELECT id as user_id, team_id
from users
union
select user_id,team_id
from team_units;

then do CTE RECURSIVE

WITH RECURSIVE recuree AS (
    SELECT user_id, team_id
    from v_TAB
    UNION ALL
    SELECT E.user_id, E.team_id
    from v_TAB E
    JOIN recuree S on E.team_id = S.team_id
)
SELECT * 
FROM recuree;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading