RECURSIVE
RECURSIVE is a keyword in SQL that indicates a query is going to use recursion to solve an operation. It's typically employed in a WITH clause to define a temporary table that references itself, enabling querying hierarchies or graphs of data within a single SQL command.
Example
Output
Explanation
The WITH RECURSIVE
clause creates a temporary named result set, numbers
. The SELECT 1
initializes the first row of the recursive query. The UNION ALL SELECT n+1 FROM numbers WHERE n < 10
clause recursively generates the next row by adding 1 to the previous row value returned by the numbers
result set. This continues until the value n
reaches 10. The SELECT * FROM numbers
statement then retrieves all of the values generated by the recursive query.
Example
Output
Explanation
In the example, a recursive common table expression (CTE) named factorial
is used. Starting with n=0
and f=1
as the initial condition, the SELECT
statement generates factorials for n
from 1 through 5. The recursion stops when n
is more than 5. The final SELECT * FROM factorial;
statement returns the results of the recursive calculation.
Example
Output
Explanation
The SQL statement with the WITH keyword is a stored procedure that Oracle calls a subquery factoring clause, or more generally, a “Common Table Expression” (CTE). The RECURSIVE
keyword is used to specify that the query is to be run recursively. The example demonstrates a simple recursion where numbers from 1 to 5 are generated. The recursion starts at 1 (SELECT 1 FROM dual
) and continues to add 1 to the previous number (SELECT number + 1 FROM number_list
) until it reaches 5 (WHERE number < 5
). The resulting set of numbers is then selected for output.
Example
Output
Explanation
In the example, a recursive common table expression cnt(x)
is created. This CTE starts with a value of 1 (VALUES(1)
) and adds 1 to x
until x<5
, generating a sequence of numbers from 1 to 5. This sequence is then selected and displayed.