SQLite Forum

Avoiding recursive CTE materialisation
Login
Re-phrase the query so as to store the results you want in the CTE and avoid redundant searches.

```
WITH parents(pid, cid)
  AS (
         SELECT parentId,
                id
           FROM export
          WHERE export.id = 60363923
      UNION ALL
         SELECT export.parentId,
                export.id
           FROM parents, export
          WHERE export.id = parents.pid
     )
SELECT cid,
       pid
  FROM parents
 WHERE cid > 60363923
 LIMIT 1
;
```
which has plan:
```
QUERY PLAN
|--CO-ROUTINE parents
|  |--SETUP
|  |  `--SEARCH export USING INTEGER PRIMARY KEY (rowid=?) (~1 row)
|  `--RECURSIVE STEP
|     |--SCAN parents (~1048576 rows)
|     `--SEARCH export USING INTEGER PRIMARY KEY (rowid=?) (~1 row)
`--SCAN parents (~983040 rows)
```