Say I have two tables, a
and b
:
a {
pk as int
fk as int
...
}
b {
pk as int
...
}
I want to join a and b in a query like so:
FROM a
JOIN b on a.fk = b.pk
Which of the following scenarios will be faster?
a.fk
is set up to be a foreign key on b.pk
- b.pk
is indexeda.fk
is set up to be a foreign key on b.pk
- b.pk
is not indexedb.pk
is indexedb.pk
is not indexedBonus question - how much faster/slower will each of these scenarios be?
If you could back up your answer with a reference then that'd be awesome. Thank you!
Foreign key indexes can significantly improve performance for queries that involve joins between the parent and child tables.
A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.
In terms of performance, fewer columns means that the database can process through the primary key faster since there is less data, and it also means that table joins will be faster since primary keys, together with foreign keys, are often used as the joining condition.
In case there are a large number of rows in the tables and there is an index to use, INNER JOIN is generally faster than OUTER JOIN. Generally, an OUTER JOIN is slower than an INNER JOIN as it needs to return more number of records when compared to INNER JOIN.
a.fk
is set up to be a foreign key on b.pk
- b.pk
is indexedb.pk
is indexeda.fk
is set up to be a foreign key on b.pk - b.pk
is not indexedb.pk
is not indexedThe performance differnces would be greatest between the indexed and non indexed versions, however whether it would be faster or slower would depend on whether it was a select or an insert. Having indexes and foreign key constraints slow down inserts but speed up selects (the index) or make the data more reliable (the FK). Since generally most inserts are not noticably slowed (unless you are doing large bulk inserts), it is usually in your best interests to have the FK and the index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With