Recursive CTE Expression Evaluation

Evaluate stored expression trees bottom-up: recursion resolves operand leaves first, then operators consume their children results.

SqlData Integrity

Code

snippet
-- expression tree evaluation in a recursive CTE: leaves resolve first, operators follow.
-- Postgres allows the recursive reference exactly once per recursive term, so the join
-- fans each parent out to one row per resolved child and aggregates the operands back
CREATE TABLE expr_nodes (
    node_id  int PRIMARY KEY,
    kind     text NOT NULL,            -- 'num' or 'op'
    op       text,
    value    numeric,
    left_id  int REFERENCES expr_nodes(node_id),
    right_id int REFERENCES expr_nodes(node_id)
);

INSERT INTO expr_nodes VALUES
    (1, 'num', NULL, 4,  NULL, NULL),
    (2, 'num', NULL, 5,  NULL, NULL),
    (3, 'num', NULL, 3,  NULL, NULL),
    (4, 'num', NULL, 3,  NULL, NULL),
    (5, 'op',  '+',  NULL, 1, 2),
    (6, 'op',  '*',  NULL, 3, 4),
    (7, 'op',  '*',  NULL, 5, 6);       -- (4 + 5) * (3 * 3)

WITH RECURSIVE evaluated AS (
    -- base: numeric leaves need no children
    SELECT node_id, value AS result
    FROM expr_nodes
    WHERE kind = 'num'

    UNION ALL

    -- the working table only holds the previous round's rows, so an operator fires
    -- once both children landed in the same round; the sample tree keeps every
    -- operator level aligned for exactly that reason
    SELECT
        p.node_id,
        CASE p.op
            WHEN '+' THEN MAX(e.result) FILTER (WHERE e.node_id = p.left_id)
                   + MAX(e.result) FILTER (WHERE e.node_id = p.right_id)
            WHEN '-' THEN MAX(e.result) FILTER (WHERE e.node_id = p.left_id)
                   - MAX(e.result) FILTER (WHERE e.node_id = p.right_id)
            WHEN '*' THEN MAX(e.result) FILTER (WHERE e.node_id = p.left_id)
                   * MAX(e.result) FILTER (WHERE e.node_id = p.right_id)
            WHEN '/' THEN MAX(e.result) FILTER (WHERE e.node_id = p.left_id)
                   / MAX(e.result) FILTER (WHERE e.node_id = p.right_id)
        END
    FROM expr_nodes p
    JOIN evaluated e ON e.node_id IN (p.left_id, p.right_id)
    WHERE p.kind = 'op'
    GROUP BY p.node_id, p.op, p.left_id, p.right_id
    HAVING COUNT(*) = 2
)
SELECT node_id, result
FROM evaluated
ORDER BY node_id;                       -- root node 7 ends with result = 81

Inside the snippet

SELECT / INSERT / CREATE statements share the script, touching expr_nodes and evaluated.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause limiting a statement to the rows that qualify; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a UNION stitching together the result sets of separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard tying rows to the parent table.

Putting it to use

Run the statement against the expr_nodes table.

Core lines

INSERT INTO expr_nodes VALUES
    (1, 'num', NULL, 4,  NULL, NULL),
    (2, 'num', NULL, 5,  NULL, NULL),
    (3, 'num', NULL, 3,  NULL, NULL),
    (4, 'num', NULL, 3,  NULL, NULL),
    (5, 'op',  '+',  NULL, 1, 2),
    (6, 'op',  '*',  NULL, 3, 4),
    (7, 'op',  '*',  NULL, 5, 6);       -- (4 + 5) * (3 * 3)
CREATE TABLE expr_nodes (
    node_id  int PRIMARY KEY,
    kind     text NOT NULL,            -- 'num' or 'op'
    op       text,
    value    numeric,
    left_id  int REFERENCES expr_nodes(node_id),
    right_id int REFERENCES expr_nodes(node_id)
);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`expr_nodes`, `evaluated` — referenced directly, no join needed.