Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store tree structure in sql?

Here is my schema using sqlite, I am not sure if this is a good way to create tree structure in sql as I have to traverse many time to obtain the entire tree, as oppose to extracting the entire tree base on top comment and construct the tree in python. Can someone give me some suggestions.

BEGIN;
CREATE TABLE "tree_comment" 
    ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, 
     "text" text NOT NULL, 
     "parent_id" integer NULL REFERENCES "tree_comment" ("id"));
CREATE INDEX "tree_comment_6be37982" ON "tree_comment" ("parent_id");

COMMIT;
like image 708
Kevin Avatar asked Jun 11 '26 06:06

Kevin


1 Answers

Your example is the correct way to represent hierarchical data in a relational database. You should use Recursive Common Table Expressions (R CTE) to query the table.

In the past, you would have had to have used Nested Set or Materialized Path, but R CTE was purpose-built to fix their flaws, so use it.

SQLite supports Recursive CTE, and it's part of the SQL:1999 standard.

Here is an example query:

https://database-patterns.blogspot.com/2014/02/trees-paths-recursive-cte-postgresql.html

like image 173
Neil McGuigan Avatar answered Jun 13 '26 01:06

Neil McGuigan