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.
Join all the records of user and department tables.
Join the result of step 1 with all the records of Users table again.
Apply WHERE condition (Department = 'QA').
Whereas the second one
Join all the QA department records (filtered set) with the users table.
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.
精彩评论