If you will consider the following table
table_A (id (PK), value1, value2)
If I want to insert a set of data, for example: (1,5), (1,3), (3,5)
I could perform a query such as :
INSERT INTO table_A (value1, value2) VALUES (1,5), (1,3), (3,5)
which would work. However, I am told prepared statements would be better. Looking into prepared statements it seems I would have to do something like this
$stmt = $dbh->prepare("INSERT INTO table_A (value1, value2) VALUES (?, ?)");
$stmt->bindParam(1, $value1);
$stmt->bindParam(2, $value2);
//for each set of values
$value1 = 1;
$value2 = 5;
$stmt->execute();
my question is, how can a prepared statement be better (performance wise) than the first method? One is a single query, the other involves several executions of the same query. Does the first query get compiled into three separate queries or something?
The prepared statement by itself is not going to be faster when you insert only once. However, if you need to run the same inserts multiple times, you will save on the time it takes to parse the query and prepare the query plan. The prepared statement insert will be parsed once, the plan for it will be cached, and then reused for all subsequent insertions. The statement with multiple embedded values, on the other hand, will need to be re-processed every time you run a new one, slowing the process down.
On the other hand, network roundtrips are slow as well. It may be slower to do an extra roundtrip than to parse and prepare a query plan, so you should profile before making a decision one way or the other.