Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to return one big query or a few smaller ones?

Tags:

I'm using MySQL to store video game data. I have tables for titles, platforms, tags, badges, reviews, developers, publishers, etc...

When someone is viewing a game, is it best to have have one query that returns all the data associated with a game, or is it better to use several queries? Intuitively, since we have reviews, it seems pointless to include them in the same query since they'll need to be paginated. But there are other situations where I'm unsure if to break the query down or use two queries...

I'm a bit worried about performance since I'm now joining to games the following tables: developers, publishers, metatags, badges, titles, genres, subgenres, classifications... to grab game badges, (from games_badges; many-to-many to games table, and many to many to badges table) I can either do another join, or run a separate query.... and I'm unsure what is best....

like image 975
Mohamad Avatar asked Oct 11 '10 22:10

Mohamad


People also ask

What is faster one big query or many small queries?

However, in the context of the question, a single large query will be faster that, let's say -in the worse possible scenario- a SELECT inside a programming loop (no matter the RDBMS used).

What is the difference between single query and multiple query?

With a single query you get everything in one go. With multiple queries you get one thing. Then you ask for another thing and get that.

Are mysql views faster than queries?

Contrary to the answers - In my experience, for views with lots of joins, doing a direct query runs faster.

Can handle multiple queries at a time?

Can a SQL Server handle multiple queries at the same time? Assuming each query is looking into different partition of the data? All (reasonable) databases can handle multiple queries at the same time. The answer is mostly yes, but knowing the context for your question would help.


1 Answers

It is significantly faster to use one query than to use multiple queries because the startup of a query and calculation of the query plan itself is costly and running multiple queries in a row slows the server more each time. Obviously you should only get the data that you actually need, but fewer queries is always better.

So if you are going to show 20 games on a page, you can speed up the query (still using only one query) with a LIMIT clause and only run that query again later when they get to the next page. That or you can just make them wait for the query to complete and have all of the data there at once. One big wait or several little waits.

tl;dr use as few queries as possible.

like image 76
Explosion Pills Avatar answered Sep 29 '22 01:09

Explosion Pills