PostgreSQL Recursive CTEs for Hierarchical Data, with Prisma

PostgreSQL Recursive CTEs for Hierarchical Data, with Prisma

by | Dec 5, 2026 | Databases | 0 comments

store each node with a parent_id column (an adjacency list), index that column, and fetch any subtree in a single query with WITH RECURSIVE. A PostgreSQL recursive CTE (common table expression) for hierarchical data has two halves. The anchor, also called the base case, selects the starting rows. The recursive term joins the table back to the rows found so far.

Add a depth counter and a path array, guard against cycles, and call the query from Prisma with $queryRaw. Your application then receives a flat, ordered list that it can turn into a nested tree in a few lines.

This tutorial covers categories, org charts, nested comments and bills of materials. It also covers the parts most tutorials skip: walking up to ancestors, typing the results in TypeScript, and knowing when a different tree model would serve you better.

Why loops in application code hurt

Most teams meet this problem the same way. A category menu or a comment thread starts small, so the code fetches the root, then loops over its children, then queries each child’s children. Developers call that pattern N+1 queries: one query for the parent plus one more for every node below it. It works with 20 rows and collapses with 20,000, because every round trip to the database adds latency.

The usual workaround is a chain of self-joins, one per level. It fails as soon as the tree gets one level deeper than the number of joins you wrote. A recursive query removes both problems, since the database traverses the tree itself and keeps joining until no new rows appear, whatever the depth.

How a recursive CTE actually runs

A CTE (common table expression) is a named subquery declared with WITH that exists only while the statement runs. The recursive version works like a loop inside the database engine:

  1. PostgreSQL runs the anchor (the non-recursive term) once and puts its rows in a working table.
  2. It runs the recursive term, which joins the base table to the working table, and the new rows replace the working table.
  3. It repeats step 2 until an iteration returns zero rows.
  4. It returns everything gathered across all iterations as one result set.

Each iteration only sees the rows produced by the previous one, not the whole result. That detail explains most behaviour you will see later, including why a cycle in the data never ends on its own.

database tree diagram

Storing the tree: the adjacency list

The adjacency list model is the simplest way to store hierarchical data in a relational database. Every row holds a reference to its parent, and root rows hold NULL. Adding, moving or deleting a node touches a single row, which is why it remains the default choice.

CREATE TABLE categories (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name       text NOT NULL,
  parent_id  bigint REFERENCES categories (id) ON DELETE CASCADE,
  CHECK (parent_id <> id)
);

CREATE INDEX categories_parent_id_idx ON categories (parent_id);

INSERT INTO categories (name, parent_id) VALUES
  ('Electronics', NULL),   -- id 1
  ('Computers', 1),        -- id 2
  ('Laptops', 2),          -- id 3
  ('Gaming laptops', 3),   -- id 4
  ('Phones', 1),           -- id 5
  ('Accessories', 5);      -- id 6

Two lines in that schema matter more than they look. The CHECK constraint stops a node from being its own parent, the most obvious loop. The index on parent_id is essential, because PostgreSQL indexes the primary key automatically but never the column that references it. Without that index, every iteration of the recursive term scans the whole table. There’s a good explainer over at martinheinz.dev.

The same structure covers an org chart (employees with a manager_id column), nested comments (comments with reply_to_id) or a folder tree. Only the names change.

Anatomy of a recursive query in PostgreSQL

The syntax has four parts: the WITH RECURSIVE header, the anchor, the UNION ALL keyword and the recursive term. The smallest possible example generates numbers, which makes the mechanism easy to see:

WITH RECURSIVE nums (n) AS (
  SELECT 1                          -- anchor: runs once
  UNION ALL
  SELECT n + 1 FROM nums WHERE n < 5  -- recursive term: runs until empty
)
SELECT n FROM nums;

The WHERE n < 5 condition is the stopping rule. In a tree query, you rarely write one, because the data stops the recursion for you: leaf nodes have no children, so the join returns nothing.

