MySQL
database errors
errno 150
table creation error
foreign key constraint

MySQL Can't create table errno 150

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

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

  1. 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.
  2. Character Set and Collation Mismatch:
    • Both foreign key and referenced columns must have the same character set and collation.
  3. Referenced Table or Column Does Not Exist:
    • The referenced table and column must exist and be defined with the appropriate constraints.
  4. Lack of Index on the Referenced Column:
    • The referenced column must be a primary key or have an index.
  5. 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.
  6. 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:

  1. Verify Data Types:
    • If user_id from orders and id from users have different collations or character sets, alter one to match the other.
    • Before creating the orders table, make sure the users table and id column are correctly defined.
    • The id in the users table 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.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design