Junior — Middle
What approach or data structure would you use to store and display a family tree in a relational database?
sobes.tech AI
Answer from AI
To store a family tree in a relational database, the "Adjacency List" structure is often used. Each person is stored in a table with a reference to their parent (for example, a parent_id field).
Example table structure:
| id | name | parent_id |
|---|---|---|
| 1 | Ivan | NULL |
| 2 | Maria | 1 |
| 3 | Alexey | 1 |
This approach is simple to implement and allows building a tree by recursively querying for descendants or ancestors.
For more complex queries, the following can be used:
- Nested Sets — storing left and right boundaries for quick subtree searches.
- Materialized Path — storing the path to a node as a string.
But for most tasks, "Adjacency List" is sufficient and well-supported by standard SQL queries.