A
A
AnjeyTsibylskij2017-05-16 12:50:13
PostgreSQL
AnjeyTsibylskij, 2017-05-16 12:50:13

Is it always necessary to use foreign keys?

Is there a performance benefit if using foreign keys in postgresql?
I understand that foreign keys are mostly for data integrity, but doesn't this slow down the process at large volumes?
After reading an article about the architecture of Instagram, I focused on the proposal: Decided to vertically split the data into several databases, using the routers mechanism from the ORM, getting rid of foreign keys in parallel
Simple task: there is a table of users and a table of posts. The posts table has a user_id field . There are a lot of posts. Should I make a foreign key and link the posts table to the users table or just put an index on the user_id fieldand achieve maximum performance?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
terrier, 2017-05-16
@AnjeyTsibylskij

Is there a performance benefit if using foreign keys in postgresql?
Apparently it meant whether there is a performance gain if NOT using foreign keys. Yes, may be. First, the foreign key check itself is not free - it's a system-level trigger. Second, postgres takes (among other things) a SHARED lock per row in the parent table. Accordingly, you need to take into account the impact of this on performance and monitor deadlocks.
However, here's a practical tip for you - leave these keys for now, postgres is very fast even with them, and a very big question is whether it is worth sacrificing data integrity for the sake of some (perhaps insignificant) performance gain (and without keys, your data is guaranteed to disperse).

O
OnYourLips, 2017-05-16
@OnYourLips

Foreign keys are not used in highload: integrity control at the storage level is not possible there.
If there is an opportunity to use them, then they should be used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question