Are brackets in the WHERE clause standard sql

2020-03-02 03:42发布

问题:

The course that I am currently doing uses brackets in its WHERE clauses like so:

SELECT bar
FROM   Foo
WHERE (CurrentState = 'happy');

Is this standard sql ?
If not then why use them?

Doesn't seem to be used in the Date & Darwen book I have.


EDIT

Just to clarify - I'm referring to 1992 sql standards

回答1:

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.



回答2:

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')


回答3:

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 ‘ ’



标签: sql standards