Monday 18 June 2012

Lesson 12: Multiple Conditions in SQL


You can add multiple criteria to your Where clauses by using "and" or "or."


Syntax:
Select */fieldname<mask> ... 
from tablename ... 
where fieldname =/!=/<> ... value
and/or
fieldname =/!=/<>... value
and/or
fieldname =/!=/<> ... value 
order by fieldname <desc> ...


Explanation:
  • The and tells SQL to retrieve the record if both conditions are met.
  • The or tells SQL to retrieve the record if either condition is met.
  • The or is less restrictive and retrieves more records.
  • If multiple ands and ors are used, the ands are evaluated first, and then the ors.
  • Use parentheses to change precedence (the order of evaluation).
Examples:Retrieve all vendors who are located in Chicago and have a current balance over 1,500 dollars. Order the results by current balance.
  1. In the SQL text box, type:
Select Name, City, CurrBal [-ZZ,ZZZ.99]
from TrnVendor
where City = 'Chicago'
and CurrBal > 1500
order by CurrBal;
  1. Execute the SQL statement.
Results:
 

NameCityCurrBal
Make Shift TiltsChicago1,793.23
Music MakerChicago4,109.14


Retrieve all vendors who are located in Chicago or who have a current balance over 1,500 dollars.
  1. In the SQL text box, type:
Select Name, City, CurrBal [-ZZ,ZZZ.99]
from TrnVendor
where City = 'Chicago'
or CurrBal > 1500
order by CurrBal;
  1. Execute the SQL statement.
NameCityCurrBal
Distant HorizonsChicago26.98
BedMakers LinenChicago500.00
Paltry PlayChicago1,000.00
Spot OutDetroit1,606.54
Narrow NestToledo1,609.00
No Waste DisposalPark Ridge1,720.98
Make Shift TiltsChicago1,793.23
Legal LookupHouston3,215.16
Music MakerChicago4,109.14
Softer SoftwareMonroe9,873.67


The next two SQL statements use exactly the same syntax except that the order of precedence is different (note parentheses in second example).
Retrieve all vendors from Chicago whose expense account is 4110 or any vendor with a current balance over 1200.
  1. In the SQL text box, type:
Select City, CurrBal [-ZZZ,ZZZ.99], ExpAcct
from TrnVendor
where City = 'Chicago'
and ExpAcct = '4110'
or CurrBal < 1200 
order by City, ExpAcct;
  1. Execute the SQL statement.


CityCurrBalExpAcct
Bayshore498.054110
Burlington51.004120
Chicago4,109.144110
Chicago500.004120
Chicago1,000.006080
Chicago26.98
7230



Retrieve all vendors whose expense account is 4110 or who have a current balance over 1200. The vendor must be located in Chicago.
  1. In the SQL text box, type:
Select City, CurrBal [-ZZZ,ZZZ.99], ExpAcct
from Vendor
where City = 'Chicago'
and (ExpAcct = '4110'
or CurrBal > 1200) 
order by City, ExpAcct;
  1. Execute the SQL statement.
Results:
 
CityCurrBalExpAcct
Chicago0.004030
Chicago4,135.244110
Chicago1,309.954110
Chicago100.006010
Chicago500.006040
Chicago47.007010
Chicago106.007190

No comments:

Post a Comment