Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to combine recursive CTE and normal CTE

Tags:

postgresql

I want a first a normal CTE on table and followed by a recursive CTE

how can I combine this two?

I know for multiple pure normal CTE I can do

WITH CTE1 AS(
), CTE2 AS(),...

so I have tried

WITH CTE1 AS(
), RECURSIVE CTE2()

but that gives me a syntax error

like image 573
Hello lad Avatar asked Nov 06 '14 16:11

Hello lad


People also ask

Can we join two CTE?

A straightforward question deserves a straightforward answer: yes, you can. Now that you know how to use multiple CTEs, writing a CTE that references another CTE is just a variation of what you've learned.

Can I use 2 CTE in SQL?

The first CTE is separated from the second one by a comma. This also goes if you write more than two CTEs: all the CTEs are separated by a comma. However, no matter how many CTEs you have, there's no comma between the last CTE and the main query.

Can we use one CTE in another CTE?

You can create recursive CTE or use a reference of a CTE to another CTE. However there is a slight differences compared with other databases - The referenced CTE must be present after the referencing CTE.

Can we use same CTE multiple times?

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. Because a CTE can be referred to multiple times in a query, syntax can be simpler.


1 Answers

Just put the recursive at the start, even if the recursive one comes later:

with recursive cte1 as (
 ...
), cte2 as (
  -- here comes the recursive cte
  ...
)
select *
from ...
like image 66
a_horse_with_no_name Avatar answered Oct 27 '22 02:10

a_horse_with_no_name