Written by 17:18 MySQL

MySQL Foreign Key – How to Relate Tables Without Freaking Out 

ow to Add a Foreign Key in MySQL

Have you ever felt like a puzzle piece that won’t fit, especially about MySQL foreign keys? 

Trust me, you’re not alone on this adventurous data journey. 

Imagine that you’re going to create your first MySQL database. It would be like your first trip to a dream place. Without hesitation, you add your first foreign key. But then, frustration knocks as you struggle with test data leaving you confused about those mysterious foreign key violations which seem to be a pain to handle. You’re about to wave the white flag and give up on those troublesome foreign keys. 

Take a deep breath and relax! This article is your virtual guide that helps you demystify foreign keys, pulverize those troublesome foreign key violations, and overcome the chicken-and-egg design dilemma. In addition, we’ll tackle each challenge step by step. No riddles or secret codes are required. It’s like navigating a treasure map. Sometimes, it can be challenging but oh-so-rewarding when you uncover the gems. 

So, stick around, newbie explorer! We’ll dive into the world of MySQL foreign keys and turn those frustrations into fist bumps of victory! 

Here is a heads-up on how we will deal with MySQL foreign keys: 

  • What is a MySQL Foreign Key?
  • How to Design MySQL Databases with Foreign Keys?
  • How to add a MySQL Foreign Key to a new table using CREATE TABLE
  • How to add a MySQL Foreign Key to an existing table using ALTER TABLE
  • Using Foreign Key Options
  • Avoiding Gotchas in MySQL Foreign Key

What is a MySQL Foreign Key? 

Imagine your database as a collection of books and MySQL foreign keys as bookmarks connecting different books. So, maintaining data integrity is a breeze since these keys ensure solid data relationships. It’s similar to a puzzle that fits neatly into its place. When you want to find related information, foreign keys act as a treasure map, leading you from one table to another. They’re crucial for smooth database experience, prevent orphaned data, and keep everything neat. 

In short, foreign keys enforce referential integrity

How Does MySQL Foreign Key Work? 

In database design, a foreign key isn’t meaningful with just a single table; it requires at least two tables to establish a relationship. To illustrate this, consider a scenario where we have two database tables: authors and books. Every book has an author. In other words, someone is not an author if they have never written a book. 

Another way to explain the foreign keys is by having parent and child tables in MySQL. The authors table is a parent table, while the books table is a child table. See an illustration of this scenario below. 

So, if you try to add a book with an author_id of 2, MySQL will reject it because the book doesn’t exist in the authors table. Foreign keys keep the database from having unknown data.  

Therefore, a foreign key will create and maintain relationship between two or more tables. That’s why, you can also refer to this as a foreign key constraint

You should appreciate it. Garbage or orphaned data, whatever you call it, is a waste of space. Furthermore, this kind of information serves no purpose for anyone requiring accurate data. So, it should not be there in the first place. Understanding this concept is key to solving foreign key violations. Later, we’ll illustrate how it works. 

What Makes MySQL Foreign Key “Foreign” to a Table? 

Picture it this way: a primary key is the superstar of a table, unique and important within its domain. It’s similar to the lead character in a story. Meanwhile, a foreign key takes on the role of a traveler from a different table and serves as a guest character with a special connection. Think of it as a cameo appearance in a movie – the foreign key doesn’t steal the spotlight. Instead, it references the primary key in another table. 

Therefore, it earns the label ‘foreign’ because it’s not the main star of its own show but rather serves as a key player in connecting the storyline across tables. 

Consider having Batman make an appearance in a Flash movie. While Barry Allen (the Flash) holds the spotlight, Bruce Wayne (Batman) is also a key to the story. 

Benefits of MySQL Foreign Keys 

  • Avoid Orphaned Data. Do you have child rows without a corresponding parent row? Then, the referential integrity of your database is weak to none. Foreign keys act as the police. They catch orphaned rows and arrest them. They ensure no one violates the referential integrity rule. 
  • Avoid Inconsistent Reports. This relates to the first benefit. Orphaned rows are responsible for mismatching report totals between summaries and report details. 
  • Better Database Diagram. Foreign keys add life to a sea of tables. Individual boxes (tables) offer no story in a database, while arrows indicate relationships.  
  • No Need to Code Further. You may want to handle orphaned rows by yourself using code. Instead, foreign key will do this for you and thus, increase your productivity.

