20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5<br />

158<br />

Function Operator<br />

Multiply *<br />

Divide /<br />

Add +<br />

Subtract -<br />

What’s not obvious from this list is the order of precedence of the operators. If you remember back to<br />

Chapter 3, you’ll recall the discussion of the order of precedence of logical operators and that some operators<br />

are evaluated first.<br />

You can see the effects of operator precedence in the following <strong>SQL</strong>:<br />

SELECT MemberId, MemberId + 2 * 3<br />

FROM MemberDetails<br />

WHERE MemberId < 10;<br />

Running this query gives the following results:<br />

MemberId MemberId + 2 * 3<br />

1 7<br />

4 10<br />

5 11<br />

6 12<br />

7 13<br />

8 14<br />

9 15<br />

Rather than adding the MemberId to the number 2 and multiplying the sum by 3, the multiplication<br />

operator has higher precedence, so 2 is multiplied by 3 and the result of this, 6, is then added to the<br />

value in MemberId. This is very similar to the order of operations in algebra, where multiplication and<br />

division take precedence over addition and subtraction when they appear in the same equation. So if<br />

you want MemberId + 2 to be evaluated first and then multiplied by 3, you need to raise the order of<br />

precedence of that part by using brackets:<br />

SELECT MemberId, ( MemberId + 2 ) * 3<br />

FROM MemberDetails<br />

WHERE MemberId < 10;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!