Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple PHP MySQL simpler queries vs one single more complex query,

Tags:

php

mysql

Should I do single more complex MySQL query or multiple simpler queries with PHP?

For example

Simpler queries:

UPDATE image SET profile = 0 WHERE user_id = 1;

UPDATE image SET profile = 1 WHERE user_id = 1 AND id = 10;

One single more complex query:

UPDATE image
    SET profile = CASE id WHEN 10 THEN 1 ELSE 0 END
    WHERE user_id = 1;

1: What is fastest and most efficient?

2: What is considered to be best practice, or preferred method?

like image 265
Alex Avatar asked Jul 06 '15 08:07

Alex


People also ask

What is faster one big query or many small queries in SQL?

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. Then you ask for another thing and get that.

Can MySQL handle complex queries?

MySQL was not designed for running complicated queries against massive data volumes (which requires crunching through a lot of data on a huge scale). MySQL optimizer is quite limited, executing a single query at a time using a single thread.

Are aggregate queries faster?

Database-level aggregation is much faster than executing the same aggregation logic at the application level while looping on large arrays. Using queries involving SQL aggregate functions with the GROUP BY statement allows you to reduce the number of rows returned drastically.


1 Answers

One single query is fastest and most efficient

Besides the IF statement, MySQL also provides an alternative conditional statement called MySQL CASE. The MySQL CASE statement makes the code more readable and efficient. See more details... http://www.mysqltutorial.org/mysql-case-statement/

like image 194
Lalit Patel Avatar answered Oct 19 '22 19:10

Lalit Patel