How to Design MySQL Tables with Foreign Keys? 

Before you add foreign keys to tables, you have to understand the relationship they’re meant to have. You can initiate the table design process by sketching it out on paper and then using SQL code to create the tables with foreign keys. Alternatively, you can use GUI tools such as dbForge Studio for MySQL to visually design your tables and enhance code accuracy with a high-end code editor. It should be noted that having foreign keys in tables can help you visually create queries much faster. 

Regardless of which tool you’re using, creating foreign keys is easy. Still, this may be a challenge for newbies. It’s a classic chicken-and-egg dilemma when it comes to adding foreign keys. 

The Chicken-and-Egg Design Dilemma 

Let me explain it using the example with the authors and books tables. I promise you won’t hesitate to use foreign keys in the future. 

To begin, you may want to design two tables as we did in the first illustration. But wait! Didn’t books have authors? Should I put the book_id in the authors table too? See, it’s like deciding “which came first: the chicken or egg?” 

In the database world, this hesitation creates a loop where one table row can’t exist without the other and vice versa. It’s a bit of a head-scratcher! 

Let’s create two tables in MySQL with the following relationships: 

As a result, you get a self-defeating design. In this case, inserting new rows into both tables is impossible. Your supposed “better half” is no longer an improvement, but rather an “other half”. This results in a scenario when nothing works for both tables involved. 

How to Avoid the Chicken-and-Egg Design Problem 

The better design is the one we did first (authors and books tables) – “Authors write books”: 

First, create the authors table without including a foreign key pointing to books. Next, create the books table and add a foreign key pointing to the authors table. This way, you break the loop and let the database differentiate the parent and child tables. 

Remember, a table cannot simultaneously function as both parent and child tables. This may sound confusing. 

Another option is a “Books have authors” relationship and here how it looks like: 

The solution here is to choose one option – you can’t have “Authors write books” and “Books have authors” at the same time. 

When to Decide for Another Table to Link Two Tables 

Our initial design of the authors and books tables only permits one author per book. However, some books may have multiple authors. Here are some examples: 

If you follow the original design, you will duplicate the title of the book in the books table with different authors. Therefore, you need a third table to avoid duplication. That table will include both author id and book id, and the foreign keys. Here’s the modified design: 

So, if you encounter a scenario like this, it’s a good idea to create a third table. 

When a Foreign Key Points to the Same Table 

Now, I know that we resolved the chicken-and-egg problem and we won’t create another one here. This scenario involves only one table, where the foreign key points to the same table using different columns as keys. 

Here’s a scenario using the authors and books idea again. Let’s say you want to identify which books are sequels to one another like a trilogy. The examples may be from Stephen King and Robert Ludlum: 

Stephen King (The Bill Hodges Trilogy) 

  • Mr. Mercedes (2014), 
  • Finders Keepers (2015), and 
  • End of Watch (2016)

Robert Ludlum (The Jason Bourne Series) 

  • The Bourne Identity (1980), 
  • The Bourne Supremacy (1986), and 
  • The Bourne Ultimatum (1990) 

To do this in our books table, we need to add another column – series_id. This column references the book_id that precedes it. In the case of the first book in a series, this series_id column remains null. See the sample data above in the books table below: 

Series_id 1 points to book_id 1 because Finders Keepers (2015) is the next installment after Mr. Mercedes (2014). Mr. Mercedes (2014) has a null series_id because it’s the first installment of the series. Then, series_id 2 refers to book_id 2, and so on. Note that we intentionally hide the authors and book_authors tables for clarity purposes. 

Here’s the modified design of the books table: 

These are the basics of understanding relationships and adding foreign keys. 

The next section will discuss how to add foreign keys in MySQL using code. 

How to Add MySQL Foreign Key to a New Table Using CREATE TABLE 

When creating tables in MySQL, it’s possible to add a foreign key. However, remember that a foreign key cannot be added when there is only one table in the database. 

The syntax of a MySQL foreign key is within the syntax of CREATE TABLE, and here it is: 

