Sunday 9 November 2014

Predicate effect in ON and WHERE clause

There is always a question, Is using predicate in ON clause gives the same result using predicate in Where clause of a query?
Actually it depends on the order in which the conditions of a query are evaluated logically in SQL Server; but if the query is an inner join, then there is no difference between using predicate as part of ON clause or Where. They might generate different result when query is with OUTER joins because the predicates in ON clause applied to the table before the join, whereas WHERE clause is applied to the result of the join.

SQL Server Logical Query Execution Order:

1. FROM
2. ON
3. OUTER
4. WHERE
5. GROUP BY
6. CUBE | ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10 ORDER BY
11. TOP

ON clause predicate with Outer Join:

In case of OUTER JOIN query will follow sequence
SELECT  *
FROM    dbo.Employee emp
        LEFT JOIN dbo.EmployeeStatus es ON emp.Status_ID = es.Status_ID
                                           AND emp.Status_ID <> 2
1.       Table Employee scanning ( Table at left side of the Outer clause )
2.       Table EmployeeStatus scanning with predicate Status_ID<>2


Result Set:

WHERE clause predicate with Outer Join:

In Case of WHERE clause query will follow the sequence
SELECT  *
FROM    dbo.Employee emp
        LEFT JOIN dbo.EmployeeStatus es ON emp.Status_ID = es.Status_ID
WHERE   emp.Status_ID <> 2
1.       Table Employee scanning
2.       Table EmployeeStatus scanning
3.       Result set filtering based on predicate Status_ID<>2


Result Set :

Reference Link:
http://msdn.microsoft.com/en-us/library/ms177634.aspx