ltree Materialized Paths Replace Recursion
Store hierarchies as dot-separated label paths and answer descendant, pattern, and slice queries with ltree operators instead of recursive CTE walks.
Code
CREATE EXTENSION IF NOT EXISTS ltree;
-- 物化路径:整棵树的层级关系压进一个 ltree 列,免去递归 CTE 逐层展开
CREATE TABLE catalog_nodes (
id integer PRIMARY KEY,
path ltree NOT NULL
);
INSERT INTO catalog_nodes VALUES
(1, 'Top'),
(2, 'Top.Science'),
(3, 'Top.Science.Astronomy'),
(4, 'Top.Science.Biology'),
(5, 'Top.Collections');
-- <@:是某节点的后代(含相等);@> 是祖先方向
SELECT path FROM catalog_nodes
WHERE path <@ 'Top.Science'
ORDER BY path;
-- lquery 用 ~ 匹配:* 通配任意层(含零层),词尾 * 为前缀匹配
SELECT path FROM catalog_nodes
WHERE path ~ 'Top.*.Bio*'
ORDER BY path;
-- subltree / subpath 按位置切片;负偏移从尾部数
SELECT subltree(path, 1, 3) AS slice, subpath(path, -1) AS leaf
FROM catalog_nodes
WHERE id = 3;
-- GIST 索引让 <@ 与 ~ 走索引而不是全表展开
CREATE INDEX idx_catalog_path ON catalog_nodes USING GIST (path);How the snippet works
The file runs SELECT / INSERT / CREATE statements, touching catalog_nodes.
Mechanically, the statements are built from: a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the catalog_nodes table.
Statements that carry the logic
SELECT subltree(path, 1, 3) AS slice, subpath(path, -1) AS leaf
FROM catalog_nodes
WHERE id = 3;
SELECT path FROM catalog_nodes
WHERE path <@ 'Top.Science'
ORDER BY path;
SELECT path FROM catalog_nodes
WHERE path ~ 'Top.*.Bio*'
ORDER BY path;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- The references are `catalog_nodes`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.