Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of execution for this SQL statement

I have below SQL Query,

SELECT TOP 5 C.CustomerID,C.CustomerName,C.CustomerSalary FROM Customer C WHERE C.CustomerSalary > 10000 ORDER BY C.CustomerSalary DESC 

What will be execution order of the following with proper explanation ,

  1. TOP Clause
  2. WHERE Clause
  3. ORDER BY Clause
like image 688
Manoj Avatar asked Jul 01 '13 11:07

Manoj


2 Answers

Check out the documentation for the SELECT statement, in particular this section:

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

which gives the following order:

FROM ON JOIN WHERE GROUP BY WITH CUBE or WITH ROLLUP HAVING SELECT DISTINCT ORDER BY TOP 
like image 177
Brian Agnew Avatar answered Sep 25 '22 05:09

Brian Agnew


  1. WHERE
  2. ORDER BY
  3. TOP

Here is a good article about that: http://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/

like image 22
Andrey Gordeev Avatar answered Sep 21 '22 05:09

Andrey Gordeev