O'Reilly logo

SQL Antipatterns by Bill Karwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Antipattern: Always Depend on One’s Parent

The naive solution commonly shown in books and articles is to add a column parent_id. This column references another comment in the same table, and you can create a foreign key constraint to enforce this relationship. The SQL to define this table is shown next, and the entity-relationship diagram is shown in Figure 4, Adjacency list entity-relationship diagram.

Trees/anti/adjacency-list.sql
 
CREATE​ ​TABLE​ Comments (
 
comment_id SERIAL ​PRIMARY​ ​KEY​,
 
parent_id ​BIGINT​ ​UNSIGNED​,
 
bug_id ​BIGINT​ ​UNSIGNED​ ​NOT​ NULL,
 
author ​BIGINT​ ​UNSIGNED​ ​NOT​ NULL,
 
comment_date ​DATETIME​ ​NOT​ NULL,
 
comment ​TEXT​ ​NOT​ NULL,
 
FOREIGN ​KEY​ (parent_id) REFERENCES Comments(comment_id),
 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required