1

This is kind of a subjective question.

If I have a recursive CTE something like:

WITH RECURSIVE r(x, y) AS ( ...
    SELECT x, y -- select1
    FROM t WHERE .. 
    UNION
    SELECT t.x, t.y -- select2
    FROM r JOIN t
    ON ...
)
SELECT x, y
FROM r

What exactly is the point of specifying the list of columns as an argument in the CTE definition? If I don't specify it, it anyways takes the list of columns in the SELECT.

If I do specify it, every time I want to make changes, I have to reflect that in both the SELECTs in the CTE and also in the argument list.

What benefit do I gain from writing WITH RECURSIVE r(x, y) AS instead of just WITH RECURSIVE r AS?

0

1 Answer 1

4

What exactly is the point of specifying the list of columns as an argument in the CTE definition?

This comes from the SQL Standard. It's another option to name the columns of the CTE.

If I don't specify it, it anyways takes the list of columns in the SELECT.

That is correct. If you don't specify it, the list of columns in the SELECT is used (and if it is a UNION/INTERSECT/EXCEPT query, the list of columns in the first of them. The 2nd and following lists are ignored).

If I do specify it, every time I want to make changes, I have to reflect that in both the SELECTs in the CTE and also in the argument list.

Incorrect. If you change the names in the "argument list", you don't have to make any change in the SELECT list. The argument list overrides the SELECT list names. You only need to change both if you add more or remove columns from the CTE.

2
  • 1
    Well, both lists have to be edited if you want to add another column, right? Commented Dec 14, 2022 at 9:28
  • 1
    @LaurenzAlbe yes, indeed. If you want to add or remove columns, both lists have to be edited (and also all the other parts if it's a UNION/INTERSECT/EXCEPT subquery). Commented Dec 14, 2022 at 9:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.