1

I have thought of this a lot and never found the answer. I have found my self in situations where i haven't known how the conditions in a where clause of a SQL query is evaluated. To be sure, i have always used parentheses to make it more readable, and simple to understand. I consider it to be good practice to use parentheses sometimes to increase readability, even if it maybe isn't needed.

Consider the following query

SELECT * 
FROM mytable 
WHERE name='Anton' 
  AND lastname='Gildebrand' 
   OR age > 18 
  AND country='Sweden'

I imagine that this query is actually equal to

SELECT * 
FROM mytable 
WHERE name='Anton' 
 AND (lastname='Gildebrand' OR (age > 18 AND country='Sweden'))

Is this correct? Or how is the conditions evaluated? Does it differ from different database engines?

a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
Anton Gildebrand
  • 3,521
  • 12
  • 47
  • 84

2 Answers2

8
SELECT * FROM mytable
WHERE name='Anton' AND lastname='Gildebrand' OR age > 18 AND country='Sweden'

Is equal to:

SELECT * FROM mytable
WHERE (name='Anton' AND lastname='Gildebrand') OR (age > 18 AND country='Sweden')

Sources: TSQL, MySQL, Oracle, PostgreSQL

MarcinJuraszek
  • 121,297
  • 15
  • 183
  • 252
3

If you are talking about and and or, then in absence of parenthesis and is evaluated first. The same as * and + in math.

These rules are not dependent on SQL implementations.

PM 77-1
  • 12,254
  • 20
  • 64
  • 106