Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are certain types of prepared queries using PDO in PHP with MySQL slow?
    primarykey
    data
    text
    <p>When using <code>SELECT * FROM table WHERE Id IN ( .. )</code> queries with more than 10000 keys using PDO with prepare()/execute(), the performance degrades ~10X more than doing the same query using mysqli with prepared statements or PDO without using prepared statements. </p> <p>More strange details:</p> <ul> <li><p>More typical SELECT statements that don't have the <code>WHERE Id IN( ..)</code> clause perform fine even with 100K+ rows. <code>SELECT * FROM table WHERE Id</code> for example is fast. </p></li> <li><p>The performance degradation occurs after prepare()/execute() is complete - it's entirely in <code>PDOStatement::fetch()</code> or <code>PDOStatement::fetchAll()</code>. The MySQL query execution time is tiny in all cases - this isn't a case of a MySQL optimization.</p></li> <li><p>Splitting the 10K query into 10 queries with 1K keys is performant.</p></li> <li><p>Using mysql, mysqli with prepared statements, or PDO without prepared statements is performant.</p></li> <li><p>PDO w/prepared takes ~6 seconds on the example below, while the others take ~0.5s.</p></li> <li><p>It gets worse in a non-linear fashion the more keys you have. Try 100K keys.</p></li> </ul> <p>Sample code:</p> <pre><code>// $imageIds is an array with 10K keys $keyCount = count($imageIds); $keys = implode(', ', array_fill(0, $keyCount, '?')); $query = "SELECT * FROM images WHERE ImageID IN ({$keys})"; $stmt = $dbh-&gt;prepare($query); $stmt-&gt;execute($imageIds); // until now, it's been fast. fetch() is the slow part while ($row = $stmt-&gt;fetch()) { $rows[] = $row; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload