Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 42P19: Invalid Recursion Fix

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL error 42P19 (invalid_recursion) means your recursive query is not shaped the way PostgreSQL requires: the recursive term must reference the recursive CTE exactly once, it cannot contain aggregates, window functions, outer joins, subqueries that reference the CTE, or a reference to the CTE inside a subquery, and the query must not recurse through a data-modifying statement. The fix is to rewrite the recursive term so it is a plain SELECT that reads from the CTE once and from ordinary tables or values, then move any aggregation, DISTINCT, ORDER BY, or filtering outside the recursive part. This guide walks through diagnosing and correcting the error step by step.

What You'll Need

  • Access to a PostgreSQL database (version 12 or later is assumed; recursive CTE rules are stable across modern versions).
  • A SQL client such as psql, pgAdmin, DBeaver, or any tool that can run queries and show error messages.
  • The full text of the failing query, including the WITH RECURSIVE block.
  • Permission to read the tables involved so you can test rewrites safely.

Step-by-Step

  1. Reproduce the error and read the full message. Run the query in your SQL client. Error 42P19 usually appears with a hint such as "recursive reference to query \"name\" must not appear within a subquery" or "aggregate functions are not allowed in a recursive query's recursive term." Note the exact hint; it tells you which rule you broke.
  2. Identify the recursive CTE and its two parts. In WITH RECURSIVE t AS ( ... ), the body is joined by UNION or UNION ALL. The part before the UNION is the non-recursive term (the anchor); the part after is the recursive term. Error 42P19 always concerns the recursive term.
  3. Check that the recursive term references the CTE exactly once. A self-join like FROM t a JOIN t b ON ... inside the recursive term is invalid. Rewrite so the CTE appears once, and join the second copy through a separate non-recursive CTE or a plain table.
  4. Remove aggregates, window functions, DISTINCT, GROUP BY, HAVING, ORDER BY, and LIMIT from the recursive term. These are not allowed there. Move them into the outer query that selects from the CTE, or compute them in a later step. For example, if you need a running total, compute it in the outer SELECT rather than inside the recursion.
  5. Move any subquery that references the CTE out of the recursive term. A pattern such as WHERE id IN (SELECT id FROM t) inside the recursive part triggers 42P19. Replace it with a direct join to t (one reference only) or restructure the logic so the CTE is read at the top level of the recursive term.
  6. Remove outer joins from the recursive term. LEFT, RIGHT, and FULL joins are not permitted there. Use an inner join, or handle the optional side with a COALESCE in the outer query.
  7. Do not use the CTE inside a data-modifying statement in the recursive term. Recursive queries cannot contain INSERT, UPDATE, DELETE, or MERGE in the recursive part. If you need to write results, run the recursive SELECT first, then a separate INSERT ... SELECT or UPDATE ... FROM using the CTE in the outer statement.
  8. Ensure column types and counts match between the anchor and recursive terms. A mismatch often surfaces as a different error, but it can also mask 42P19. Cast columns explicitly (for example NULL::integer) so both branches align.
  9. Add a termination condition. Every recursive term needs a WHERE clause or join condition that eventually stops producing rows. Without it you get an infinite loop or a statement timeout, not 42P19, but it is part of a correct rewrite.
  10. Test the rewritten query on a small dataset. Add a LIMIT in the outer query while testing, then remove it. Confirm row counts and values match what you expect from the original logic.
  11. Run EXPLAIN on the final query. Check that the plan shows a Recursive Union node and that the recursive term reads the CTE once. This confirms the structure is valid and helps spot performance issues.

Common Mistakes

  • Putting DISTINCT or GROUP BY in the recursive term to "remove duplicates." Use UNION instead of UNION ALL if you need deduplication, or deduplicate in the outer query.
  • Referencing the CTE inside a correlated subquery in the recursive term. PostgreSQL rejects this even though the subquery looks harmless.
  • Using a LEFT JOIN to handle missing parents in a hierarchy. Rewrite with an inner join and filter or COALESCE in the outer SELECT.
  • Forgetting that the anchor term also cannot contain certain constructs in some contexts; keep both terms simple and move complex logic outside.
  • Assuming the error means the query is wrong logically. 42P19 is a structural rule, not a data problem; the same logic can often be expressed validly with a different shape.

Tips

  • Write the anchor and recursive terms separately in a scratch file, test each with a plain SELECT, then combine them.
  • Use UNION ALL by default for performance and add deduplication only if your data requires it.
  • Keep the recursive term as narrow as possible: select only the columns you need and push filters into the join condition.
  • If you need aggregation per level, compute it in the outer query or in a separate non-recursive CTE that reads from the recursive result.
  • Name your CTE clearly (for example org_tree) so error hints are easier to map back to your query.

Troubleshooting

If the error persists after rewriting, re-read the hint text: it names the specific construct PostgreSQL rejected. If you see "recursive reference must not appear within a subquery," search the recursive term for any SELECT that mentions the CTE name. If you see "aggregate functions are not allowed," look for SUM, COUNT, MAX, MIN, or ARRAY_AGG in the recursive part. If the query runs but returns wrong rows, check that your termination condition is correct and that the anchor term produces the expected starting rows. If you get a different error after fixing 42P19, such as a type mismatch, cast columns explicitly in both terms. When testing rewrites, run them inside a transaction and roll back if needed so you do not leave partial changes.

Frequently Asked Questions

What exactly does error 42P19 mean?

It is PostgreSQL's invalid_recursion error: the recursive term of a WITH RECURSIVE query violates one of the structural rules, such as referencing the CTE more than once or using an aggregate.

Can I use ORDER BY inside a recursive CTE?

Not in the recursive term. Apply ORDER BY in the outer query that selects from the CTE.

Why can't I use a LEFT JOIN in the recursive part?

PostgreSQL disallows outer joins in the recursive term. Use an inner join and handle missing rows with COALESCE or a filter in the outer query.

Does UNION ALL avoid the error?

UNION ALL is allowed and often preferred, but it does not by itself fix 42P19; the structural rules still apply to the recursive term.

Can a recursive CTE write data?

No. The recursive term cannot contain INSERT, UPDATE, DELETE, or MERGE. Run the recursive SELECT and use its result in a separate data-modifying statement.

Will upgrading PostgreSQL fix it?

No. The rule is part of SQL standard behavior and applies across supported versions; the query must be rewritten.