Escreva a palavra-chave WITH uma única vez no topo. Se alguma das suas Common Table Expressions for recursiva, acrescente RECURSIVE uma vez no topo também — mesmo que nem todas sejam recursivas:
WITH RECURSIVE cte1 AS (...), -- can still be non-recursive cte2 AS (SELECT ... UNION ALL SELECT ...), -- recursive term cte3 AS (...) SELECT ... FROM cte3 WHERE ...;O manual explica:
If
RECURSIVEis specified, it allows aSELECTsubquery to reference itself by name.
E, ainda mais útil:
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.
Em outras palavras, uma vez que RECURSIVE está presente, a ordem das cláusulas WITH se torna irrelevante.
De bônus: como cte1 e cte2 no exemplo não são referenciadas pelo SELECT externo e são SELECTs simples, sem efeitos colaterais, elas nunca são executadas a menos que referenciadas por cte3.