简体   繁体   中英

SQL query execution order

If I have a LINQ query like this:

query.OrderBy(e => e.Name).Where(e => e.Name.Contains("Test")).Take(10);

What would be the execution order of ORDERBY , WHERE and TAKE .

  1. Is ORDERBY done only on records that match the search criteria or on the whole table?
  2. Will it search whole table for search criteria and then do TAKE 10 records or it will stop search when it gets 10 records that match criteria?

Behind the hood that linq code is a SQL query. In SQL, you don't get to choose how the query is executed. This is a descriptive language, where you tell the database what results you want, and you let it figure out the most efficient way to do.

There are mental paths that we relate to to understand SQL code (like: the from clause is executed first, then the where clause, then group by if any, then select and finally order by ) - but the database does not necessarily follows that schema. Execution plans are usually built as directed acyclic graphs, that offer much more flexibility.

It occurs in this order -

WHERE predicate is used to filter results,

THEN ORDER BY to sort and

THEN 10 from that, which happens to be TOP 10 syntax.

You could easily see how its executed in SQL Server by running the query with "INCLUDE ACTUAL EXECUTION PLAN" on.

在此处输入图像描述

Here is the query i used to demonstarte plus the output. Sorry had to use Ozar's tool as getting the image here on SO might be annoying.

https://www.brentozar.com/pastetheplan/?id=H1v7h-q6D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM