Referencing column and referenced column are incompatible in MySQL
This error occurs in MySQL when the column you are attempting to add a foreign key constraint on does not have a matching data type with the column you are linking to in the parent table.
Consider the following table
pupils that contains pupil names:
CREATE TABLE pupils (id INT UNSIGNED AUTO_INCREMENT,name VARCHAR(30),PRIMARY KEY (id));INSERT INTO pupils (name) VALUES ('axel'), ('bob'), ('cathy');SELECT * FROM pupils;+----+-------+| id | name |+----+-------+| 1 | axel || 2 | bob || 3 | cathy |+----+-------+
To create a new table
product with a foreign key constraint on
bought_by that refers to
id from the
CREATE TABLE product (id INT UNSIGNED AUTO_INCREMENT,name VARCHAR(30),bought_by INT,PRIMARY KEY (id),FOREIGN KEY (bought_by) REFERENCES pupil (id));ERROR 3780 (HY000): Referencing column 'bought_by' and referenced column 'id' in foreign key constraint 'product_ibfk_1' are incompatible.
Even though both columns are type
INT, as the
id column in
UNSIGNED (i.e. cannot take negative values) and the
bought_by column is
SIGNED (i.e. can take negative values) these columns are considered incompatible. Updating one of the column types to match the other will allow you to create the table with the foreign key constraint.
CREATE TABLE product (id INT UNSIGNED AUTO_INCREMENT,name VARCHAR(30),bought_by INT UNSIGNED,PRIMARY KEY (id),FOREIGN KEY (bought_by) REFERENCES pupil (id));Query OK, 0 rows affected (0.01 sec)
We are able to create the table successfully with the foreign key.