Loop

Experimental

  1. 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:

  1. def loop(step, initial):
  2. result = []
  3. current = initial
  4. while current is not empty:
  5. result = append(result, current)
  6. current = step(current)
  7. return result

Examples

PRQL

  1. from [{n = 1}]
  2. loop (
  3. filter n<4
  4. select n = n+1
  5. )
  6. # returns [1, 2, 3, 4]

SQL

  1. WITH RECURSIVE table_0 AS (
  2. SELECT
  3. 1 AS n
  4. ),
  5. table_1 AS (
  6. SELECT
  7. n
  8. FROM
  9. table_0
  10. UNION
  11. ALL
  12. SELECT
  13. n + 1
  14. FROM
  15. table_1
  16. WHERE
  17. n < 4
  18. )
  19. SELECT
  20. n
  21. FROM
  22. table_1 AS table_2

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.