search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Outline
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Referencing column and referenced column are incompatible in MySQL

schedule Aug 12, 2023
Last updated
local_offer
MySQL
Tags
tocTable of Contents
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

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.

Example

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 pupil table:

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 pupils is 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.

Now specifying bought_by as INT UNSIGNED:

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.

robocat
Published by Arthur Yanagisawa
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
20
thumb_down
6
chat_bubble_outline
1
settings
Enjoy our search
Hit / to insta-search docs and recipes!