Search code examples
sqlsql-serverunion-allexcept

SQL Order of processing


Consider I have a query like

select * from A
Except 
select * from B 
union all
select * from B 
except
select * from A

Query is processed like

select * 
from 
(
select * from A
Except 
select * from B 
) a
union all
(
select * from B
Except 
select * from A 
) b

How is the order of processing defined in sql. Will it process like this at any case

select * from A
Except 
select * from
(
select * from B 
union all
select * from B 
) a
except
select * from A

Solution

  • UNION and EXCEPT have equal precedence but will bind from left to right, meaning they are evaluated in "left to right" order, as they are processed.

    From @SeanLange's URL (TL;DR), worth taking note of:

    If EXCEPT or INTERSECT is used together with other operators in an expression, it is evaluated in the context of the following precedence:

    • Expressions in parentheses
    • The INTERSECT operator
    • EXCEPT and UNION evaluated from left to right based on their position in the expression