Should I use one big SQL Select statement or several small ones?

15,987

Solution 1

You should run a profiling tool if you're truly worried cause it depends on many things and it can vary but as a rule its better to have fewer queries being compiled and fewer round trips to the database.

Make sure you filter things as well as you can using your where and join on clauses.

But honestly, it usually doesn't matter since you're probably not going to be hit all that hard compared to what the database can do, so unless optimization is your spec you should not do it prematurely and do whats simplest.

Solution 2

Generally, it's better to have one SELECT statement. One of the main reasons to have databases is that they are fast at processing information, particularly if it is in the format of query.

If there is any drawback to this approach, it's that there are some kinds of analysis that you can't do with one big SELECT statement. RDBMS purists will insist that this is a database design problem, in which case you are back to my original suggestion.

Solution 3

When you use JOINs instead of multiple queries, you allow the database to apply its optimizations. You also are potentially retrieving rows that you don't need (if you were to replace an INNER join with multiple selects), which increases the network traffic between your app server and database server. Even if they're on the same box, this matters.

Solution 4

It might depend on what you do with the data after you fetch it from the DB. If you use each of the four results independently, then it would be more logical and clear to have four separate SELECT statements. On the other hand, if you use all the data together, like to create a unified row in a table or something, then I would go with the single SELECT and JOINs.

I've done a bit of PHP/MySQL work, and I find that even for queries on huge tables with tons of JOINs, the database is pretty good at optimizing - if you have smart indexes. So if you are serious about performance, start reading up on query optimization and indexing.

Solution 5

I would say 1 query with the join. This way you need to hit the server only once. And if your tables are joined with indexes, it should be fast.

Share:
15,987
simpleblob
Author by

simpleblob

Updated on June 13, 2022

Comments

  • simpleblob
    simpleblob almost 2 years

    I'm building a PHP page with data sent from MySQL.

    Is it better to have

    • 1 SELECT query with 4 table joins, or
    • 4 small SELECT queries with no table join; I do select from an ID

    Which is faster and what is the pro/con of each method? I only need one row from each tables.