WHILE and FOR loops to implement patterns such as accumulation, graph traversal, and convergence algorithms.
Data flows provide loop constructs that are especially useful when a computation requires repeated passes over data, such as propagating values through a graph or refining an estimate until it stabilizes. The RETURN SELECT statement in a query data flow returns the final result set to the caller.
For details about data flow syntax and supported statements, see Data Flows.
Prerequisites
Before you begin, ensure that you have:- A running Ocient deployment with access to execute SQL statements.
- The
CREATE TABLEandINSERTprivileges on the target schema.
Accumulation with a WHILE Loop Example
This example computes a running factorial using a WHILE loop. The example demonstrates the basic loop pattern with variable manipulation and a safety limit.
1
Execute the Query Data Flow
Execute this query data flow to compute the factorial of 10. The This data flow returns a single row containing the factorial of 10 (3628800).
MAX ITERATIONS clause acts as a safety limit to prevent infinite loops if the loop never satisfies the termination condition.SQL
Graph Traversal with Iterative Expansion Example
This example finds all nodes reachable from a starting node in a directed graph by iteratively expanding the frontier of discovered nodes. Each iteration discovers new neighbors and adds them to the set of reached nodes.1
Create the Graph Table
Create a table representing a directed graph with edges between nodes.
SQL
2
Insert Sample Data
Insert edges representing a simple directed graph.
SQL
3
Execute the Traversal Data Flow
Execute this query data flow to find all nodes reachable from node 1.This data flow returns all nodes reachable from node 1: 1, 2, 3, 4, 5, 6, 7, and 8. Nodes 10, 11, and 12 are not reachable from node 1 and do not appear in the results.
SQL
Convergence Algorithm Example
This example implements an iterative averaging algorithm that converges to a stable value. Each iteration computes the average of the current value and a target, stopping when the change between iterations falls below a threshold.1
Execute the Convergence Data Flow
Execute this query data flow to iterate until the value converges.Output:
SQL
42.0009, 16 (converged value and iteration count)Iterator-Style FOR Loop Example
This example uses an iterator-styleFOR loop to iterate over query results and accumulate a sum.
1
Execute the Iterator Data Flow
Execute this query data flow to sum values from a query result.Output:
SQL
55The iterator-style FOR loop executes once per row returned by the SELECT statement. The source query must return exactly one column.
