开发者

Order of Filter to make the execution of SQL query better

I have two queries serving the same purpose.

SELECT * FROM #user 
    INNER JOIN #department ON #user.departmentId = #department.departmentId
    INNER JOIN #user m开发者_C百科anager ON #department.departmentHead = manager.userid
WHERE #department.DepartmentName= 'QA'

SELECT * FROM #user 
    INNER JOIN #department ON #department.DepartmentName= 'QA' AND #user.departmentId = #department.departmentId 
    INNER JOIN #user manager ON #department.departmentHead = manager.userid

The table structure is as follows.

create table #user
(
    userid int identity(1,1),
    userName varchar(20),
    departmentId int
)

create table #department
(
    departmentId int identity(1,1),
    departmentName varchar(50),
    departmentHead int
)

I am expecting some difference between the two queries, in the performance perspective. My assumption/understanding is that the first query gets executed in this order.

  1. Join all the records of user and department tables.

  2. Join the result of step 1 with all the records of Users table again.

  3. Apply WHERE condition (Department = 'QA').

Whereas the second one

  1. Join all the QA department records (filtered set) with the users table.

  2. Join the results of step 1 with all the records of user table.

I am assuming that the second query to be more efficient than the first one since the second query applies the filter at an early stage of execution saving the followers to deal with less number of records.

But SQL Execution plan doesn't show any difference between the two queries. Please explain this and validate if my understanding on the order of filter application is correct.


Actually SQL server has statistical data about your tables and can rearange the joins to create a more optimal execution plan.

Query hint FORCE ORDER specifies that the join order indicated by the query syntax is preserved during query optimization. But dont use that unless you have a performance problem.


Order of statements in SQL queries largely doesn't matter. The query gets compiled completely and then the execution plan is created based on what is calculated to be the likely best possible way to execute the query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