by raganwald · 16y ago · 0 comments
The database maintains a cache of query plans, so when you give it the same query, you get the query plan back right away and the database runs it.
There are data caches for other reasons, but the problem Jeff is describing is that the C# VM must interpret all the steps of building a SQL query in text every time it's run. The database may have the query plan cached, but even though the code never changes, building the SQL query string happens every time.
i thought that he was saying that a new plan is always constructed. what i was saying is that a new plan only needs to be constructed for "sufficiently different" queries, where "sufficiently different" can be something much more stringent than the hash of the literal text.
if we're only worrying about the parsing time (as opposed to the time to build and optimize a plan) then it's even more pointless to worry about this (i'm assuming parsing is significantly faster than actually building a plan).
[edit: i'm confused who is who here; have swapped person twice, hope this is correct]
But the point of the article is that the problem is not in the database, it's over in the CLR which is spending a lot of time composing the SQL text that gets sent to the database.
In Oracle, when you use literals any change to the text results in another hard parse on the database side. However, you can use bind variables instead of literals and it can re-use the query plan even when you are searching for different values.
http://www.akadia.com/services/ora_bind_variables.html
The OP is talking about LINQ. I assume that its Oracle implementation is smart enough to use bind variables, but I am not going to look that up right now...
(usually it's simply "exec User_GetBySandalCount @sandalCount", 4)
update: NVM!
http://dev.mysql.com/tech-resources/articles/mysql-query-cac...
Which is disappointing. I will go look at Postgres... and it seems to cache only at a lower level (indices, tables etc).
The only reason I can think of for a query with different literals in the conditionals to have a different plan would be if a histogram of frequencies was actually kept such that different literals created large differences in result sizes which then get fed into a join and affect the join logic. But that's going to be pretty rare and is a level of optimization that is unnecessary. It's also not going to make a huge difference unless the query is very complex, because the plans for simple queries are... simple.