Wednesday, 5 February 2025

SQL With Recursive All, Union ALL


https://www.techonthenet.com/mysql/union_all.php

UNION ALL



The MySQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It returns all rows from the query and it does not remove duplicate rows between the various SELECT statements.

Each SELECT statement within the MySQL UNION ALL operator must have the same number of fields in the result sets with similar data types.


 https://stackoverflow.com/questions/18840998/recursive-in-sql

The syntax that you are using looks like Postgres. "Recursion" in SQL is not really recursion, it is iteration. Your statement is:


WITH RECURSIVE t(n) AS (

    SELECT 1

    UNION ALL

    SELECT n+1 FROM t WHERE n < 100

)

SELECT sum(n) FROM t;

The statement for t is evaluated as:


Evaluate the non-self-referring part (select  1).

Then evaluate the self-referring part. (Initially this gives 2.)

Then evaluation the self-referring part again. (3).

And so on while the condition is still valid (n < 100).

When this is done the t subquery is finished, and the final statement can be evaluated.



The RECURSIVE from the query doesn't mean anything: it's just another name like n or t. What makes things recursive is that the CTE named t references itself inside the expression. To produce the result of the expression, the query engine must therefore recursively build the result, where each evaluation triggers the next. It reaches this point: SELECT n+1 FROM t... and has to stop and evaluate t. To do that, it has to call itself again, and so on, until the condition (n < 100) no longer holds. The SELECT 1 provides a starting point, and the WHERE n < 100 makes it so that the query does not recur forever.

No comments:

Post a Comment