Loop
Experimental
loop {step_function} {initial_relation}
Iteratively applies step
function to initial
relation until the step
returns an empty table. Returns a relation that contains rows of initial relation and all intermediate relations.
This behavior could be expressed with following pseudo-code:
def loop(step, initial):
result = []
current = initial
while current is not empty:
result = append(result, current)
current = step(current)
return result
Examples
PRQL
from_text format:json '[{"n": 1 }]'
loop (
filter n<4
select n = n+1
)
# returns [1, 2, 3, 4]
SQL
WITH table_0 AS (
SELECT
1 AS n
),
table_4 AS (
WITH RECURSIVE _loop AS (
SELECT
n
FROM
table_0 AS table_1
UNION
ALL
SELECT
n + 1
FROM
_loop AS table_2
WHERE
n < 4
)
SELECT
*
FROM
_loop
)
SELECT
n
FROM
table_4 AS table_3
Note
The behavior of WITH RECURSIVE
may depend on the database configuration in MySQL. The compiler assumes the behavior described by the Postgres documentation and will not produce correct results for alternative configurations of MySQL.
Note
Currently, loop
may produce references to the recursive CTE in sub-queries, which is not supported by some database engines, e.g. SQLite. For now, we suggest step functions are kept simple enough to fit into a single SELECT statement.