Royi Namir
Royi Namir

Reputation: 148524

SQL Server tsql parenthesis logic?

(dynamic query...)

select * from myTable where

(   <--- 

 @param1 IS NULL
                  OR (
                         param1 IN 
                                           ( 
                                              SELECT item
                                              FROM   blabla1
                                           )
                     )
)   <---
and
(   <---

 @param2 IS NULL
                  OR (
                         param2  IN 
                                           ( 
                                              SELECT item
                                              FROM   blabla2
                                           )
                     )
)   <---

question :

look at the parenthesis marked with <---.

Can I remove them ( without impacting the logic here ) ?

Upvotes: 0

Views: 941

Answers (3)

Gerardo Lima
Gerardo Lima

Reputation: 6703

@MikaelEriksson is right, the results will not be the same, because the AND operator has higher precedence over the OR operator (msdn).

In your sample, instead of (A or A') and (B or B'), you'll get A or (A' and B) or B'.

Upvotes: 1

Ritesh D
Ritesh D

Reputation: 228

No, you cannot remove them. If we remove these brackets then it will impact the logic.

Upvotes: 0

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

No. you need those but you can remove the ones around the IN statement.

select * 
from myTable
where
  (@param1 IS NULL OR @param1 IN (SELECT item FROM blabla1))
  and 
  (@param2 IS NULL OR @param2 IN (SELECT item FROM blabla2))

If you remove the ones you asked about you would have a query that works like this

select * 
from myTable
where
  param1 IS NULL
  OR
  (param1 IN (SELECT item FROM blabla1)) and param2 IS NULL 
  OR
  (param2 IN (SELECT item FROM blabla2))

Upvotes: 2

Related Questions