by Bob Horton
Sr. Data Scientist at Microsoft
Common table expressions (CTEs, or “WITH clauses”) are a syntactic feature in SQL that makes it easier to write and use subqueries. They act as views or temporary tables that are only available during the lifetime of a single query. A more sophisticated feature is the “recursive CTE”, which is a common table expression that can call itself, providing a convenient syntax for recursive queries. This is very useful, for example, in following paths of links from record to record, as in graph traversal.
This capability is supported in Postgres, and Microsoft SQL Server (Oracle has similar capabilities with a different syntax), but not in MySql. Perhaps surprisingly, it is supported in SQLite, and since SQLite is the default backend for sqldf
, this gives R users a convenient way to experiment with recursive CTEs.
Factorials
This is the example from the Wikipedia article on hierarchical and recursive queries in SQL; you just pass it to sqldf
and it works.
library('sqldf')
sqldf("WITH RECURSIVE temp (n, fact) AS
(SELECT 0, 1 -- Initial Subquery
UNION ALL
SELECT n+1, (n+1)*fact FROM temp -- Recursive Subquery
WHERE n < 9)
SELECT * FROM temp;")
## n fact
## 1 0 1
## 2 1 1
## 3 2 2
## 4 3 6
## 5 4 24
## 6 5 120
## 7 6 720
## 8 7 5040
## 9 8 40320
## 10 9 362880
Other databases may use slightly different syntax (for example, if you want to run this query in Microsoft SQL Server, you …read more
Source:: http://revolutionanalytics.com