UNION ALL keeps every row, while UNION discards rows that duplicate a row already found. UNION can stop some loops, but only when the repeated rows are identical in every column. As soon as you add a depth counter, each repeated row differs, so UNION no longer protects you. We recommend UNION ALL with an explicit cycle guard instead (see the cycles section below). Related reading: Recursive Queries, Lateral Joins, Pagination, JSONB Arrays.

PostgreSQL also restricts what the recursive term may contain. It can reference the CTE only once, and the PostgreSQL documentation forbids aggregate functions in it. Any totals per subtree therefore happen after the recursion, in the outer query.

Fetching a full subtree with depth and path

This is the query most applications need: retrieve everything under one node, with its depth and the path from the starting point.

WITH RECURSIVE subtree AS (
  SELECT id, name, parent_id,
         0 AS depth,
         ARRAY[id] AS path
  FROM categories
  WHERE id = 1                      -- start node

  UNION ALL

  SELECT c.id, c.name, c.parent_id,
         s.depth + 1,
         s.path || c.id
  FROM categories c
  JOIN subtree s ON c.parent_id = s.id
)
SELECT id, name, parent_id, depth, path
FROM subtree
ORDER BY path;

The anchor picks the start node. To fetch the whole forest, replace WHERE id = 1 with WHERE parent_id IS NULL, which selects every root. The recursive term joins each category to its parent found in the previous round and adds 1 to the depth.

The path array does two jobs. Sorting by path places each child right under its parent, which is the order a nested menu needs. Sorting by depth instead groups all rows of the same level together, which breaks the visual tree. The path also lets you detect loops, as we will see.

A readable breadcrumb such as Electronics > Computers > Laptops needs a text column too. Write name::text AS label in the anchor and s.label || ' > ' || c.name in the recursive term. The cast matters. Without it, PostgreSQL may reject the query because the column type in the non-recursive term differs from the type of the whole result.

Inheriting values down the tree

The path array is one example of a value carried from parent to child, and you can carry anything the same way. A common case is permissions or settings that children inherit, such as an access list stored as an array on each folder:

  -- anchor
  SELECT id, parent_id, permitted AS effective FROM folders WHERE id = 0
  UNION ALL
  -- recursive term
  SELECT f.id, f.parent_id, s.effective || f.permitted
  FROM folders f JOIN tree s ON f.parent_id = s.id

Each row then holds its own values plus everything inherited above it. The reverse, collecting values from children up to a parent, needs a different shape, covered next.

Walking up: ancestors and breadcrumbs

Ancestor queries are the mirror image. You start from a leaf and follow parent_id upward, so the join condition flips:

WITH RECURSIVE ancestors AS (
  SELECT id, name, parent_id, 0 AS height
  FROM categories
  WHERE id = 4                      -- 'Gaming laptops'

  UNION ALL

  SELECT c.id, c.name, c.parent_id, a.height + 1
  FROM categories c
  JOIN ancestors a ON c.id = a.parent_id
)
SELECT name FROM ancestors ORDER BY height DESC;

The result reads from the root down to the leaf, which is exactly a breadcrumb trail. Note the direction: c.parent_id = s.id walks down, while c.id = a.parent_id walks up. Swapping these two by mistake is one of the most frequent causes of “my query returns one row”.

Totals per subtree

Because aggregates can’t run inside the recursive term, subtree totals follow a two-step pattern. First list every pair of (ancestor, descendant), then group in the outer query:

WITH RECURSIVE pairs AS (
  SELECT id AS root_id, id AS node_id FROM categories
  UNION ALL
  SELECT p.root_id, c.id
  FROM categories c
  JOIN pairs p ON c.parent_id = p.node_id
)
SELECT p.root_id, count(pr.id) AS products_in_subtree
FROM pairs p
LEFT JOIN products pr ON pr.category_id = p.node_id
GROUP BY p.root_id;

This gives the product count for each category, including everything in its subcategories. On a large tree, run it for one root at a time, or store the result if the tree rarely changes.

Real-world shapes: org charts, bills of materials, graphs

