WITH RECURSIVE cte(id, pid, NAME) AS (SELECT id, pid, name FROM tb a WHERE a.pid IS NOT NULL UNION ALL SELECT b.id, a.pid, b.NAME FROM tb a INNER JOIN cte b ON a.id = b.pid WHERE a.pid IS NOT NULL ) SELECT pid AS id, id AS SID, NAME FROM cte a UNION SELECT id, id, name FROM tb ORDER BY id, sid;