In SQL, what does using parentheses with an OR mean?

天大地大妈咪最大 提交于 2019-12-24 15:55:30

问题


Example:

select count(*) from my table
where
column1 is not null
and
(column1 = 4 OR column1 = 5)

Example 2:

select count(*) from my table
where
column1 is not null
and
column1 = 4 OR column1 = 5

In my database with the real column names, I get two different results. The one with the parentheses is right because if I do:

select count(*) from my table
where
column1 is not null
and
column1 = 4

and then

select count(*) from my table
where
column1 is not null
and
column1 = 5

and add them together, I get the right answer...I think. Same as the first example with the parentheses above.

Why do I get different results by changing precedence with the OR test?


回答1:


It's not Oracle or SQL. It's basic boolean logic. The AND condition is "stronger" (has precedence) than OR, meaning it will be evaluated first:

column1 is not null
and
column1 = 4 OR column1 = 5

Means

column1 is not null
and
column1 = 4

is evaluated first, then OR is applied between this and column1 = 5

Adding parentheses ensures OR is evaluated first and then the AND.

Pretty much like in maths:

2 * 3 + 5 = 6 + 5 = 11

but

2 * (3 + 5) = 2 * 8 = 16

More reading here: http://msdn.microsoft.com/en-us/library/ms190276.aspx




回答2:


This comes down to whether your expression is parsed as:

(column1 is not null and column1 = 4) OR column1 = 5

or

column1 is not null and (column1 = 4 OR column1 = 5)

See the difference?



来源:https://stackoverflow.com/questions/10034489/in-sql-what-does-using-parentheses-with-an-or-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!