An org chart is the classic employee hierarchy, and the query only changes names. The anchor selects the person you start from (or WHERE manager_id IS NULL for the top), and the recursive term joins employees e ON e.manager_id = s.id. Adding depth gives the reporting level, This returns all subordinates of the starting employee, at any depth. “Everyone up to two levels below Alice” is simply WHERE depth <= 2 in the recursive term.

A BOM (bill of materials) adds one twist: each link carries a quantity, and quantities multiply down the tree. For example, if a bike needs 2 wheels and each wheel needs 36 spokes, the bike needs 72 spokes.

WITH RECURSIVE parts AS (
  SELECT component_id, quantity
  FROM bom WHERE assembly_id = 100
  UNION ALL
  SELECT b.component_id, p.quantity * b.quantity
  FROM bom b JOIN parts p ON b.assembly_id = p.component_id
)
SELECT component_id, sum(quantity) AS total_needed
FROM parts GROUP BY component_id;

A graph is a more general data structure where a node can have several parents, stored in an edges (src, dest) table. Recursion still walks it, but the shortcut that worked for trees no longer holds. A node reachable by two routes appears twice, and any loop in the edges runs forever. Graphs are where cycle handling stops being optional.

Cycles and infinite recursion

A tree should never loop, yet real data does. An admin moves a category under its own grandchild, an import writes the wrong parent_id, and the next request spins until it times out. In PostgreSQL, a recursive query has no built-in iteration limit, so a cycle keeps running until it hits statement_timeout or exhausts resources.

The portable guard uses the path array. Stop when the next node is already in the path:

  SELECT c.id, c.name, c.parent_id, s.depth + 1, s.path || c.id
  FROM categories c
  JOIN subtree s ON c.parent_id = s.id
  WHERE NOT c.id = ANY (s.path)
    AND s.depth < 50              -- optional safety cap

Since PostgreSQL 14, the SQL-standard CYCLE and SEARCH clauses do this for you. Write them right after the closing parenthesis of the CTE:

WITH RECURSIVE subtree AS (
  SELECT id, name, parent_id FROM categories WHERE id = 1
  UNION ALL
  SELECT c.id, c.name, c.parent_id
  FROM categories c JOIN subtree s ON c.parent_id = s.id
)
SEARCH DEPTH FIRST BY id SET tree_order
CYCLE id SET is_cycle USING cycle_path
SELECT * FROM subtree WHERE NOT is_cycle ORDER BY tree_order;

CYCLE adds a boolean column that turns true on the row that closes a loop, and it stops following that branch. SEARCH DEPTH FIRST produces an ordering column equivalent to the path sort above, while BREADTH FIRST orders level by level.

To find existing loops before they hurt you, run the path-guarded query from every root and compare its row count with the table size. Rows that never appear under any root belong to a cycle, or to a branch cut off by a deleted parent.

One curiosity from the documentation helps when debugging. An outer LIMIT can stop an endless recursive query, because PostgreSQL only computes as many rows as the parent query fetches. It’s handy for testing, but never a cycle guard in production code.

Running the query through Prisma

Prisma, the TypeScript ORM (object-relational mapper), models the adjacency list as a self-relation. It can load children with nested include, but only to a depth you write by hand. For a full subtree in one round trip, you send the recursive SQL (Structured Query Language) yourself.

model Category {
  id       BigInt     @id @default(autoincrement())
  name     String
  parentId BigInt?    @map("parent_id")
  parent   Category?  @relation("CategoryTree", fields: [parentId], references: [id], onDelete: Cascade)
  children Category[] @relation("CategoryTree")

  @@index([parentId])
  @@map("categories")
}

The @@map and @map attributes keep table and column names in lowercase snake case. Without them, Prisma creates "Category" and "parentId", which must be quoted in raw SQL because PostgreSQL folds unquoted names to lowercase. Forgetting the quotes produces a “relation does not exist” error that looks like a missing migration.

Then call $queryRaw with a tagged template. Prisma turns each ${} into a bound parameter, so user input never gets concatenated into the SQL:

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

type Row = { id: bigint; name: string; parent_id: bigint | null; depth: number };

