ritesh gyanchandani ritesh gyanchandani - 7 months ago 15
SQL Question

Brackets use in where clause

Case1:

SELECT *
FROM Products
WHERE Price NOT BETWEEN 10 AND 20


Case2:

SELECT *
FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3)


Why is case 2 brackets are used after
Where
, what is the reason behind this and it's logic?

Answer

The SQL AND condition and OR condition can be combined to test for multiple conditions in a SELECT, INSERT, UPDATE, or DELETE statement.

When combining these conditions, it is important to use parentheses so that the execution knows in what order to evaluate each condition. (Just like when you were learning the order of operations in Math class!). In your case there is no precedence between the operators.

Example where brackets are needed:

SELECT 
  supplier_id
FROM 
   suppliers
WHERE 
  (name = 'IBM' OR name = 'Hewlett Packard')  AND city = 'Atlantic City'
Comments