SQL Logic Operator Precedence: And and Or

后端 未结 4 661
深忆病人
深忆病人 2020-11-21 23:53

Are the two statements below equivalent?

SELECT [...]
FROM [...]
WHERE some_col in (1,2,3,4,5) AND some_other_expr

and

SELE         


        
4条回答
  •  无人共我
    2020-11-22 00:47

    And has precedence over Or, so, even if a <=> a1 Or a2

    Where a And b 
    

    is not the same as

    Where a1 Or a2 And b,
    

    because that would be Executed as

    Where a1 Or (a2 And b)
    

    and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

     Where (a1 Or a2) And b
    

    Here's an example to illustrate:

    Declare @x tinyInt = 1
    Declare @y tinyInt = 0
    Declare @z tinyInt = 0
    
    Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
    Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F
    

    For those who like to consult references (in alphabetic order):

    • Microsoft Transact-SQL operator precedence
    • Oracle MySQL 9 operator precedence
    • Oracle 10g condition precedence
    • PostgreSQL operator Precedence
    • SQL as understood by SQLite

提交回复
热议问题