Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using Foreign Key speed up table joins

I think my title is pretty self explainitory, however I will outline what I am doing below.

A person is connected to a town. This town is connected to a county. The county is connected to a country. There are many counties in one country. Also there are many towns in a county. That being said many people can be from the same town.

In my database I have a separate table for people, towns, counties and countries. To get a full user record I LEFT JOIN the tables on a record set. This is a simplied version of what I do as a singular person is spread across many more tables. Would the use of FOREIGN keys speed up the execution of my query? Even if it is only a slight speed increase or less resource usage happening I would be interested.

The scale at which I am planning for is quite large, so the execution time and resource usage could be useful. As on a single person coming back from the database I have roughly 5-6 joins for multiple tables.

edit for the answer so far I would like to point out I am indexing each table, using primary and unique keys. Also the data set could quickly add up to millions of rows in one table(people) so performance is key.

like image 981
JustSteveKing Avatar asked May 06 '26 19:05

JustSteveKing


1 Answers

Foreign keys do not directly speed up the execution of queries. They do have an indirect effect, because they guarantee that the referenced column is indexed. And the index will have an impact on performance.

As you describe the problem, all the join relationships should include the primary key on one of the tables. The resulting queries should be a very efficient in execution.

I would not worry about 5 or 6 joins for the queries -- unless you have a very large amount of data (more than one table with millions of rows). Or you are in a severely memory-constrained environment.

like image 166
Gordon Linoff Avatar answered May 09 '26 16:05

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!