Is the parent_id a self reference and null?
Moving on to Bill Karwin's book SQL Antipatterns, Chapter 3, Naive Trees (Adjacency Table, Parent-Child Relationship), there is an example of a comment table.
CREATE TABLE Comments (
comment_id SERIAL PRIMARY KEY,
parent_id BIGINT UNSIGNED,
comment TEXT NOT NULL,
FOREIGN KEY (parent_id) REFERENCES Comments(comment_id)
);
Sample data
| comment_id | parent_id | comments
|------------| ----------|-------------------------------------
|1 | NULL |What’s the cause of this bug?
|2 | 1 |I think it a null pointer
|3 | 2 |No, I checked for that
|4 | 1 |We need to check for invalid input
|5 | 4 |Yes,that a bug
|6 | 4 |Yes, please add a check
|7 | 6 |That fixed it
The table has comment_id, parent_id and a comment column. Parent_id is a foreign key referencing comment_id.
Auto add comment_id starting at 1.
Question.
If parent_id should be a foreign key that refers to comment_id, then why does the line with comment_id = 1 have parent_id null / 0 when the target is to have a foreign key to ensure referential integrity.
Note. I created the table as is and tried to enter data and got this error
# 1452 - Unable to add or update child row: foreign key constraint failed (`category`.`comments`, CONSTRAINT` comments_ibfk_1` FOREIGN KEY (` parent_id`). REFERENCES` comments` (`comment_id`))
source to share
Collect some insights from the comments above in this CW answer.
-
parent_id
NULL
in this table for the "root" node, which is at the top of the tree and therefore has no parent. -
Read https://dev.mysql.com/doc/refman/5.7/en/null-values.html : Keep in mind that the value
NULL
is different from values such as 0 for numeric types, or empty string for string types. See the " Problems withNULL
Values " section for more information . -
Also keep in mind that a keyword
NULL
is not the same as a literal string with a word'NULL'
. -
Read https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html : MySQL
SERIAL
has an alias forBIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE
.
source to share