10

I have recursive query to retrieve all children of a given person

WITH RECURSIVE recursetree(id, parent_id) AS (
    SELECT id, parent_id FROM tree WHERE parent_id = 0
  UNION
    SELECT t.id, t.parent_id
    FROM tree t
    JOIN recursetree rt ON rt.id = t.parent_id
  )
SELECT * FROM recursetree;

As you can see, I'm specifying list of columns to be retrieved. But I want to use SELECT * (I have really many columns in real table, and they can be changed in future). Is there some way to get ALL columns without defining each column individually?

0

2 Answers 2

10

You don't need to specify the columns in the WITH part. If you leave that out, the column names will be determined by the first query in the UNION:

WITH RECURSIVE recursetree AS (
    SELECT * FROM tree WHERE parent_id = 0
  UNION
    SELECT t.*
    FROM tree t
    JOIN recursetree rt ON rt.id = t.parent_id
)
SELECT * 
FROM recursetree;
Sign up to request clarification or add additional context in comments.

4 Comments

Yours is cleaner! I don't know if the intermediate CTE object being "fatter" will affect performance, (I'm afraid it will)
@wildplasser: only an explain (analyze, verbose) can tell ;)
But I am too lazy to set up a test rig. I'd have to type in all the column names! catb.org/jargon/html/R/recursion.html
I just checked. My intuition was right. 100K rows(22columns, rowsize ~650) ; mine: 439.704ms, yours: 15984.338ms
7

quick hack-around (rejoin with the original):

WITH RECURSIVE recursetree(id, parent_id) AS (
    SELECT id, parent_id FROM tree WHERE parent_id = 0
  UNION
    SELECT t.id, t.parent_id
    FROM tree t
    JOIN recursetree rt ON rt.id = t.parent_id
  )
SELECT *
FROM tree tr
WHERE EXISTS ( SELECT 1
    FROM recursetree x
    WHERE x.id = tr.id
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.