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 between 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.