Is it possible to combine multiple CTEs in single query with arel? I am looking for way to get result like this:
WITH cte1 AS ( ... ), WITH RECURSIVE cte2 AS ( ... ), WITH cte3 AS ( ... ) SELECT ... FROM cte3 WHERE ...  As you can see, I have one recursive CTE and two non recursive.
After learning common table expressions or CTEs, a natural question is “Can I use several CTEs in one query?” Yes, you can!
A CTE is similar to a derived table in that it is not stored and lasts only for the duration of the query. Unlike a derived table, a CTE behaves more like an in-line view and can be referenced multiple times in the same query. Using a CTE makes complex queries easier to read and maintain.
Nested CTEs is a scenario where one CTE references another CTE in it.
Use the key word WITH once at the top. If any of your Common Table Expressions (CTE) are recursive (rCTE) you have to add the keyword RECURSIVE at the top once also, even if not all CTEs are recursive:
WITH RECURSIVE   cte1 AS (...)         -- can still be non-recursive , cte2 AS (SELECT ...            UNION ALL            SELECT ...)  -- recursive term , cte3 AS (...) SELECT ... FROM cte3 WHERE ...  The manual:
If
RECURSIVEis specified, it allows aSELECTsubquery to reference itself by name.
Bold emphasis mine. And, even more insightful:
Another effect of
RECURSIVEis thatWITHqueries need not be ordered: a query can reference another one that is later in the list. (However, circular references, or mutual recursion, are not implemented.) WithoutRECURSIVE,WITHqueries can only reference siblingWITHqueries that are earlier in theWITHlist.
Bold emphasis mine again. Meaning that the order of WITH clauses is meaningless when the RECURSIVE key word has been used.
BTW, since cte1 and cte2 in the example are not referenced in the outer SELECT and are plain SELECT commands themselves (no collateral effects), they are never executed (unless referenced in cte3).
Yes.  You don't repeat the WITH.  You just use a comma:
WITH cte1 AS ( ... ),      cte2 AS ( ... ),      cte3 AS ( ... ) SELECT ... FROM 'cte3' WHERE ...   And: Only use single quotes for string and date constants. Don't use them for column aliases. They are not allowed for CTE names anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With