Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Foreign Key constraints in MySQL?

I was wondering,

What will be my motivation to use constraint as foreign key in MySQL, as I am sure that I can rule the types that are added?

Does it improve performance?

like image 592
Dejell Avatar asked Aug 08 '10 10:08

Dejell


People also ask

Why do we use foreign key constraints?

Although the main purpose of a foreign key constraint is to control the data that can be stored in the foreign key table, it also controls changes to data in the primary key table.

What is the purpose of a foreign key in SQL?

A foreign key is a column or set of columns that allow us to establish a referential link between the data in two tables. This referential link helps to match the foreign key column data with the data of the referenced table data.

What's the benefit of having primary and foreign keys?

Primary and foreign keys help create structure in relational databases. A primary key ensures unique row identification. This results in faster sorting, searching, and querying operations. A foreign key creates a link between two tables.


1 Answers

Foreign keys enforce referential integrity. These constraints guarantee that a row in a table order_details with a field order_id referencing an orders table will never have an order_id value that doesn't exist in the orders table.

Foreign keys aren't required to have a working relational database (in fact MySQL's default storage engine doesn't support FKs), but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity). The ability to enforce referential integrity at the database level is required for the C in ACID to stand.

As for your concerns regarding performance, in general there's a performance cost, but will probably be negligible. I suggest putting in all your foreign key constraints, and only experiment without them if you have real performance issues that you cannot solve otherwise.

like image 137
Daniel Vassallo Avatar answered Sep 27 '22 03:09

Daniel Vassallo