DEV Community

Cover image for How to Add, Show, and Drop MySQL Foreign Keys
Jamey Barton
Jamey Barton

Posted on

How to Add, Show, and Drop MySQL Foreign Keys

What is a foreign key in MySQL?

We’ll start with the definition. A foreign key is a column or a group of columns that allow cross-referencing related data across tables in a database. A foreign key relationship comprises a parent table (that contains the initial column values) and a child table (with column values that reference those of the parent table). A foreign key constraint is defined on the child table.

Why use MySQL foreign keys?

Let’s have a brief look at the primary reasons for using foreign keys.

Reason #1. The cornerstone of it all—which will be stated by nearly every article on foreign keys that you will find—is that foreign keys will help you constantly maintain the referential integrity of your databases. Moreover, you won’t need to overcomplicate things and store the same data in different tables simultaneously.

Reason #2. With foreign keys defining relationships between tables, it is easier to get a clear picture of database design, which in turn helps you troubleshoot possible issues.

Reason #3. Finally, foreign keys help achieve better performance of your queries. It does not happen directly, since the actual performance boost is gained through the use of indexes. However, foreign keys are indexed automatically because they are often used for searching, which makes them a vital part of search optimization.

https://blog.devart.com/mysql-foreign-key.html

Top comments (0)