Example 1
Generate the full path for each folder in a file system hierarchy
The anchor selects the root folder and seeds path with its name. Each recursive step finds folders whose parent_id matches a row already in paths and concatenates the parent's path, a slash, and the current folder's name. docs and images are both direct children of root, so their paths are root/docs and root/images. photos is a child of images, so its path becomes root/images/photos.
CREATE TABLE folders (id INT, name VARCHAR(50), parent_id INT);
INSERT INTO
folders
VALUES
(1, 'root', NULL),
(2, 'docs', 1),
(3, 'images', 1),
(4, 'photos', 3);WITH RECURSIVE
paths AS (
SELECT
id,
CAST(name AS CHAR(200)) AS path
FROM
folders
WHERE
parent_id IS NULL
UNION ALL
SELECT
f.id,
CONCAT (p.path, '/', f.name)
FROM
folders f
JOIN paths p ON f.parent_id = p.id
)
SELECT
path
FROM
paths
ORDER BY
path;| path |
|---|
| root |
| root/docs |
| root/images |
| root/images/photos |
CREATE TABLE folders (id INT, name VARCHAR(50), parent_id INT);
INSERT INTO
folders
VALUES
(1, 'root', NULL),
(2, 'docs', 1),
(3, 'images', 1),
(4, 'photos', 3);WITH
paths AS (
SELECT
id,
CAST(name AS VARCHAR(500)) AS path
FROM
folders
WHERE
parent_id IS NULL
UNION ALL
SELECT
f.id,
CAST(p.path + '/' + f.name AS VARCHAR(500))
FROM
folders f
JOIN paths p ON f.parent_id = p.id
)
SELECT
path
FROM
paths
ORDER BY
path;| path |
|---|
| root |
| root/docs |
| root/images |
| root/images/photos |
CREATE TABLE folders (id INT, name VARCHAR(50), parent_id INT);
INSERT INTO
folders
VALUES
(1, 'root', NULL),
(2, 'docs', 1),
(3, 'images', 1),
(4, 'photos', 3);WITH RECURSIVE
paths AS (
SELECT
id,
name AS path
FROM
folders
WHERE
parent_id IS NULL
UNION ALL
SELECT
f.id,
p.path || '/' || f.name
FROM
folders f
JOIN paths p ON f.parent_id = p.id
)
SELECT
path
FROM
paths
ORDER BY
path;| path |
|---|
| root |
| root/docs |
| root/images |
| root/images/photos |
SQL Server omits RECURSIVE and uses + for string concatenation. PostgreSQL and SQLite use ||. MySQL and MariaDB use CONCAT with an explicit cast on the anchor column. All engines produce identical paths.