Search code examples
sqldatabasepostgresqljoininner-join

Which is better, 11 regular queries or 10 INNER JOIN queries?


Basically, I have a program that queries a postgres DB every so often, and then upon certain conditions it needs additional information from a separate table. I can get all the info from an INNER JOIN from the beginning, but most of the time the JOIN info is not needed.

I estimate at most like 1/10 of the time the JOIN info is needed, so which is more performant?

10 + 1 = 11 regular queries or 10 queries with JOIN

10 is a conservative guess, it may very well be 100+ queries before the join info is needed. How expensive are queries compare to queries with a JOIN clause in it?


Solution

  • Most joins are not expensive. Each query on the other hand takes time, because your program must make a conversation with the database (i.e. tell it what query it wants to issue, be told how many columns and which data type it'll get, and so on) in order to retrieve the data.

    Having the data already loaded with a join can make the program more responsive. Say, the user scrolls through a list of main data and on some lines detail data must be retrieved. It would be horrible, if you had to get this data from the database at the moment of scrolling.

    If on the other hand the user scrolls through a list of main data and if they want to see detail data, they must press a button, then some waiting time is expected. You can get it from the database in that case.

    So, the answer is: It depends. Both approaches are valid. Choose the one that looks more appropriate to you.