tags:

views:

983

answers:

4

If i have a parameterized SQL statement like this:

SELECT * FROM table WHERE my_field = :field_value

Does anyone know if PDO will recognize this(see below) as the same SQL statement and use the cache instead of assuming it's a completely different SQL statement:

SELECT * FROM table WHERE my_field = :new_field_value

So, I guess the question is: if the name of a parameter changes in a parameterized select statement but nothing else changes, will I still get the performance benefit of caching? Or do I have to make sure that the parameter name stays the same?

+1  A: 

It should be recognized as the same statement since the caching is done after the query parameters are replaced by values

andy.gurin
Oh okay. I was under the impression that parameterization is useful for performance because caching can be done without worrying about the actual values that are part of the query. But it sounds like you're saying that caching is done with the given values.
Karim
A: 

PDO has no cache - MySql does. And yes, it will cache the "final" query in the query cache. Not only that, but if you use use the same prepared statements multiple times, you will gain an additional speed increase, because MySql can cache the query execution plan for that statement.

troelskn
So are you saying that it doesn't matter what name I use for parameters? As long as the syntax of the query is the same, i get the caching benefits?
Karim
No, you need to hold on to the prepared statement, to re-use it. But you can call it multiple times, binding different values each time, and get a slight benefit from that.
troelskn
+1  A: 

If you're using PDO_MySQL, it rewrites prepared statements into raw SQL on its own before the server even sees them, unless you set PDO::ATTR_EMULATE_PREPARES to false.

Ant P.
Doesn't that suggest that there's no performance benefit whatsoever to parameterization when using PDO with default attributes?
Karim
@Karim: Yes, pretty much. The default's there to make it work with MySQL 4.x. On top of no performance gains, PDO's rewriter is pretty buggy and doesn't handle edge cases well (it broke my code a few times until I learned to turn it off).
Ant P.
A: 

I'm not sure how PDO handles named parameters but if it uses MySQL prepared statements then you will need to use MySQL 5.1.17 or later if you want it to use the query cache.

MySQL Query Cache

Before MySQL 5.1.17, prepared statements do not use the query cache. Beginning with 5.1.17, prepared statements use the query cache under certain conditions, which differ depending on the preparation method:

ejunker