ERROR 3780 (HY000): Referencing column 'order_id' and referenced column 'id' in foreign key constraint 'order_items_ibfk_1' are incompatible.

Created at 10-Feb-2024 , By samar

ERROR 3780 (HY000): Referencing column 'order_id' and referenced column 'id' in foreign key constraint 'order_items_ibfk_1' are incompatible. Why i am getting above error while executing the below query.

create table order_items (
	id int auto_increment primary key, 
	order_id int, 
	product_id int, 
	quantity int, 
	FOREIGN KEY (order_id) REFERENCES orders(id), 
	FOREIGN KEY (product_id) references products(id)
);

Please provide me solution.

Here are table structure and other details related to tabels.

products table structure -

CREATE TABLE `products` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `price` float DEFAULT NULL,
  PRIMARY KEY (`id`)
)

orders table structure -

CREATE TABLE `orders` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `total_amount` decimal(10,2) NOT NULL,
  `status` enum('pending','processing') DEFAULT 'pending',
  PRIMARY KEY (`id`)
)
  • Columns must have the same data type and length while defining foreign key in MySQL

    The error message you're encountering, "Referencing column 'order_id' and referenced column 'id' in foreign key constraint 'order_items_ibfk_1' are incompatible," typically occurs when the data types of the columns in the foreign key constraint don't match exactly.

    You have unsigned primary key in products and orders table so while defining the foreign key you have to assign the unsigned to foreign key column (order_id, product_id).

    Table structure for order_items table should be look like below -

    create table order_items (
    	id int auto_increment primary key, 
    	order_id int unsigned , 
    	product_id int unsigned, 
    	quantity int, 
    	FOREIGN KEY (order_id) REFERENCES orders(id), 
    	FOREIGN KEY (product_id) references products(id)
    );
    

Back to code snippet queries related sql

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.