Hierarchical Queries: Trees, Paths and Levels in SQL
Working with trees in SQL: displaying a hierarchy depth-first with paths and indentation, roots, branches and leaves, rolling totals up a tree, closure tables, materialised paths and ltree, flattening levels into columns, and Oracle's CONNECT BY.
kvi5hnuCode Sprout team member10 min readOn this page
Hierarchies are everywhere: product categories, organisation charts, folders, threaded comments, bills of materials. A relational table stores them in rows, and the typical questions follow the tree's shape: "show the whole tree, indented", "what's under this node?", "what's the path to this node?", "total the sales of each category including its subcategories".
Article 25 introduced recursive CTEs and used them to walk a hierarchy up and down. This article goes further: presenting trees, classifying nodes, aggregating over subtrees, and the alternative ways of storing a tree that make some of these queries much simpler. The examples use a small category tree:

CREATE TABLE categories (
cat_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (cat_id),
code TEXT -- matches products.category where a category has products
);
-- 1 Outdoor (root), 2 Camping and 5 Hiking under it,
-- 3 Tents and 4 Lighting under Camping, 6 Packs and 7 Clothing under Hiking, 8 Socks under Clothing
Each row points to its parent, and the root has a NULL parent. This is the adjacency list model, the most common and the most natural way to store a tree.
Displaying a tree
-- A category tree stored as an adjacency list: each row points to its parent
CREATE TABLE categories (
cat_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (cat_id),
code TEXT -- matches products.category for the categories that have products
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL, NULL),
(2, 'Camping', 1, NULL),
(3, 'Tents', 2, 'tents'),
(4, 'Lighting', 2, 'lighting'),
(5, 'Hiking', 1, NULL),
(6, 'Packs', 5, 'packs'),
(7, 'Clothing', 5, 'clothing'),
(8, 'Socks', 7, NULL);
-- The whole tree, depth-first, indented, with each category's full path
WITH RECURSIVE tree AS (
SELECT cat_id, name, 0 AS depth,
ARRAY[name] AS path
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.cat_id, c.name, t.depth + 1,
t.path || c.name
FROM categories c
JOIN tree t ON c.parent_id = t.cat_id
)
SELECT repeat(' ', depth) || name AS category,
depth,
array_to_string(path, ' > ') AS full_path
FROM tree
ORDER BY path;
category | depth | full_path
-------------------+-------+-------------------------------------
Outdoor | 0 | Outdoor
Camping | 1 | Outdoor > Camping
Lighting | 2 | Outdoor > Camping > Lighting
Tents | 2 | Outdoor > Camping > Tents
Hiking | 1 | Outdoor > Hiking
Clothing | 2 | Outdoor > Hiking > Clothing
Socks | 3 | Outdoor > Hiking > Clothing > Socks
Packs | 2 | Outdoor > Hiking > Packs
(8 rows)
The recursive CTE starts at the root and repeatedly adds the children of the rows found so far, as in article 25. Two extra columns make the output useful:
depthgoes up by one at each level.repeat(' ', depth)indents each name by its depth, giving the familiar outline view.pathis an array of the names from the root down to the node, built by appending each child's name to its parent's path.array_to_string(path, ' > ')turns it into a breadcrumb such asOutdoor > Hiking > Clothing > Socks.
The path also solves the hardest part, the order. A recursive CTE produces rows level by level: first the root, then all of depth 1, then all of depth 2. To show each node directly under its parent, sort by the path. Arrays compare element by element, so every node sorts right after its parent and before its parent's next sibling: this is a depth-first order, with siblings in alphabetical order.
Sorting by a path of names is fine for display. If names could contain the same text at the same level, or must sort in a custom order, build the path from a sort key or the IDs instead. The SQL standard has a SEARCH DEPTH FIRST BY ... SET ordercol clause for this, supported by PostgreSQL 14+.
Roots, branches and leaves
-- A category tree stored as an adjacency list: each row points to its parent
CREATE TABLE categories (
cat_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (cat_id),
code TEXT -- matches products.category for the categories that have products
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL, NULL),
(2, 'Camping', 1, NULL),
(3, 'Tents', 2, 'tents'),
(4, 'Lighting', 2, 'lighting'),
(5, 'Hiking', 1, NULL),
(6, 'Packs', 5, 'packs'),
(7, 'Clothing', 5, 'clothing'),
(8, 'Socks', 7, NULL);
\pset null '(null)'
-- Roots, branches and leaves, with each node's number of children
SELECT c.name,
CASE WHEN c.parent_id IS NULL THEN 'root'
WHEN NOT EXISTS (SELECT 1 FROM categories k WHERE k.parent_id = c.cat_id) THEN 'leaf'
ELSE 'branch' END AS kind,
(SELECT COUNT(*) FROM categories k WHERE k.parent_id = c.cat_id) AS children,
p.name AS parent
FROM categories c
LEFT JOIN categories p ON p.cat_id = c.parent_id
ORDER BY c.cat_id;
name | kind | children | parent
----------+--------+----------+----------
Outdoor | root | 2 | (null)
Camping | branch | 2 | Outdoor
Tents | leaf | 0 | Camping
Lighting | leaf | 0 | Camping
Hiking | branch | 2 | Outdoor
Packs | leaf | 0 | Hiking
Clothing | branch | 1 | Hiking
Socks | leaf | 0 | Clothing
(8 rows)
Every node of a tree is one of three kinds:
- a root has no parent:
parent_id IS NULL - a leaf has no children:
NOT EXISTSa row whoseparent_idis this node - a branch has both a parent and children
These tests need no recursion: the parent is one self-join away (article 14), and the children are one EXISTS or COUNT away. The LEFT JOIN keeps the root, whose parent is NULL.
Rolling totals up a tree
"Revenue per category, including all subcategories" is the tree version of a subtotal. Products are attached to the bottom of the tree, but every ancestor's total must include them:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- A category tree stored as an adjacency list: each row points to its parent
CREATE TABLE categories (
cat_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (cat_id),
code TEXT -- matches products.category for the categories that have products
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL, NULL),
(2, 'Camping', 1, NULL),
(3, 'Tents', 2, 'tents'),
(4, 'Lighting', 2, 'lighting'),
(5, 'Hiking', 1, NULL),
(6, 'Packs', 5, 'packs'),
(7, 'Clothing', 5, 'clothing'),
(8, 'Socks', 7, NULL);
-- Revenue rolled up the tree: every category's total includes all its descendants
WITH RECURSIVE pairs AS (
-- every category is its own descendant at distance 0 ...
SELECT cat_id AS ancestor, cat_id AS descendant FROM categories
UNION ALL
-- ... and the children of a descendant are descendants too
SELECT p.ancestor, c.cat_id
FROM pairs p
JOIN categories c ON c.parent_id = p.descendant
),
leaf_revenue AS (
SELECT cat.cat_id, SUM(s.amount) AS revenue
FROM sales s
JOIN categories cat ON cat.code = s.category
WHERE s.status <> 'cancelled'
GROUP BY cat.cat_id
)
SELECT a.name,
COALESCE(SUM(lr.revenue), 0) AS revenue_incl_subtree
FROM pairs p
JOIN categories a ON a.cat_id = p.ancestor
LEFT JOIN leaf_revenue lr ON lr.cat_id = p.descendant
GROUP BY a.cat_id, a.name
ORDER BY a.cat_id;
name | revenue_incl_subtree
----------+----------------------
Outdoor | 1026.44
Camping | 842.49
Tents | 738.99
Lighting | 103.50
Hiking | 183.95
Packs | 89.95
Clothing | 94.00
Socks | 0
(8 rows)
The trick is to generate every (ancestor, descendant) pair first:
- Every category is its own descendant, at distance 0. That makes a category's own sales count towards its own total.
- The children of any descendant are also descendants of the same ancestor. The recursion follows the tree down from every starting node.
With those pairs, the rollup is an ordinary join and GROUP BY ancestor. The revenue per leaf is computed once in leaf_revenue, by joining the sales view (article 20) to the categories through code. Outdoor's total, 1,026.44, is the sum of everything. Camping has 842.49, from tents and lighting. Socks has 0: no product is linked to it, because the Merino socks are attached to Clothing.
The LEFT JOIN and COALESCE keep categories with no sales. Because each descendant appears exactly once under each of its ancestors, nothing is counted twice, unlike approaches that join a parent to its children level by level.
Closure tables
The (ancestor, descendant) pairs are so useful that many systems store them, in a closure table:
-- A category tree stored as an adjacency list: each row points to its parent
CREATE TABLE categories (
cat_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (cat_id),
code TEXT -- matches products.category for the categories that have products
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL, NULL),
(2, 'Camping', 1, NULL),
(3, 'Tents', 2, 'tents'),
(4, 'Lighting', 2, 'lighting'),
(5, 'Hiking', 1, NULL),
(6, 'Packs', 5, 'packs'),
(7, 'Clothing', 5, 'clothing'),
(8, 'Socks', 7, NULL);
-- A closure table: one row for every ancestor/descendant pair, with the distance
CREATE TABLE category_paths (
ancestor INTEGER REFERENCES categories (cat_id),
descendant INTEGER REFERENCES categories (cat_id),
distance INTEGER NOT NULL,
PRIMARY KEY (ancestor, descendant)
);
INSERT INTO category_paths
WITH RECURSIVE pairs AS (
SELECT cat_id AS ancestor, cat_id AS descendant, 0 AS distance FROM categories
UNION ALL
SELECT p.ancestor, c.cat_id, p.distance + 1
FROM pairs p JOIN categories c ON c.parent_id = p.descendant
)
SELECT * FROM pairs;
SELECT COUNT(*) AS closure_rows FROM category_paths;
-- Everything under Hiking: no recursion needed at query time
SELECT c.name, cp.distance
FROM category_paths cp
JOIN categories c ON c.cat_id = cp.descendant
WHERE cp.ancestor = 5 AND cp.distance > 0
ORDER BY cp.distance, c.name;
-- Every ancestor of Socks, nearest first
SELECT c.name, cp.distance
FROM category_paths cp
JOIN categories c ON c.cat_id = cp.ancestor
WHERE cp.descendant = 8 AND cp.distance > 0
ORDER BY cp.distance;
closure_rows
--------------
21
(1 row)
name | distance
----------+----------
Clothing | 1
Packs | 1
Socks | 2
(3 rows)
name | distance
----------+----------
Clothing | 1
Hiking | 2
Outdoor | 3
(3 rows)
The table holds one row for every pair, including each node paired with itself, with the distance between them: 21 rows for 8 categories. It's filled once from the recursive CTE, then every hierarchical question is a simple, indexable join:
- All descendants of a node:
WHERE ancestor = :id AND distance > 0. - All ancestors of a node:
WHERE descendant = :id AND distance > 0, nearest first by distance. - Direct children:
distance = 1. Depth: the largest distance from the root.
The cost is maintenance. Adding a leaf inserts one row for each of its ancestors, plus itself. Moving a subtree deletes and re-inserts many rows. The closure table must be kept in step with the adjacency list, usually by a trigger (article 65) or by application code. For trees that are read far more than they change, such as product categories, this is a good trade.
Materialised paths and ltree
Another way to store a tree puts each node's full path in a column, such as 'outdoor.hiking.clothing'. Descendants are then found by prefix, path LIKE 'outdoor.hiking.%', with no recursion. PostgreSQL's ltree extension provides a dedicated type:
-- A category tree stored as an adjacency list: each row points to its parent
CREATE TABLE categories (
cat_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (cat_id),
code TEXT -- matches products.category for the categories that have products
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL, NULL),
(2, 'Camping', 1, NULL),
(3, 'Tents', 2, 'tents'),
(4, 'Lighting', 2, 'lighting'),
(5, 'Hiking', 1, NULL),
(6, 'Packs', 5, 'packs'),
(7, 'Clothing', 5, 'clothing'),
(8, 'Socks', 7, NULL);
-- Materialised paths with the ltree extension
CREATE EXTENSION IF NOT EXISTS ltree;
CREATE TABLE category_tree (
path ltree PRIMARY KEY,
name TEXT NOT NULL
);
INSERT INTO category_tree VALUES
('outdoor', 'Outdoor'),
('outdoor.camping', 'Camping'),
('outdoor.camping.tents', 'Tents'),
('outdoor.camping.lighting', 'Lighting'),
('outdoor.hiking', 'Hiking'),
('outdoor.hiking.packs', 'Packs'),
('outdoor.hiking.clothing', 'Clothing'),
('outdoor.hiking.clothing.socks', 'Socks');
-- <@ means "is a descendant of (or equal to)"; nlevel gives the depth
SELECT name, path, nlevel(path) AS depth
FROM category_tree
WHERE path <@ 'outdoor.hiking'
ORDER BY path;
-- @> means "is an ancestor of (or equal to)"; subpath extracts part of a path
SELECT name, subpath(path, 0, 1) AS root
FROM category_tree
WHERE path @> 'outdoor.hiking.clothing.socks'
ORDER BY nlevel(path);
name | path | depth
----------+-------------------------------+-------
Hiking | outdoor.hiking | 2
Clothing | outdoor.hiking.clothing | 3
Socks | outdoor.hiking.clothing.socks | 4
Packs | outdoor.hiking.packs | 3
(4 rows)
name | root
----------+---------
Outdoor | outdoor
Hiking | outdoor
Clothing | outdoor
Socks | outdoor
(4 rows)
<@means "is a descendant of, or equal to":path <@ 'outdoor.hiking'finds Hiking and everything under it.@>means "is an ancestor of, or equal to", finding every node on the path to Socks.nlevel(path)is the depth, andsubpathextracts parts of a path. Sorting by anltreevalue gives depth-first order.- A GiST index on the
pathcolumn makes<@and@>fast on large trees.
Path labels may contain only letters, digits, underscores and hyphens (PostgreSQL 16+). Moving a subtree means rewriting the paths of every node in it, which ltree's functions make a single UPDATE. SQL Server has a similar built-in type, hierarchyid, with methods such as IsDescendantOf and GetLevel.
A fourth model, nested sets, stores a left and right number for each node so that a subtree is a numeric range. It makes reading subtrees fast but makes every insert renumber much of the tree, so it has fallen out of favour now that recursive CTEs are available everywhere.
| Model | Store | Subtree query | Changes |
|---|---|---|---|
| adjacency list | parent_id | recursive CTE | easy: update one row |
| closure table | all ancestor/descendant pairs | simple join | many rows per change |
materialised path / ltree | path per node | prefix match or <@ | rewrite paths of the moved subtree |
| nested sets | left and right numbers | range comparison | renumber much of the tree |
The adjacency list is the right default: it's simple, each change touches one row, and the database can enforce it with a foreign key. Add a closure table or a path column when subtree queries are frequent and the tree is large.
Flattening levels into columns
Reports and spreadsheets sometimes want a tree flattened, one row per leaf with a column per level:
-- A category tree stored as an adjacency list: each row points to its parent
CREATE TABLE categories (
cat_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (cat_id),
code TEXT -- matches products.category for the categories that have products
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL, NULL),
(2, 'Camping', 1, NULL),
(3, 'Tents', 2, 'tents'),
(4, 'Lighting', 2, 'lighting'),
(5, 'Hiking', 1, NULL),
(6, 'Packs', 5, 'packs'),
(7, 'Clothing', 5, 'clothing'),
(8, 'Socks', 7, NULL);
\pset null '(null)'
-- Flattening the tree: each leaf with its levels as columns
WITH RECURSIVE tree AS (
SELECT cat_id, ARRAY[name] AS path
FROM categories WHERE parent_id IS NULL
UNION ALL
SELECT c.cat_id, t.path || c.name
FROM categories c JOIN tree t ON c.parent_id = t.cat_id
)
SELECT path[1] AS level_1, path[2] AS level_2, path[3] AS level_3, path[4] AS level_4
FROM tree t
WHERE NOT EXISTS (SELECT 1 FROM categories k WHERE k.parent_id = t.cat_id)
ORDER BY path;
level_1 | level_2 | level_3 | level_4
---------+---------+----------+---------
Outdoor | Camping | Lighting | (null)
Outdoor | Camping | Tents | (null)
Outdoor | Hiking | Clothing | Socks
Outdoor | Hiking | Packs | (null)
(4 rows)
The path array from the recursive CTE already holds the levels in order, so path[1], path[2] and so on are the columns. Only the leaves are kept. Socks is the only leaf four levels deep, so the other rows have NULL in level_4. As with pivoting by position (article 44), the number of columns has to be fixed in the query, which suits trees with a known maximum depth.
CONNECT BY in Oracle
Oracle had hierarchical queries long before recursive CTEs, with its own syntax, still widely used:
SELECT LPAD(' ', 4 * (LEVEL - 1)) || name AS category,
LEVEL AS depth,
SYS_CONNECT_BY_PATH(name, ' > ') AS full_path,
CONNECT_BY_ISLEAF AS is_leaf
FROM categories
START WITH parent_id IS NULL
CONNECT BY PRIOR cat_id = parent_id
ORDER SIBLINGS BY name;
START WITHchooses the root rows, andCONNECT BY PRIOR cat_id = parent_idlinks each row to its children.PRIORmarks the parent's column.LEVELis the depth, starting at 1.SYS_CONNECT_BY_PATHbuilds the path,CONNECT_BY_ISLEAFflags leaves, andCONNECT_BY_ROOTreturns a column of the root row.- The output is already depth-first, and
ORDER SIBLINGS BYsorts children within each parent without breaking the tree order. NOCYCLEwithCONNECT_BY_ISCYCLEdeals with cycles.
Oracle also supports recursive CTEs, which are portable. Snowflake and Db2 (in its Oracle-compatibility mode) also accept CONNECT BY. Elsewhere, use recursive CTEs.
What's current
- PostgreSQL 14 added the standard
SEARCH DEPTH FIRSTandSEARCH BREADTH FIRSTclauses for ordering recursive results, andCYCLEfor detecting cycles (article 25). - PostgreSQL 16 allowed hyphens in
ltreelabels. - Recursive CTEs are available in every major database, including MySQL 8, SQLite and SQL Server, so
CONNECT BYis needed only for existing Oracle code.
Common questions
How do I display a tree in the right order?
Build a path from the root in the recursive CTE, as an array or a padded string, and ORDER BY it. In Oracle, CONNECT BY with ORDER SIBLINGS BY does this directly.
How do I find all descendants of a node?
Start a recursive CTE at that node and follow parent_id down. With a closure table, select rows with that ancestor. With ltree, use <@.
How do I total values over each subtree? Generate (ancestor, descendant) pairs, including each node with itself, join the values to the descendants, and group by the ancestor.
Which tree model should I use?
An adjacency list (parent_id) by default. Add a closure table or materialised paths when the tree is large and subtree queries are frequent.
How do I find leaf nodes?
WHERE NOT EXISTS (SELECT 1 FROM t AS child WHERE child.parent_id = t.id).
Summary
- An adjacency list stores each node's parent. Recursive CTEs walk it.
- Carry a depth and a path in the recursive CTE. Indent by depth, and sort by path for depth-first order.
- Roots have no parent, leaves have no children, and branches have both.
- Subtree totals need all (ancestor, descendant) pairs, including each node with itself, then a
GROUP BYon the ancestor. - A closure table stores those pairs, turning hierarchy queries into joins at the cost of maintenance.
- Materialised paths and
ltreefind subtrees by prefix.hierarchyiddoes the same in SQL Server. - A path array flattens a tree into level columns.
- Oracle's
CONNECT BYwithLEVEL,SYS_CONNECT_BY_PATHandORDER SIBLINGS BYis the older, Oracle-specific syntax.
Practice questions
Write a query that lists the names of all leaf categories.
Answer
SELECT name
FROM categories c
WHERE NOT EXISTS (SELECT 1 FROM categories k WHERE k.parent_id = c.cat_id)
ORDER BY name;
Lighting, Packs, Socks and Tents.
Write a recursive query that returns the names of all categories under Camping (ID 2), not including Camping itself.
Answer
WITH RECURSIVE sub AS (
SELECT cat_id, name FROM categories WHERE parent_id = 2
UNION ALL
SELECT c.cat_id, c.name FROM categories c JOIN sub s ON c.parent_id = s.cat_id
)
SELECT name FROM sub ORDER BY name;
Lighting and Tents. Starting from the children of Camping, rather than from Camping, leaves it out.
How many rows does the closure table get if a new category, Stoves, is added under Camping?
Answer
3 more, for a total of 24: Stoves paired with itself (distance 0), with Camping (distance 1) and with Outdoor (distance 2). A new leaf adds one row for itself and one for each of its ancestors.
Why does the tree query sort by path instead of by depth?
Answer
Sorting by depth lists all nodes of one level before the next, so children end up far from their parents. Sorting by the path array puts each node right after its parent and before the parent's next sibling, which is the depth-first order of an outline.
Previous: Advanced Searching in SQL: Top-N, Extremes, Skipping Rows and Previous Values

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.