Question

I was playing around with foreign key constraints and realized that I can add a constraint to a non-existent table. I can also insert records, no problem.

mysql> show tables;
Empty set (0.00 sec)

mysql> create table t(id int, FOREIGN KEY (id) REFERENCES x(id));
Query OK, 0 rows affected (0.00 sec)

mysql> insert into t values (1);
Query OK, 1 row affected (0.00 sec)

I am wondering if I don't quite understand foreign key constraints.

Was it helpful?

Solution

I think that the default storage is set to MyIsam, not InnoDb, and the table is created as MyIsam, not Innodb.

Foreign keys are only supported by Innodb tables.
For MyIsam tables, foreign key constraints are not supported, and while creating the table with create table command, a foreign key specification is parsed, but it is ignored.

Try to set innodb as a default engine using SET storage_engine=innodb;, or create a table using explicitely Innodb like this:

create table t(id int, FOREIGN KEY (id) REFERENCES x(id)) engine=innodb;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top