Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Optimize Query

Author  Topic 

bobbabuoy
Starting Member

33 Posts

Posted - 2004-05-17 : 07:21:22
Can someone please help me understand when/how you should use parentheses when writing queries? My queries are working fine but I want them to work optimally well. Is there a tutorial out there?

Thanks!

nr
SQLTeam MVY

12543 Posts

Posted - 2004-05-17 : 07:27:12
parentheses normally won't affect the query plan but they may make the query more difficult to understand.

I tend to use them just for or's and subqueries.

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

SamC
White Water Yakist

3467 Posts

Posted - 2004-05-17 : 07:42:46
Parentheses [known as brackets in the UK, but hey, they've got a sense of humor] are needed to set subqueries apart as in:

SELECT Cola FROM Mytable WHERE Colb IN (SELECT ... )

and

SELECT SevenUp
FROM (
SELECT ... FROM ...
) A

Go to Top of Page

ravilobo
Master Smack Fu Yak Hacker

1184 Posts

Posted - 2004-05-17 : 08:28:54
If you are doing something like below..
5*10/10

The position of bracket will deside the output..
(5*10)/10
is differenr from
5*(10/10)

Use them in mathematical expressions...




------------------------
I think, therefore I am
Go to Top of Page

nr
SQLTeam MVY

12543 Posts

Posted - 2004-05-17 : 11:40:09
>> (5*10)/10
is differenr from
5*(10/10)

The result of those will be the same.
(5*10)/11
5*(10/11)
will be different due to integer arithmetic - but it's not a good idea to code like that as it's not very obvious what the intention is.

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2004-05-17 : 12:55:39
and as Nigel alludes, NEVER mix AND's and OR's without using parenthesis, even if you know the default evaluation order and it always seems to work the way you like. Always fully parenthesize boolean expressions if an OR is involved.

for JOINS, I never use them -- haven't seen the need yet. MS Access drives me crazy because JET SQL for whatever reason requires every join to be in parenthesises which makes it impossible to read.

Speaking of MS Access, it also goes a little crazy and puts lots of parens around expressions and criteria, but most GUI code generaters do that including the query builder in EM.

- Jeff
Go to Top of Page
   

- Advertisement -