async function getSubtree(rootId: bigint) {
  return prisma.$queryRaw<Row[]>`
    WITH RECURSIVE subtree AS (
      SELECT id, name, parent_id, 0 AS depth, ARRAY[id] AS path
      FROM categories WHERE id = ${rootId}
      UNION ALL
      SELECT c.id, c.name, c.parent_id, s.depth + 1, s.path || c.id
      FROM categories c
      JOIN subtree s ON c.parent_id = s.id
      WHERE NOT c.id = ANY (s.path)
    )
    SELECT id, name, parent_id, depth FROM subtree ORDER BY path`;
}

Avoid $queryRawUnsafe for this, since it accepts a plain string and opens the door to SQL injection. The generic type is a promise you make, not a check Prisma performs. If you want types generated from the SQL itself, Prisma’s TypedSQL feature reads .sql files and generates typed functions.

From flat rows to a nested tree

The database returns a flat list. Building the nested structure in memory takes one pass, because rows sorted by path always arrive after their parent:

type Node = { id: string; name: string; children: Node[] };

function buildTree(rows: Row[]): Node[] {
  const byId = new Map<string, Node>();
  const roots: Node[] = [];
  for (const r of rows) {
    const node = { id: r.id.toString(), name: r.name, children: [] };
    byId.set(node.id, node);
    const parent = r.parent_id != null ? byId.get(r.parent_id.toString()) : undefined;
    (parent ? parent.children : roots).push(node);
  }
  return roots;
}

The toString() calls aren’t cosmetic. PostgreSQL bigint columns come back as JavaScript BigInt, and JSON.stringify throws on them. Converting IDs once, here, keeps your API responses serializable.

Performance: what actually makes it fast

Recursive queries have a reputation for being slow, which is mostly a reputation for missing indexes. Each iteration is a join between the new rows and the base table on parent_id. With an index, that join is a series of quick lookups. Without one, it becomes a full table scan per level.

Part of the bad reputation comes from older PostgreSQL versions. Before PostgreSQL 12, every CTE acted as an optimization fence: PostgreSQL computed it in full before the outer query could filter it.

Since version 12, a non-recursive CTE that is side-effect free and referenced once gets inlined into the main query, and the MATERIALIZED and NOT MATERIALIZED keywords let you choose. A recursive CTE is still computed on its own, so put your filters in the anchor and the recursive term, not only in the final SELECT.

A few habits keep these queries predictable:

  • Start from the narrowest anchor possible: one node rather than every root, when the page only needs one subtree.
  • Cap the depth in the recursive term when the business rule allows it, such as comment threads limited to 10 levels.
  • Select only the columns you need inside the CTE, since every row carries them through each iteration.
  • Read the plan with EXPLAIN (ANALYZE, BUFFERS) and look for a sequential scan on the table inside the recursive part.
  • Cache trees that rarely change, like a product taxonomy, in a materialized view refreshed after edits.

Is this viable for millions of rows? The size of the table matters less than the size of the subtree you fetch. For example, fetching a few hundred descendants from a very large table stays a short series of index lookups. Pulling the entire table through recursion is a batch job, whatever the model.

Choosing a tree model: adjacency list or something else

The adjacency list with recursive CTEs suits most web applications. Still, three other models exist, and each wins in specific cases. The choice comes down to how often the tree changes and which question you ask most. PostgreSQL CTEs: WITH queries and materialization covers this in more depth.

Model Best when Avoid when
Adjacency list + recursive CTE The tree changes often: comments, org charts, user-managed categories You run the same deep subtree query thousands of times per second with no caching
Materialized path (ltree extension) Reads dominate and you filter by path patterns, such as “all paths under Electronics.Computers” Nodes move often, since every move rewrites the paths of the whole branch
Closure table (one row per ancestor-descendant pair) You need fast ancestor and descendant lookups in both directions, or a node can have several parents Storage is tight or the tree is very deep, because the pair table grows quickly
Nested sets (left and right numbers) The tree is almost static and you read whole subtrees in a single range scan You insert or move nodes regularly, since an insert can renumber a large part of the table

ltree ships with PostgreSQL as an extension, so you enable it with CREATE EXTENSION ltree;. It isn’t free, though. Something has to keep the path column in sync when a parent changes, usually a trigger or application code, and that synchronization becomes your responsibility.

For a typical client project, such as an e-commerce catalogue or a SaaS (software as a service) app with nested folders, we’d start with the adjacency list. Move to a closure table or ltree only when measurements show the recursive query is the bottleneck.

recursive ctes outside postgresql

Recursive CTEs outside PostgreSQL

If your project might change database, the core pattern carries over with small differences:

  • MySQL 8.0 and later use WITH RECURSIVE too, and stop at 1,000 iterations by default through the cte_max_recursion_depth setting.
  • SQL Server omits the RECURSIVE keyword and stops after 100 levels unless you add OPTION (MAXRECURSION n).
  • Oracle supports recursive WITH without the keyword, plus its older CONNECT BY PRIOR syntax, which many existing Oracle schemas still use.
  • SQLite supports WITH RECURSIVE, which makes it convenient for local tests of the same logic.

PostgreSQL, unlike MySQL and SQL Server, imposes no iteration limit. That is exactly why the cycle guard matters more on PostgreSQL than elsewhere.

Common mistakes and how to fix them

  • The query returns only the start row. The join condition points the wrong way. Use c.parent_id = s.id to go down and c.id = s.parent_id to go up.
  • The anchor’s rows repeat with a fixed level and nothing deeper appears. The second SELECT never references the CTE, so nothing is recursive. The recursive term must join back to the CTE name.
  • Error about a column type in the non-recursive term. A text or numeric column grows during recursion. Cast it in the anchor, for example name::text or 0::int AS depth.
  • The request hangs, then times out. The data contains a cycle. Add the path guard or the CYCLE clause, then find and fix the bad parent_id.
  • The tree renders in the wrong order. You sorted by depth. Sort by the path array or by the SEARCH ordering column.

Checklist for hierarchical data in PostgreSQL

  1. Store parent_id with a foreign key and a CHECK (parent_id <> id).
  2. Create an index on parent_id.
  3. Write the anchor first and test it alone.
  4. Join the recursive term in the right direction: down for subtrees, up for ancestors.
  5. Carry depth and a path array, cast to explicit types.
  6. Guard against cycles with the path check or CYCLE.
  7. Sort by path, never by depth alone.
  8. Do aggregates in the outer query.
  9. Call it from Prisma with $queryRaw, never $queryRawUnsafe.
  10. Convert BigInt IDs before returning JSON.
  11. Check the plan with EXPLAIN (ANALYZE, BUFFERS) on a realistic dataset.

Where to start

Pick the one tree in your application that currently loops in code, often the category menu or the comment thread. Add the parent_id index, replace the loop with the subtree query above, and compare response times before and after on production-sized data. Once that path works, ancestors, totals and cycle checks are variations of the same query, and the PostgreSQL documentation on common table expressions covers every clause in detail.

Building an app around nested data? Plan the tree model before the first migration: it’s far cheaper than changing it once the data is live.

FAQ

Can Prisma query a recursive relation without raw SQL?

Only to a fixed depth. You can nest include: { children: { include: { children: true } } } as many levels as you write, but Prisma can’t recursively follow an unknown depth. For whole subtrees, raw SQL with a recursive CTE is the practical route.

Is a recursive CTE better than a temporary table?

For tree traversal, usually yes. A temporary table needs a loop in application code or in a function to fill it level by level, which brings back the round trips. Temporary tables do help when you reuse an intermediate result several times and want to index it.

Should I use a recursive view?

PostgreSQL supports CREATE RECURSIVE VIEW, which wraps the query under a name. It’s convenient for reporting, but a view can’t take your start node as a parameter. For per-request subtrees, a function or a query with parameters gives you direct control over the anchor.

How do I move a node to another parent?

Update its parent_id, and its whole branch moves with it, since children point to it rather than to the root. Before saving, check that the new parent isn’t one of the node’s own descendants. The ancestor query above does that check in one statement.