Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RECURSIVE in SQL

Tags:

sql

recursion

I'm learning SQL and had a hard time understanding the following recursive SQL statement.

WITH RECURSIVE t(n) AS (
    SELECT 1
    UNION ALL
    SELECT n+1 FROM t WHERE n < 100
)
SELECT sum(n) FROM t;

What is n and t from SELECT sum(n) FROM t;? As far as I could understand, n is a number of t is a set. Am I right?

Also how is recursion triggered in this statement?

like image 739
whileone Avatar asked Sep 17 '13 03:09

whileone


2 Answers

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:

  1. Evaluate the non-self-referring part (select 1).
  2. Then evaluate the self-referring part. (Initially this gives 2.)
  3. Then evaluation the self-referring part again. (3).
  4. 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.

like image 167
Gordon Linoff Avatar answered Oct 30 '22 21:10

Gordon Linoff


This is called a Common Table Expression, or CTE.

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.

At least, that's how it's supposed to work conceptually. What generally really happens is that the query engine builds the result iteratively, rather than recursively, if it can, but that's another story.

like image 41
Joel Coehoorn Avatar answered Oct 30 '22 20:10

Joel Coehoorn