CREATE TABLE child_table_name 
( column1 column_definition, column2 column_definition, columnN column_definition, 
  [CONSTRAINT constraint_name]  
  FOREIGN KEY [index_name](foreign_key_column1, ...) 
  REFERENCES parent_table_name(parent_table_column1, ...) 
  [ON DELETE RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT] 
  [ON UPDATE RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT], ... 

Let’s explain the syntax: 

  • CREATE TABLE child_table_name: Specify the name of the child table. Note that a parent table already exists in the database.
  • column1 column_definition: Add the primary key column, foreign key column, and other columns. The column definition includes the data type, size, etc.
  • [CONSTRAINT constraint_name]: It is optional. Specify a constraint name to differentiate several constraints, including foreign keys. If you don’t provide one, MySQL will assign a constraint name.
  • FOREIGN KEY [index_name]: The FOREIGN KEY keyword is a must, while the index name is optional. MySQL will use the constraint name for the index name if provided. If both constraint name and index name are empty, MySQL will provide a name for each.
  • (foreign_key_column1,…): Specify the foreign key columns that should exist in the table you are creating.
  • REFERENCES parent_table_name: Specify the name of the parent table.
  • (parent_table_column1, …): Define the columns from the parent table. They should have the same data types as the foreign key columns.
  • ON DELETE and ON UPDATE: It is optional. It tells MySQL what to do when a parent row has matching child rows during the delete and update operations. If it is not specified, MySQL may trigger a foreign key violation. Check the Foreign Key Options for more information.
  • Multiple Foreign Keys: Repeat the constraint syntax for every foreign key using different constraint names. A comma separates each constraint.

Example 1: Add One Foreign Key to a Table 

This query will add a foreign key to the books table with the authors table as a parent table: 

-- create the database 
CREATE DATABASE library; 

USE library; 

-- create the parent table 
CREATE TABLE authors 
(author_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 author_name varchar(30) NOT NULL); 

-- create the child table with a foreign key 
CREATE TABLE books 
(book_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 book_title varchar(50) NOT NULL,
 author_id int NOT NULL, 
 CONSTRAINT fk_books_authors_author_id 

 FOREIGN KEY (author_id) 
 REFERENCES authors(author_id) 
); 

This design uses one author for one book similar to the very first design. The author_id is the foreign key in the books table. We used a constraint name here, which MySQL will also use for the index. 

Example 2: Adding Two Foreign Keys to a Table 

Let’s say our books table also needs publishers. Therefore, we’ll need two foreign keys: one from the authors table and another from the publishers table. Consequently, the books table will have two parent tables, one for authors and another for publishers, similar to having two parents. 

-- create the database 
CREATE DATABASE library; 

USE library; 

-- create the parent table 
CREATE TABLE authors 
(author_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
 author_name varchar(30) NOT NULL); 

-- create another parent table 
CREATE TABLE publishers 
(publisher_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 publisher_name varchar(30) NOT NULL); 

-- create the child table with two foreign keys 
CREATE TABLE books 
(book_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 book_title varchar(50) NOT NULL, 
 author_id int NOT NULL, 
 publisher_id int NOT NULL, 

 /* create a foreign key from the authors table */ 
 CONSTRAINT fk_books_authors_author_id 
 FOREIGN KEY (author_id) 
 REFERENCES authors(author_id), 

 /* create a foreign key from the publishers table */ 
 CONSTRAINT fk_books_publishers_publisher_id 
 FOREIGN KEY (publisher_id) 
 REFERENCES publishers(publisher_id) 
); 

From the above code, you can see that you need to follow the sequence: first, create the parent tables and then the child table. Otherwise, MySQL will produce an error. 

Check out the diagram below for a clearer view of the relationships. 

You can add more foreign keys together with new tables as needed. 

Example 3: Adding Another Table to Link Two Tables 

This example will allow several authors for a book without duplicating the book titles. This can be achieved by creating another table that includes author_id and book_id

-- create the database 
CREATE DATABASE library; 

USE library; 

-- create the parent table 
CREATE TABLE authors 
(author_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 author_name varchar(30) NOT NULL); 

-- create another parent table 
CREATE TABLE publishers 
(publisher_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 publisher_name varchar(30) NOT NULL); 

-- create the child table  
CREATE TABLE books 
(book_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 book_title varchar(50) NOT NULL, 
 publisher_id int NOT NULL,   

 /* create a foreign key from the publishers table */ 
 CONSTRAINT fk_books_publishers_publisher_id 
 FOREIGN KEY (publisher_id) 
 REFERENCES publishers(publisher_id) 
); 

CREATE TABLE book_authors 
(book_author_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 author_id int NOT NULL, 
 book_id int NOT NULL, 

 CONSTRAINT uk_book_authors 
 UNIQUE KEY (author_id, book_id), 

 /* create a foreign key from the authors table */ 
 CONSTRAINT fk_book_authors_author_id 
 FOREIGN KEY (author_id) 
 REFERENCES authors(author_id),  

 /* create a foreign key from the books table */ 
 CONSTRAINT fk_books_authors_book_id 
 FOREIGN KEY (book_id) 
 REFERENCES books(book_id) 
); 

The book_authors table contains two foreign keys and a unique key. The following is the modified database diagram: 

Example 4: Relating a Table to Itself 

Earlier, we added a series_id column to the books table for a series. Let’s modify the books table by adding this column. 

CREATE TABLE books 
(book_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 book_title varchar(50) NOT NULL, 
 publisher_id int NOT NULL, 
 series_id int, 

 /* create a foreign key from the publishers table */ 
 CONSTRAINT fk_books_publishers_publisher_id 
 FOREIGN KEY (publisher_id) 
 REFERENCES publishers(publisher_id), 
 /* create a foreign key from the same table */ 
 CONSTRAINT fk_books_series_id 
 FOREIGN KEY (series_id) 
 REFERENCES books(book_id) 
); 

fk_books_series_id adds the relation to the same books table, while series_id relates to book_id. Here’s the updated diagram showing the books table only. 

How to Add a MySQL Foreign Key to an Existing Table Using ALTER TABLE 

You can add a foreign key to an existing table using ADD CONSTRAINT in the ALTER TABLE statement. 

Here’s the syntax: 

ALTER TABLE child_table_name 
   ADD CONSTRAINT [constraint_name]  
   FOREIGN KEY [index_name](foreign_key_column1, ...) 
   REFERENCES parent_table_name(parent_table_column1, ...) 
   [ON DELETE RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT] 
   [ON UPDATE RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT], ... 

The syntax is very similar to that of CREATE TABLE with a few exceptions: 

  • ALTER TABLE child_table_name. Specify the name of the child table you want to add foreign keys to. Both the parent and child tables should already exist. 
  • ADD CONSTRAINT [constraint_name]. These keywords are a must to add the MySQL foreign key constraint to an existing table. The name is still optional, and the same rules apply as in CREATE TABLE. 

Example 1: Adding a Foreign Key to an Existing Table 

This example assumes that the authors and books tables do not have foreign keys. 

ALTER TABLE books 
  ADD CONSTRAINT fk_books_authors_author_id 
    FOREIGN KEY (author_id) REFERENCES authors(author_id); 

Example 2: Adding Several Foreign Keys to an Existing Table 

You can add two foreign keys to the books table using ADD CONSTRAINT. Each constraint should be separated by commas: 

ALTER TABLE books 
 /* create foreign key from publishers table */
 ADD CONSTRAINT fk_books_publishers_publisher_id 
   FOREIGN KEY (publisher_id) 
   REFERENCES publishers(publisher_id), 

 /* create foreign key from the same table */ 
 ADD CONSTRAINT fk_books_series_id 
   FOREIGN KEY (series_id) 
   REFERENCES books(book_id); 

The above code assumes the books and publishers tables already exist. The first foreign key points to the publishers table while the second one refers to itself. 

Example 3: Adding Multi-Column Foreign Keys to Existing Tables 

The following example creates a database for a food chain offering combo meals like a McDonald’s Happy Meal, which consists of a burger, French fries, soda, and a toy. 

-- create the database 
CREATE DATABASE food_chain_store; 

USE food_chain_store; 

-- create a products table 
CREATE TABLE products 
(product_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 product_name varchar(30) NOT NULL, 
 is_combo_product boolean DEFAULT 0, 
 product_combo_item_id int, 

 unit_price decimal(10,2) DEFAULT 0.00, 

 CONSTRAINT uk_product_name 
 UNIQUE KEY (product_name)  
); 

-- create product order tables 
CREATE TABLE order_header 
(order_header_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 order_date datetime, 
 order_total decimal(10,2) NOT NULL); 

CREATE TABLE product_orders 
(order_header_id int NOT NULL, 
 product_id int NOT NULL, 
 line_number smallint NOT NULL, 
 unit_price decimal(10,2) NOT NULL DEFAULT 0.00, 
 quantity smallint NOT NULL DEFAULT 1, 

  PRIMARY KEY (order_header_id, product_id, line_number) 
); 

CREATE TABLE product_order_details 
(order_header_id int NOT NULL, 
 product_combo_id int NOT NULL, 
 line_number smallint NOT NULL, 
 product_id int NOT NULL, 
 unit_price decimal(10,2) NOT NULL DEFAULT 0.00, 
 quantity smallint NOT NULL DEFAULT 1, 
 PRIMARY KEY (order_header_id, product_combo_id, line_number, product_id) 
); 

/* create a foreign key for products to reference a product item included in a combo */ 
ALTER TABLE products 
  ADD CONSTRAINT fk_product_combo 
   FOREIGN KEY (product_combo_item_id) 
   REFERENCES products (product_id); 

/* create several foreign keys referencing products and order_header */ 
ALTER TABLE product_orders 
  ADD CONSTRAINT fk_product_orders_order_header 
    FOREIGN KEY (order_header_id) 
    REFERENCES order_header (order_header_id),  
  ADD CONSTRAINT fk_product_orders_product_product_id 
    FOREIGN KEY (product_id) 
    REFERENCES products(product_id); 

/* create foreign keys referencing product_orders with multiple columns */ 
ALTER TABLE product_order_details 
  ADD CONSTRAINT fk_product_orders_details 
    FOREIGN KEY (order_header_id, product_combo_id, line_number) 
    REFERENCES product_orders (order_header_id, product_id, line_number) 
    ON DELETE CASCADE 

The multi-column foreign key is added to the product_order_details table. It includes each product item in a combo ordered. 

To easily make sense of it all, have a look at the database diagram of the above code: 

Instead of writing code, consider using a GUI tool such as dbForge Studio for MySQL to add foreign keys: 

In the screenshot, the Table Designer is used to add a multi-column foreign key to the product_order_details table. dbForge Studio generates the SQL DDL code as you click and select columns. 

Using Foreign Key Options 

Earlier, we introduced the ON UPDATE and ON DELETE clauses of the MySQL foreign key constraint. The action taken to the parent and child tables depends on the following options: 

  • RESTRICT. It rejects the delete or update operations on the parent table. It is the same as not specifying ON UPDATE or ON DELETE. It serves as a ‘safeguard’, indicating that other issues must be resolved before proceeding.
  • CASCADE. Deleting a row from the parent table also results in the deletion of the matching rows in the child table. This process can be compared to a domino effect – when the main piece falls, everything linked to it goes down too. Similarly, updating the primary key of a row updates the matching rows in the child table. This analogy can be compared to distributing your new phone number to everyone.
  • SET NULL. When you update or delete a key in the parent table, the foreign key in the child table becomes null. However, if you define the foreign key column(s) as NOT NULL, you will trigger an error. To avoid this, make sure you set the foreign key column(s) to NULL. I don’t like this setting as it allows for orphaned rows.
  • NO ACTION. An option from standard SQL that performs the same function as RESTRICT in MySQL.
  • SET DEFAULT. Recognized by the MySQL parser but rejected by both InnoDB and NDB engines.

Example 1: Using RESTRICT 

Let’s say you defined the books table like this: 

CREATE TABLE books 
(book_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 book_title varchar(50) NOT NULL, 
 publisher_id int NOT NULL, 
 series_id int,
 

 /* create a foreign key from the publishers table */ 
 CONSTRAINT fk_books_publishers_publisher_id 
 FOREIGN KEY (publisher_id) 
 REFERENCES publishers(publisher_id) 
 ON DELETE RESTRICT 
 ON UPDATE RESTRICT, 

 /* create a foreign key from the same table */ 
 CONSTRAINT fk_books_series_id 
 FOREIGN KEY (series_id) 
 REFERENCES books(book_id) 
); 

Next, we add some rows to the publishers and books tables. 

INSERT INTO publishers (publisher_name) 
  VALUES ('Publisher 1'); 

INSERT INTO books (book_title, publisher_id) 
  VALUES ('The Shining', 1); 

Now, delete and update the publisher we added earlier. 

The output is as follows:

A foreign key error occurs as expected with the RESTRICT option. The same behavior happens with NO ACTION and without specifying the ON UPDATE and ON DELETE clauses. 

Example 2: Using CASCADE 

Let’s say you defined the books table with a delete and update CASCADE. 

CREATE TABLE books 
(book_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 book_title varchar(50) NOT NULL, 
 publisher_id int NOT NULL, 
 series_id int, 

 /* create a foreign key from the publishers table */ 
 CONSTRAINT fk_books_publishers_publisher_id 
 FOREIGN KEY (publisher_id) 
 REFERENCES publishers(publisher_id) 
 ON DELETE CASCADE 
 ON UPDATE CASCADE, 

 /* create a foreign key from the same table */ 
 CONSTRAINT fk_books_series_id 
 FOREIGN KEY (series_id) 
 REFERENCES books(book_id) 
); 

Next, add some rows and UPDATE publisher_id from 1 to 2: 

Upon performing the INSERT operation, new publisher_id is automatically set to 1 because of the AUTO_INCREMENT property. We also inserted ‘publisher_id = 1’ in the books table. However, after the UPDATE operation has been executed, publisher_id in the books table is also updated. 

ON DELETE CASCADE also behaves as expected: 

As you can see, the deletion of the publisher record triggers a deletion in the books table. 

Avoiding Gotchas in MySQL Foreign Key

Here’s a breakdown of common issues and their corresponding fixes: 

#1: Looping Foreign Keys (“Chicken-and-Egg” Situation) 

  • Issue: Creating tables that reference each other. It causes a dependency loop between them, and vice versa. 
  • Fix: Choose a parent table and create it first without the foreign key reference. After that, create the child table with the foreign key that refers to the parent table. 

#2: Incorrect Foreign Key Values 

  • Issue: Inserting data that doesn’t match the foreign key value. It leads to integrity errors. 
  • Fix: Double-check your data before insertion. Ensure it matches the values in the referenced table’s primary key. Alternatively, allow NULL if appropriate but maintain referential integrity. 

#3: Deleting Rows with Foreign Key Dependencies 

  • Issue: Attempting to delete a row that has child rows referencing it. 
  • Fix: Use the ON DELETE clauses like CASCADE to specify how to handle child rows when you delete a parent row. This maintains referential integrity without causing errors. Not specifying ON DELETE or ON UPDATE also catches orphaned data before they happen. But you have to deal with the foreign key violation in your front-end app. 

#4: Updating Foreign Key Values 

  • Issue: Trying to update the foreign key values first. Then, update the primary key value of the parent table. This will lead to a foreign key violation. 
  • Fix: Make sure you update both foreign key and primary key value if necessary or use ON UPDATE CASCADE, if applicable. 

#5: Dealing with Bulk Inserts 

  • Issue: Foreign key violations when inserting bulk data from CSVs and others. 
  • Fix: Ensure you insert data in the proper order. Begin by inserting data into parent tables and then into child tables. Disabling foreign keys temporarily will only make inserts easier. But you must ensure that you recreate the foreign keys in the correct order if you turn them back on. 

Remember, practice and experience are crucial. As you continue to work with MySQL foreign keys, you will become more familiar with them and adept at avoiding and resolving issues. 

Takeaways 

Foreign keys in MySQL ensure referential integrity and prevent orphaned data. In this article, we explained how to add foreign keys to the new or existing tables and also described RESTRICT and CASCADE options. 

We also introduced the GUI tool – dbForge Studio for MySQL which includes the database diagram, code editor, and other cutting-edge functionalities. Try it out and level up your productivity with the Query Profiler and other useful tools. 

Last modified: October 04, 2023
Close