Are brackets in the WHERE clause standard sql

我是研究僧i 提交于 2019-11-30 19:47:01

Yes. You can use parenthesis to bind components of where clauses. This isn't necessary in your example, but if you had multiple and and or components, you might need parenthesis to either ensure correct order of operations or simply to self-document the query.

Example 1:

select *
from foo
where 
   (class='A' and subclass='B')
   or (class='C' and subclass='D')

In example 1, the parens aren't strictly required because and binds more tightly than or, but if you had multiple or conditions tied by and you would need it to get correct results, as in example 2 below.

Example 2:

select *
from foo
where 
   (class='A' or class='B')
   and (subclass='C' or subclass='D')

I use them in either case, because I don't like having to parse the sql in my head the same way the query optimizer does -- I'd rather be explicit about it and more quickly understand what the intent is.

Claudio Bredfeldt

They are optional. They make sense for more complex WHERE statements.

... WHERE (created > '2012-10' AND created < '2013-01') 
OR (modified > '2012-10' AND modified < '2013-01')

No. They are only required to be used when you have AND on OR conditions in your statement to avoid shortcircuits, just like this:

SELECT...
FROM...
WHERE  col1 > 1 AND col2 < 3 AND col3 >= OR col3 = 1 AND col5 < 1

The above query will give you unexpected result as it will not determine the correct condition it will take. A round brackets will help you segregate condition in this case,

SELECT...
FROM...
WHERE  col1 > 1 AND col2 < 3 AND (col3 >= OR col3 = 1) AND col5 < 1

by the way, it should be single quotes ' ' not ‘ ’

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