MySQL
SQL

Welcoming Tables with Foreign Keys Into Your Database

intro

This blog will explain the use cases of using foreign keys within your tables inside of your database.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

If you’re a regular reader of this blog, you will certainly know that we like diving deep into certain topics that may be considered off-limits for developers or DBAs making use of “vanilla” data management strategies. In this blog, we’ve covered how InnoDB interacts with its own tablespace — ibdata1 — and many other interesting things.

Another interesting thing that is on the minds of many developers and DBAs, however, are foreign keys. Foreign keys are often the source of confusion or praise — depending on who you ask. Why is that the case and what can we do to make them work for us? Let’s start from the beginning.

What are Foreign Keys?

In the database world, the concept of foreign keys refers to one or multiple columns that are used to “link” data in two tables together so that developers working on the data set can control what data gets stored in the table bearing the foreign key.

To create a table with foreign key syntax in SQL, employ such a query:

Copy
        
1 ALTER TABLE demo_table ADD FOREIGN KEY (fk_id_column) REFERENCES demo_table2(id);

In most cases, such an SQL query will run and complete like a breeze, successfully adding a foreign key to a table called demo_table linked to a table called demo_table2 (adjust table names as necessary.) It will run like a breeze and create a foreign key!

After the foreign key will be created, it will act as the “missing link” that links tables together. On a high level, two tables linked together with a foreign key will look like so:

Two tables linked together with a foreign key on the CustomerID column
Two tables linked together with a foreign key on the CustomerID column

The example above illustrates two tables with one foreign key entity. At the same time, keep in mind that a table can have more than one foreign key where the key references primary keys belonging to different tables. Once a foreign key relationship is established, the foreign key column in the secondary (child) table will have the same value as the corresponding row in the main table.

In other cases, you may observe an error like Can't create table database.table_name (errno: 150 "Foreign key constraint is incorrectly formed") like seen below:

An error related to create a table with foreign key syntax in SQL  DbVisualizer
An error related to create a table with foreign key syntax in SQL — DbVisualizer

Such an error can be rather confusing, but in many cases, it has to do with a character encoding and collation mismatch. If you face such an error, ensure that the character encoding and the collation are the exact same on both of the tables and restart the operation.

Foreign Key Reference Options

Before restarting the operation, though, bear in mind that foreign keys allow you to set a way that referential integrity will be preserved. Options may vary depending on your DBMS of choice, but MySQL has five options: CASCADE, SET NULL, NO ACTION, RESTRICT, and SET DEFAULT.

Here’s what those options mean and why they are so important:

  1. CASCADE: should a row from the parent table be updated or deleted, the values of the matching rows in another table will be updated/deleted accordingly, too.
  2. SET NULL: should a row from the original table be updated or deleted, the values of the foreign key columns in the child table will be set to NULL.
  3. RESTRICT: should a row from the original table have a matching row in the child table, MySQL will not update or delete rows in the original table. Same goes with NO ACTION.
  4. SET DEFAULT: such an option exists and is recognized by the parser, however, it’s rejected by InnoDB.

In other words, you really have four options to choose from: CASCADE, SET NULL, RESTRICT, or NO ACTION . How to employ them depends heavily on the use case applicable in your specific situation: have a look at the card deck in your possession and choose wisely. Otherwise, don’t forget that create a table with foreign key syntax in SQL is only the tip of the iceberg.

We create such tables because we have a reason to do so; the reasons vary (they should), but your database needs to stay warm at all times. It needs to stay warm because you will face problems in your journey as a developer or DBA; those problems need to be squashed quickly and effectively using tools.

DbVisualizer is one of such tools. Not only will it let you observe what’s happening in your database, but it will also provide you with:

  1. A quick introspection into the most crucial data in your possession, no matter how much data you have.
  2. The ability to “purify” your queries (format them to make them look nicer) and that can be vital for those dealing with bigger data sets.
  3. The ability to observe information (columns/indexes/triggers) related to the table on the left side of the SQL client — together with the information, you will be provided with the exact length of data columns, and it can also do many other things!

Don’t be shy — give DbVisualizer a whirl today, and until next time!

Summary

To create a table with foreign key syntax in SQL, we employ foreign keys. Foreign keys need to be applied and worked with differently depending on what database management system you find yourself using — they also have a couple of options that make them act in a way different than usual. Weigh your choices, try queries out in a sandbox if you’re in doubt, and until next time. Oh, and don’t forget to try DbVisualizer too!

FAQ

How to create a table with foreign key syntax in SQL?

To create a foreign key on the demo_table linked to the id column in table demo_table2, use this SQL query:

Copy
        
1 ALTER TABLE demo_table ADD CONSTRAINT fk_id_column FOREIGN KEY (id_column) REFERENCES demo_table2(id);

Where Can I Learn More About SQL Indexes?

To learn more about index types and everything else that they involve, refer to our blog over at TheTable, as well as read books and attend industry events — for those into MySQL, the book Hacking MySQL: Breaking, Optimizing, and Securing MySQL for Your Use Case is a good place to start as the book will not only tell you how to optimize your SQL queries for performance, but tell you why your databases necessitate optimization and why their performance might be faltering in the first place.

Dbvis download link img
About the author
LukasVileikisPhoto
Lukas Vileikis
Lukas Vileikis is an ethical hacker and a frequent conference speaker. He runs one of the biggest & fastest data breach search engines in the world - BreachDirectory.com, frequently speaks at conferences and blogs in multiple places including his blog over at lukasvileikis.com.
The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

A Complete Guide to an SQL Recursive Query Expression

author Lukas Vileikis tags MySQL SQL 5 min 2025-04-16
title

A Guide to the SQL Standard Deviation Functions

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-04-15
title

SQL EXISTS: Syntax and Use Cases with Examples

author Leslie S. Gyamfi tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-04-14
title

Dealing With NULL in SQL: Complete Guide

author Leslie S. Gyamfi tags SQL 7 min 2025-04-09
title

A Complete Guide to the New MySQL 9 VECTOR Data Type

author Antonello Zanini tags MySQL MySQL 9 5 min 2025-04-08
title

Data Backup and Recovery: Implement the Golden Rule in Your Database

author Lukas Vileikis tags Backup Recovery SQL 6 min 2025-04-07
title

How to Delete Table Data in SQL: A Complete Guide

author Lukas Vileikis tags SQL 5 min 2025-04-03
title

SQL Query Optimization: Everything You Need to Know

author Leslie S. Gyamfi tags OPTIMIZATION SQL 9 min 2025-04-02
title

A Complete Guide to the Different Types of DBMS

author Antonello Zanini tags DBMS NOSQL SQL 8 min 2025-03-31
title

MySQL Indexing Mistakes 101

author Lukas Vileikis tags MySQL Search SQL 10 min 2025-03-27

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.