CTE CYCLE Composite Keys And Custom Markers
Detect loops on multi-column graph keys with the PostgreSQL CYCLE clause, writing custom string flags and tracking hop counts via the path array.
Code
CREATE TEMP TABLE tenant_links (
tenant text NOT NULL,
node_id integer NOT NULL,
next_node integer,
PRIMARY KEY (tenant, node_id)
);
INSERT INTO tenant_links VALUES
('acme', 1, 2),
('acme', 2, 3),
('acme', 3, 1), -- loop back to (acme, 1)
('beta', 1, 2), -- independent node 1 in another tenant
('beta', 2, NULL);
WITH RECURSIVE graph AS (
SELECT tenant, node_id, next_node, 1 AS depth
FROM tenant_links
WHERE node_id = 1
UNION ALL
SELECT l.tenant, l.node_id, l.next_node, g.depth + 1
FROM tenant_links l
JOIN graph g
ON l.tenant = g.tenant
AND l.node_id = g.next_node
) CYCLE tenant, node_id SET loop_state TO 'LOOP' DEFAULT 'OK' USING hop_trail
SELECT
tenant,
node_id,
depth,
loop_state,
cardinality(hop_trail) AS path_len,
hop_trail::text AS visited_path
FROM graph
ORDER BY tenant, depth, node_id;Runtime walkthrough — CTE CYCLE Composite Keys And Custom Markers
SELECT / INSERT / CREATE statements share the script, touching tenant_links and graph.
tenant_links bootstraps its own temporary session tables directly inline without prior setup and discards all temporary structures when disconnecting cleanly.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause constraining which rows the statement operates on; 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; DEFAULT values filling omitted columns.
Using it
The file sets up its own scratch surface: it builds the session-local tables it works with (tenant_links), so one full run against a throwaway database is enough.
Key statements
INSERT INTO tenant_links VALUES
('acme', 1, 2),
('acme', 2, 3),
('acme', 3, 1), -- loop back to (acme, 1)
('beta', 1, 2), -- independent node 1 in another tenant
('beta', 2, NULL);
CREATE TEMP TABLE tenant_links (
tenant text NOT NULL,
node_id integer NOT NULL,
next_node integer,
PRIMARY KEY (tenant, node_id)
);
Interactive Tools for This Topic
FAQ
- What objects does the SQL involve?
- `tenant_links`, `graph` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.