I was having a doubt regarding foreign key constraints. So I made two simple table like these for testing purposes.
mysql> EXPLAIN parent;
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.01 sec)
mysql> EXPLAIN child;
+-----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| parent_id | int(11) | NO | MUL | NULL | |
+-----------+---------+------+-----+---------+----------------+
Now I did not specify the foreign key constraint at the time of creation of the table. I added it later as follows.
ALTER TABLE child
ADD CONSTRAINT parent_fk FOREIGN KEY(parent_id) REFERENCES parent(id);
I checked the engine used for the tables and its InnoDB. My Question are…
-
Why its not restricting me from deleting a record in parent on which there are several dependent child records? By default it should restrict me right?
-
If I create an index on the foreign key field before I add the foreign key constraint, its working as expected. Do I need to create index like that each time?
- Is it a bad practice to add any kind of constraints after the creation of a table?
MySQL requires indexes on fields when using
ALTER TABLEto add new foreign key constraints. The constraint is checked against the index in the parent table, so without an index no check is made.14.6.4.4. FOREIGN KEY Constraints
And, also:
To answer your specific questions:
1) It’s not restricting you because you have not created the required indexes. As stated in their documentation, the algo uses the indexes corresponding to the constraint.
2) See #1. Yes, unless the FK is in place before the rows are added to the parent table.
3) No, it isn’t bad practice. You just need to be explicit with your intent. For example, do you want to check for referential integrity after
ALTERing the table? Here is a potentially helpful question: Force InnoDB to recheck foreign keys on a table/tables?