Connecting conditions with logical operators  Chapter 3: Using Aggregates, Grouping, and Sorting

Chapter 2: Queries: Selecting Data from a Table

Logical operator precedence

Arithmetic and bitwise operators are handled before logical operators. When more than one logical operator is used in a statement, not is evaluated first, then and, and finally or. See “Bitwise operators” for more information.

For example, the following query finds all the business books in the titles table, no matter what their advances are, as well as all psychology books that have an advance of more than $5500. The advance condition pertains only to psychology books because the and is handled before the or.

select title_id, type, advance 
from titles 
where type = "business" or type = "psychology" 
  and advance > 5500
title_id  type        advance 
--------  ----------  ---------- 
BU1032    business     5,000.00 
BU1111    business     5,000.00 
BU2075    business    10,125.00 
BU7832    business     5,000.00 
PS1372    psychology   7,000.00 
PS2106    psychology   6,000.00 
 
(6 rows affected) 

You can change the meaning of the query by adding parentheses to force evaluation of the or first. This query finds all business and psychology books with advances of more than $5500:

select title_id, type, advance 
from titles 
where (type = "business" or type = "psychology") 
  and advance > 5500 
title_id  type         advance 
--------  ----------   --------- 
BU2075    business     10,125.00 
PS1372    psychology    7,000.00 
PS2106    psychology    6,000.00 
 
(3 rows affected) 




Copyright © 2005. Sybase Inc. All rights reserved. Chapter 3: Using Aggregates, Grouping, and Sorting

View this book as PDF