开发者

Does Adding "TOP 1" to a sql statement increase performance signficantly?

In a SQL query, does adding "TOP 1" to

SELECT TOP 1 [values] FROM [TABLE] where [TABLE].Value = "ABC" 

give me a performance increase, when I know there is only one of those records? Specifically I'm thinking about LinqToSql and the difference b开发者_JAVA百科etween the methods .Single(...) and .First(...), where .First(...) adds the TOP 1 to the generated sql.

The LinqToSql already feels slow, so I'm just trying to think of ways to make it faster.

EDIT: The [TABLE].Value maybe a foreign key in some instances.


A TOP 1 select should terminate once the first result is found so, yes, it could be much faster depending on your query. On the other hand, you really want to consider the semantics and the potential implication of undetected inconsistencies in the data. Single() is really most appropriate if there really is only one match. If you have more than one match and are using Single() you'll get an exception and be made aware of either the error in your data or in your code. In your case I'd use Single(). To make the query faster, I would consider adding an index on the column(s) that I'm using as the discriminator.


My experience with SQL Servers tells me that it makes your query run much faster.


Why not just add a UNIQUE index on the column?


Adding a "TOP" clause can help in some cases - if SQL Server anticipates the query could return a very large number of results, it may lock the table in anticipation. If you know that won't be the case and can limit with a TOP, it won't add that overhead.


Single and First have different uses.

Single is meant for the situation you describe. You always want your code to "fail early."

If you are querying based on your primary key, or a unique index, the query optimizer is going to remove the "TOP ... N" clause anyways.

In other cases, TOP 1 might have positive performance impacts, but if that's not exactly what you want to do, don't do it.


I have a table with over 7 million records, the relative cost is much more expensive even with a clustered index if I select all the rows, I think your question could include more information about the actual query you are attempting and why, for instance, returning top 1 from a table with 10 rows vs returning all 10 provides negligible performance gains, if your table has 7 million rows, its another story entirely.


No, it will potentially make your queries slower because a sort may have to be done first.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