Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query optimization : Which SELECT syntax is faster?

Given 5,000 IDs of records fetch in the database, which query , in your opinion is faster?

  1. Loop through 5000 IDs using php and perform a SELECT query for each one,

    foreach($ids as $id){
      // do the query 
      $r = mysql_query("SELECT * FROM TABLE WHERE ID = {$id}");
    }
    
  2. Or collect all ids in an array, and use SELECT * FROM TABLE WHERE ID IN (1 up to 5000)

    //assuming $ids = array(1,2 ---- up to 5000);
    $r = mysql_query("SELECT * FROM TABLE WHERE ID IN (".join(",",$ids).")");
    
like image 917
r2b2 Avatar asked Mar 24 '26 10:03

r2b2


2 Answers

Without a shadow of a doubt, loading them all in one go will be faster. Running 5,000 queries is going to be a lot slower as each query will carry a certain amount of overhead.

Also, to speed it up even more, DON'T use the * operator! Select the fields you are going to use, if you only need the ID column, specify this! If you want all the columns, specify them all, because you may later add fields in and you do not need to retrieve this new field.

like image 66
Tom Gullen Avatar answered Mar 26 '26 00:03

Tom Gullen


option 2 is definitely going to be faster. 5000 separate db queries are going to have huge network connection overhead.

like image 45
Sergey Eremin Avatar answered Mar 25 '26 22:03

Sergey Eremin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!