Does adding "TOP 1" to the sql statement add significant performance?

In the SQL query, "TOP 1" is added to

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

give me an increase in performance when I know that there is only one of these entries? In particular, I am thinking about LinqToSql and the difference between the .Single(...) and .First(...) methods, where .First(...) adds TOP 1 to the generated sql.

LinqToSql is already feeling slow, so I'm just trying to figure out how to make it faster.

EDIT: [TABLE].Value may be a foreign key in some cases.

+4
source share
7 answers

A TOP 1 select should end after the first result is found, yes, it can be much faster depending on your request. On the other hand, you really want to consider the semantics and potential impact of undetected data inconsistencies. Single () is really the most suitable if there really is only one match. If you have more than one match and use Single (), you will get an exception and find out about the error in your data or in your code. In your case, I would use Single (). To speed up the query, I would like to add an index for the column (s) that I use as the discriminator.

+5
source

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

+2
source

Why not just add a UNIQUE index to the column?

+2
source

Adding a "TOP" clause may help in some cases - if SQL Server expects the query to return a very large number of results, it may lock the table while waiting. If you know that this will not happen and can be limited with TOP, this will not add this overhead.

+2
source

Single and First have different uses.

Single intended to describe the situation. You always want your code to "not run earlier."

If you request based on your primary key or a unique index, the query optimizer will in any case delete the sentence "TOP ... N".

In other cases, TOP 1 can have a positive effect on performance, but if this is not exactly what you want to do, do not.

0
source

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 may include more information about the actual query you are trying and why, for example, returning the first Placing a table with 10 rows compared to returning all 10 provides a small performance gain if your table has 7 million rows and the other completely.

0
source

No, this will potentially make your queries slower, because sorting can be done first.

-4
source

Source: https://habr.com/ru/post/1301143/


All Articles