开发者

Does a redundant where predicate in a SQL query affect performance?

Consider a query like:

select *
from t
where a = 5 and (a = 5 and b = 7)

Does the redundant predicate a = 5 affect the performance of the query. I believe not, but I am being told otherwise (yes, I know that it depends on the DBMS but just assume it's some enterprise-y DBMS like SQL开发者_高级运维 Server, DB2 or Oracle).


The answer would normally be no, the redundant clause does not affect performance. Of course being a programmer you can use evidence to prove it one way or the other (unlike the person who will repeat their myths as fact).

Just open up your database of choice, enter your query with and without the redundent clause, then ask your database to explain both queries.

For example in SQL Server Management Studio (MS SQL Server) open a query window, enter your query and then right click and select "Display estimated executation plan" (or you can select an option to display the actual plan after the query is run).


I would like to quote the following from The Law of Leaky Abstractions by Joel Spolsky

The SQL language is meant to abstract away the procedural steps that are needed to query a database, instead allowing you to define merely what you want and let the database figure out the procedural steps to query it. But in some cases, certain SQL queries are thousands of times slower than other logically equivalent queries. A famous example of this is that some SQL servers are dramatically faster if you specify "where a=b and b=c and a=c" than if you only specify "where a=b and b=c" even though the result set is the same. You're not supposed to have to care about the procedure, only the specification. But sometimes the abstraction leaks and causes horrible performance and you have to break out the query plan analyzer and study what it did wrong, and figure out how to make your query run faster.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