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?