The general format of a recursive query is:
WITH RECURSIVE cte_name(arg1, arg2, arg3) AS( -- arg1, arg2 are column outputs from seed_data_query
seed_data_query -- non-recursive term, executes first
UNION ALL -- can be just UNION, which returns unique rows. It's slower.
recursive_query_based_on_seed_data -- recursive term
) SELECT * FROM cte_name;
When executing, the seed_data_query
executes first, giving a set of base results. Note that this is not the "base case" from recursion. In recursion, base case is a terminating clause and is the last to execute. Here, the non-recursive part acts as seed data for the recursive part. Termination of a recursive CTE happens when the recursive part yields 0 rows.
The result of seed_data_query
is passed as argument to the next query. For recursive_query_based_on_seed_data
, cte_name(arg1, arg2, arg3)
is available as a temporary table with columns arg1, arg2, arg3, etc. All your regular join operations are possible with this temporary table.