简体   繁体   English

SQL 查询执行顺序

[英]SQL query execution order

If I have a LINQ query like this:如果我有这样的LINQ查询:

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

What would be the execution order of ORDERBY , WHERE and TAKE . ORDERBYWHERETAKE的执行顺序是什么。

  1. Is ORDERBY done only on records that match the search criteria or on the whole table? ORDERBY是仅对匹配搜索条件的记录执行还是对整个表执行?
  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?它会在整个表中搜索搜索条件,然后执行TAKE 10 records ,还是在获得 10 条符合条件的记录时停止搜索?

Behind the hood that linq code is a SQL query. linq 代码的背后是一个 SQL 查询。 In SQL, you don't get to choose how the query is executed.在 SQL 中,您无法选择查询的执行方式 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.我们有一些思维路径可以理解 SQL 代码(例如:首先执行from子句,然后执行where子句,然后group by如果有的话),然后select最后order by ) - 但数据库不一定遵循该模式. 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, WHERE 谓词用于过滤结果,

THEN ORDER BY to sort and THEN ORDER BY 排序和

THEN 10 from that, which happens to be TOP 10 syntax. THEN 10 from that,这恰好是 TOP 10 语法。

You could easily see how its executed in SQL Server by running the query with "INCLUDE ACTUAL EXECUTION PLAN" on.通过运行“包括实际执行计划”的查询,您可以很容易地看到它在 SQL 服务器中是如何执行的。

在此处输入图像描述

Here is the query i used to demonstarte plus the output.这是我用来演示的查询加上 output。 Sorry had to use Ozar's tool as getting the image here on SO might be annoying.抱歉不得不使用 Ozar 的工具,因为在 SO 上获取图像可能很烦人。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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