MySQL Common Table Expressions: Recursive Queries for Hierarchical Data

Recursive CTEs: query category trees and page hierarchies in MySQL

WordPress stores hierarchies as parent pointers: a page has a post_parent, a category a parent in wp_term_taxonomy. Finding all descendants of an item needs one query per level in PHP, or a function like get_term_children() that loads the whole taxonomy into memory. A recursive common table expression walks the tree inside MySQL in a single query, at any depth.

Problem: A shop with 2,400 product categories in up to six levels needs, for a report, the total stock of all products in a top-level category and all its subcategories. The PHP code calls get_term_children() and then queries products per category, which takes 9 seconds.

Solution: Use WITH RECURSIVE to collect the category and all its descendants from wp_term_taxonomy, join the result with wp_term_relationships and the stock meta in the same query, and use a depth column and a path column for ordered tree output. Requires MySQL 8.0 or MariaDB 10.2.

All descendants of a category

WITH RECURSIVE tree AS (
    SELECT term_taxonomy_id, term_id, parent, 0 AS depth
    FROM wp_term_taxonomy
    WHERE taxonomy = 'product_cat' AND term_id = 42      -- the start category

    UNION ALL

    SELECT child.term_taxonomy_id, child.term_id, child.parent, tree.depth + 1
    FROM wp_term_taxonomy AS child
    JOIN tree ON child.parent = tree.term_id
    WHERE child.taxonomy = 'product_cat'
)
SELECT * FROM tree;

The first SELECT is the anchor: the start row. The second part refers to tree itself and adds the children of every row found so far; MySQL repeats it until no new rows appear. depth counts the levels.

Total stock in the whole subtree

WITH RECURSIVE tree AS (
    SELECT term_taxonomy_id, term_id
    FROM wp_term_taxonomy
    WHERE taxonomy = 'product_cat' AND term_id = 42
    UNION ALL
    SELECT c.term_taxonomy_id, c.term_id
    FROM wp_term_taxonomy AS c
    JOIN tree ON c.parent = tree.term_id
    WHERE c.taxonomy = 'product_cat'
)
SELECT COUNT(DISTINCT p.ID) AS products,
       SUM(CAST(pm.meta_value AS SIGNED)) AS stock
FROM tree
JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tree.term_taxonomy_id
JOIN wp_posts AS p ON p.ID = tr.object_id AND p.post_type = 'product' AND p.post_status = 'publish'
JOIN wp_postmeta AS pm ON pm.post_id = p.ID AND pm.meta_key = '_stock';

A product assigned to two subcategories would be counted twice in SUM(); for exact numbers, first select the distinct product IDs in a second CTE and sum over those. Each recursion step looks up children by parent, and wp_term_taxonomy has no index on that column (only on term_id, taxonomy and on taxonomy). With a few thousand terms that is still fast; for large taxonomies, an extra index on (taxonomy, parent) turns each step into an index lookup.

A page tree with breadcrumb paths

WITH RECURSIVE pages AS (
    SELECT ID, post_title, post_parent, CAST(post_title AS CHAR(1000)) AS path, 0 AS depth
    FROM wp_posts
    WHERE post_type = 'page' AND post_status = 'publish' AND post_parent = 0
    UNION ALL
    SELECT p.ID, p.post_title, p.post_parent, CONCAT(pages.path, ' › ', p.post_title), pages.depth + 1
    FROM wp_posts AS p
    JOIN pages ON p.post_parent = pages.ID
    WHERE p.post_type = 'page' AND p.post_status = 'publish'
)
SELECT ID, depth, path FROM pages ORDER BY path;

The CAST in the anchor sets the column type for all levels; without it, MySQL uses the type of the first row, and longer paths are cut off.

From PHP

global $wpdb;
$rows = $wpdb->get_results( $wpdb->prepare(
    "WITH RECURSIVE tree AS (
        SELECT term_id FROM {$wpdb->term_taxonomy} WHERE taxonomy = %s AND term_id = %d
        UNION ALL
        SELECT c.term_id FROM {$wpdb->term_taxonomy} c JOIN tree ON c.parent = tree.term_id WHERE c.taxonomy = %s
    ) SELECT term_id FROM tree",
    'product_cat',
    42,
    'product_cat'
) );
$ids = wp_list_pluck( $rows, 'term_id' );

MySQL stops a recursion after 1,000 levels (cte_max_recursion_depth), which protects against loops in broken data, where a term is its own ancestor. Non-recursive CTEs and window functions for reports: window functions and CTEs.

NOTE: For WordPress-level code, prefer the APIs when the numbers are small: get_term_children() and get_page_children() are cached and respect filters. The recursive CTE is for reports and large trees where loading everything into PHP is the bottleneck. MariaDB supports WITH RECURSIVE since 10.2.2, but not the cte_max_recursion_depth variable (it uses max_recursive_iterations).