PostgreSQL 17.12Lab-verified · 2026-11-30

PostgreSQL 42P19: recursive reference to query must not appear within an outer join

The recursive term of WITH RECURSIVE uses the CTE in a place PostgreSQL does not allow.

PostgreSQL 17.12
42P19: recursive reference to query "tree" must not appear within an outer join

Jump to a cause

  1. 01LEFT JOIN to the recursive CTE (org tree)
  2. 02Aggregate (sum) inside the recursive term (BOM)
  3. 03Subquery on the CTE to stop a cycle

Lab-verifiedReproduced and fixed on PostgreSQL 17.12 · 2026-11-30 · container image postgres:17

42P19 (invalid_recursion) is raised while parsing a WITH RECURSIVE query. The recursive term may reference the CTE only once, as a plain table in a normal join, so PostgreSQL rejects it inside an outer join, an aggregate or a subquery. The message says which rule was broken.

In the lab the three cases were a LEFT JOIN in an org tree, sum() in a bill of materials, and NOT IN (SELECT ... FROM cte) used to stop a cycle. Each was fixed by moving that logic out of the recursive term.

01LEFT JOIN to the recursive CTE (org tree)

The recursive term was FROM dept d LEFT JOIN tree ON d.parent_id = tree.id. PostgreSQL stopped with must not appear within an outer join, pointing at tree.

With a plain JOIN the query walked the tree: HQ at level 1, Sales and IT at 2, Infra at 3.

Setup
Setuprun as lab_a
CREATE TABLE dept (id int PRIMARY KEY, parent_id int, name text);
INSERT INTO dept VALUES (1, NULL, 'HQ'), (2, 1, 'Sales'), (3, 1, 'IT'), (4, 3, 'Infra');
OUTPUT
CREATE TABLE
INSERT 0 4
Reproducerun as lab_a
WITH RECURSIVE tree AS (
  SELECT id, name, 1 AS lvl FROM dept WHERE parent_id IS NULL
  UNION ALL
  SELECT d.id, d.name, tree.lvl + 1
  FROM dept d LEFT JOIN tree ON d.parent_id = tree.id
)
SELECT * FROM tree;
✕ ERROR
ERROR:  42P19: recursive reference to query "tree" must not appear within an outer join
LINE 5:   FROM dept d LEFT JOIN tree ON d.parent_id = tree.id
                                ^
Checkrun as lab_a
SELECT id, parent_id, name FROM dept ORDER BY id;
OUTPUT
 id | parent_id | name
----+-----------+-------
  1 |           | HQ
  2 |         1 | Sales
  3 |         1 | IT
  4 |         3 | Infra
(4 rows)

Each step only needs rows whose parent is already in the CTE, so an inner JOIN gives the same tree.

After the fixrun as lab_a
WITH RECURSIVE tree AS (
  SELECT id, name, 1 AS lvl FROM dept WHERE parent_id IS NULL
  UNION ALL
  SELECT d.id, d.name, tree.lvl + 1
  FROM dept d JOIN tree ON d.parent_id = tree.id
)
SELECT * FROM tree ORDER BY lvl, id;
✓ SUCCESS
 id | name  | lvl
----+-------+-----
  1 | HQ    |   1
  2 | Sales |   2
  3 | IT    |   2
  4 | Infra |   3
(4 rows)

02Aggregate (sum) inside the recursive term (BOM)

To total parts for a bike, sum(p.qty * b.qty) with GROUP BY was put in the recursive term. It failed with aggregate functions are not allowed in a recursive query's recursive term.

Computing p.qty * b.qty per row in the recursion and running sum(qty) ... GROUP BY child in the outer query returned spoke 64, wheel 2, frame 1.

Setup
Setuprun as lab_a
CREATE TABLE bom (parent text, child text, qty int);
INSERT INTO bom VALUES ('bike', 'wheel', 2), ('wheel', 'spoke', 32), ('bike', 'frame', 1);
OUTPUT
CREATE TABLE
INSERT 0 3
Reproducerun as lab_a
WITH RECURSIVE parts AS (
  SELECT child, qty FROM bom WHERE parent = 'bike'
  UNION ALL
  SELECT b.child, sum(p.qty * b.qty)::int
  FROM bom b JOIN parts p ON b.parent = p.child
  GROUP BY b.child
)
SELECT * FROM parts;
✕ ERROR
ERROR:  42P19: aggregate functions are not allowed in a recursive query's recursive term
LINE 4:   SELECT b.child, sum(p.qty * b.qty)::int
                          ^
