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?

Anton Gildebrand
  • 3,641
  • 12
  • 50
  • 86

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
  • 124,003
  • 15
  • 196
  • 263
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,933
  • 21
  • 68
  • 111