MySQL Can't create table errno 150
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
MySQL's error messages can sometimes be cryptic, and one such example is the "Can't create table (errno: 150)" error. This often indicates an issue with foreign key constraints in a table creation query. Understanding and resolving this error involves grasping the intricacies of MySQL database constraints and relationships.
Understanding errno: 150
In the context of MySQL, "errno: 150" specifically refers to a foreign key violation. When you receive this error, MySQL is unable to create the table because there is something wrong with one or more foreign key definitions in the CREATE TABLE statement.
Common Causes of errno: 150
- Data Type Mismatch:
- If the data type of a foreign key column does not match the referenced primary key column, you'll encounter this error. Both columns must have compatible data types and attributes.
- Character Set and Collation Mismatch:
- Both foreign key and referenced columns must have the same character set and collation.
- Referenced Table or Column Does Not Exist:
- The referenced table and column must exist and be defined with the appropriate constraints.
- Lack of Index on the Referenced Column:
- The referenced column must be a primary key or have an index.
- Attempting to Reference a Non-Primary Key Column that is not Unique:
- The referenced column, which is not a primary key, must be defined as UNIQUE.
- Incompatible Engine Types:
- Both tables must use the InnoDB storage engine for foreign key constraints to work.
Diagnosing and Fixing errno: 150
To resolve this error, you’ll need to carefully check your table and column definitions in the CREATE TABLE statement. Here's a breakdown of key steps to help you diagnose and fix this issue:
- Verify Data Types:
- If
user_idfromordersandidfromusershave different collations or character sets, alter one to match the other. - Before creating the
orderstable, make sure theuserstable andidcolumn are correctly defined. - The
idin theuserstable should be either a primary key or have an index: - Confirm both tables use the InnoDB engine:
- You may need to modify table structures to ensure they meet all rules for foreign key constraints.