Checkrun as lab_a
SELECT parent, child, qty FROM bom ORDER BY parent, child;
OUTPUT
 parent | child | qty
--------+-------+-----
 bike   | frame |   1
 bike   | wheel |   2
 wheel  | spoke |  32
(3 rows)

Let the recursion produce rows, then aggregate in the outer SELECT.

After the fixrun as lab_a
WITH RECURSIVE parts AS (
  SELECT child, qty FROM bom WHERE parent = 'bike'
  UNION ALL
  SELECT b.child, p.qty * b.qty
  FROM bom b JOIN parts p ON b.parent = p.child
)
SELECT child, sum(qty) AS total_qty FROM parts GROUP BY child ORDER BY child;
✓ SUCCESS
 child | total_qty
-------+-----------
 frame |         1
 spoke |        64
 wheel |         2
(3 rows)

03Subquery on the CTE to stop a cycle

Routes A→B→C→A form a loop. Using WHERE r.dst NOT IN (SELECT node FROM reach) to stop it failed with must not appear within a subquery.

The CYCLE node SET is_cycle USING path clause (PostgreSQL 14+) ended the loop: the second A came back with is_cycle = t and path {(A),(B),(C),(A)}, and recursion stopped there.

Setup
Setuprun as lab_a
CREATE TABLE route (src text, dst text);
INSERT INTO route VALUES ('A', 'B'), ('B', 'C'), ('C', 'A');
OUTPUT
CREATE TABLE
INSERT 0 3
Reproducerun as lab_a
WITH RECURSIVE reach AS (
  SELECT 'A'::text AS node
  UNION ALL
  SELECT r.dst FROM route r JOIN reach ON r.src = reach.node
  WHERE r.dst NOT IN (SELECT node FROM reach)
)
SELECT * FROM reach;
✕ ERROR
ERROR:  42P19: recursive reference to query "reach" must not appear within a subquery
LINE 5:   WHERE r.dst NOT IN (SELECT node FROM reach)
                                               ^
Checkrun as lab_a
SELECT src, dst FROM route ORDER BY src;
OUTPUT
 src | dst
-----+-----
 A   | B
 B   | C
 C   | A
(3 rows)

Filter WHERE NOT is_cycle in the outer query if you do not want the repeated row.

After the fixrun as lab_a
WITH RECURSIVE reach AS (
  SELECT 'A'::text AS node
  UNION ALL
  SELECT r.dst FROM route r JOIN reach ON r.src = reach.node
) CYCLE node SET is_cycle USING path
SELECT node, is_cycle, path FROM reach;
✓ SUCCESS
 node | is_cycle |       path
------+----------+-------------------
 A    | f        | {(A)}
 B    | f        | {(A),(B)}
 C    | f        | {(A),(B),(C)}
 A    | t        | {(A),(B),(C),(A)}
(4 rows)

FAQ

Why can't I use LEFT JOIN in a recursive CTE in PostgreSQL?

The recursive reference cannot sit on the nullable side of an outer join. Use an inner JOIN in the recursive term; for a tree walk it returns the same rows.

How do I use SUM or COUNT with WITH RECURSIVE?

Not inside the recursive term. Return one row per step and aggregate in the outer query, e.g. SELECT child, sum(qty) FROM parts GROUP BY child.

How do I prevent infinite loops in a recursive CTE?

On PostgreSQL 14 or later add CYCLE col SET is_cycle USING path after the CTE. A subquery on the CTE itself raises 42P19.

Is 'column has type X in non-recursive term but type Y overall' also 42P19?

No, that is 42804 (datatype mismatch). Cast the column in the non-recursive term.

How we verify

Each scenario starts from fresh database users. A script runs the setup, confirms the exact error code, applies the fix and runs the statement again. The output shown is what the database printed, saved by the script.

lab_a and lab_b are ordinary roles created for the test, each owning a schema of the same name; postgres is the superuser. PostgreSQL 17.12