Professional Documents
Culture Documents
DBNote 05
DBNote 05
Chapter 5
Advanced Queries
Jerry Post
Copyright © 2003
1
D Tables
A
Animal
AnimalOrder Animal AnimalID
OrderItem Name SaleAnimal
OrderID
OrderID Category
OrderDate SaleID
T
AnimalID Breed
ReceiveDate Breed AnimalID
Cost DateBorn
SupplierID SalePrice
Gender
ShippingCost Category
Registered
EmployeeID Breed
Employee Color
A
Supplier ListPrice Customer
EmployeeID Photo
SupplierID LastName CustomerID
Name City FirstName Sale Phone
ContactName Phone FirstName
CityID SaleID
B
Phone Address LastName
ZipCode SaleDate
Address ZipCode Address
City EmployeeID
ZipCode CityID ZipCode
State CustomerID
CityID TaxPayerID CityID
AreaCode SalesTax
DateHired Category
Population1990
A
DateReleased
Population1980 Category
Country Registration SaleItem
Latitude
Longitude Merchandise SaleID
OrderItem
ItemID
S
ItemID
Merchandise PONumber Quantity
Description
Order ItemID SalePrice
QuantityOnHand
Quantity
PONumber ListPrice
Cost
OrderDate Category
E
ReceiveDate
SupplierID
EmployeeID
ShippingCost
2
D Organization
A
Harder Questions
T Subqueries
3
D Harder Questions
A How many cats are “in- Which customers (who
T stock” on 10/1/04?
Which cats sold for more
bought something at least
once) did not buy anything
S
E
4
D Sub-query for Calculation
A Which cats sold for more than the average sale price of cats?
Assume we know the average price is $170.
A
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE ((Animal.Category=‘Cat’) AND (SaleAnimal.SalePrice>
( SELECT AVG(SalePrice)
S
FROM Animal
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE (Animal.Category=‘Cat’)
E
)
) );
5
Query04_13
A Customer
CustomerID
Phone
Sale
SaleID
SaleDate
SaleItem
SaleID
ItemID
B
FirstName EmployeeID Quantity
LastName CustomerID SalePrice
A Table
Sort
Customer
Ascending
Customer
Ascendin
SaleItem
S Criteria
g
In (1,2,30,32,33)
Or
E List all customers (Name) who purchased one of the following items: 1, 2, 30, 32, 33.
6
D Using IN with a Sub-query
A List all customers who bought items for cats.
T SELECT Customer.LastName, Customer.FirstName, SaleItem.ItemID
A
FROM (Customer
INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID)
INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID
B
WHERE (SaleItem.ItemID In
(SELECT ItemID FROM Merchandise WHERE Category=‘Cat’)
);
A
S
E
7
Query04_14
T (SELECT CustomerID
FROM Sale
WHERE (Month([SaleDate])=5) );
A Customer
CustomerID
Sale
SaleID
LastName First
Adkins Inga
B Phone
FirstName
LastName
SaleDate
EmployeeID
CustomerID
McCain
Grimes
Sam
Earl
A Field
Table
LastName
Customer
FirstName
Customer
Month(SaleDate)
Sale
CustomerID
Customer
S Sort
Criteria
Ascending Ascending
3 In (SELECT CustomerID FROM State
E Or
WHERE (Month(SaleDAte)=5)
List all of the customers who bought something in March and who bought something in
May. (Two tests on the same data!) 8
Query04_15
A Any: value is compared to each item in the list. If it is True for any of
the items, the statement is evaluated to True.
S All: value is compared to each item in the list. If it is True for every
item in the list, the statement is evaluated to True (much more
restrictive than any.
E
9
Query04_16
T
AnimalID FROM Animal
Name WHERE (Animal.AnimalID Not In
Category
(SELECT AnimalID From SaleAnimal));
Breed
B Table
Sort
Animal Animal Animal 19
25
Gene
Vivian
Dog
Dog
34 Rhonda Dog
A Criteria
Or
Not In (SELECT AnimalID
FROM SaleAnimal)
88
181
Brandy Dog
Fish
10
D SubQuery: NOT IN (Data)
A Animal SaleAnimal
T
ID Name Category Breed ID SaleID SalePrice
2 Fish Angel 2 35 $10.80
4 Gary Dog Dalmation 4 80 $156.66
5 Fish Shark 6 27 $173.99
A 6
7
8
Rosie Cat
Eugene Cat
Miranda Dog
Oriental Shorthair
Bombay
Norfolk Terrier
7
8
10
25
4
18
$251.59
$183.38
$150.11
B
9 Fish Guppy 11 17 $148.47
10 Sherri Dog Siberian Huskie
11 Susan Dog Dalmation
12 Leisha Dog Rottweiler
A
S Which animals have not been sold?
E
11
Query04_17
A AnimalID
Name
Category
SaleID
AnimalID
SalePrice
12
19
25
Leisha
Gene
Vivian
Dog
Dog
Dog
B
Breed
34 Rhonda Dog
88 Brandy Dog
Field AnimalID SaleID Name Categor
181 Fish
A
y
Table Animal SaleAnimal Animal Animal
Sort
S Criteria
Or
Is Null
T 4
5
6
Gary
Rosie
Dog
Fish
Cat
Dalmation
Shark
Oriental Shorthair
4
Null
6
80
Null
27
$156.66
Null
$173.99
A
7 Eugene Cat Bombay 7 25 $251.59
8 Miranda Dog Norfolk Terrier 8 4 $183.38
9 Fish Guppy Null Null Null
10 Sherri Dog Siberian Huskie 10 18 $150.11
B 11
12
Susan Dog
Leisha Dog
Dalmation
Rottweiler
11
Null
17
Null
$148.47
Null
A
S
E
13
D Older Syntax for Left Join
A Which animals have not been sold?
T SELECT ALL
E
WHERE Animal.AnimalID = SaleAnimal.AnimalID (+)
And SaleAnimal.SaleID Is Null;
14
Query04_18
A FROM Animal
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE ((Animal.Category=‘Cat’) AND (SaleAnimal.SalePrice>
T ( SELECT AVG(SalePrice)
FROM Animal
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
A WHERE (Animal.Category=‘Cat’)
Animal SaleAnimal
) ) );
B
AnimalID SaleID average, so use a
Name AnimalID subquery to look it up.
Category SalePrice
Breed Watch parentheses.
A Field
Table
AnimalID
Animal
Name
Animal
Category
Animal
SalePrice
SaleAnimal
S Sort
Criteria 3
Descending
> (SELECT Avg(SalePrice) FROM
A (SELECT Avg(SaleAnimal.SalePrice)
FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE (Animal.Category = Animal.Category) ) )
B
ORDER BY SaleAnimal.SalePrice DESC;
T Correlated Subquery
Recompute subquery for every row in top level--slow!
Better to compute and save Subquery, then use in join.
A SELECT A1.AnimalID, A1.Name, A1.Category, SaleAnimal.SalePrice
FROM Animal As A1 INNER JOIN SaleAnimal
B ON A1.AnimalID = SaleAnimal.AnimalID
WHERE (SaleAnimal.SalePrice>
(SELECT Avg(SaleAnimal.SalePrice)
E
List the Animals that have sold for a price higher than the average for animals in
that Category.
17
D Correlated Subquery Problem
A Animal + SaleAnimal
Category SalePrice
T Fish
Dog
$10.80
$156.66
Compute Avg: $37.78
Compute Avg: $174.20
A
Fish $19.80 Compute Avg: $37.78
Cat $173.99 Compute Avg: $169.73
Cat $251.59
Compute Avg: $169.73
B
Dog $183.38
Fish $1.80 Recompute average
Dog $150.11 for every row in the
A
Dog $148.47 main query!
18
D More Efficient Solution: 2 queries
A Animal + SaleAnimal
Saved Query
Category SalePrice
T Fish
Dog
$10.80
$156.66
Category AvgOfSalePrice
Bird $176.57
A
Fish $19.80
Cat $173.99 JOIN Cat $169.73
Cat $251.59 Dog $174.20
Animal.Category = Fish $37.78
B
Dog $183.38
Fish $1.80 Query1.Category Mammal $80.72
Dog $150.11 Reptile $181.83
Spider $118.16
A
Dog $148.47
19
D UNION Operator
A SELECT EID, Name, Phone, Salary, ‘East’ AS Office
FROM EmployeeEast
UNION
T SELECT EID, Name, Phone, Salary, ‘West’ AS Office
FROM EmployeeWest
A EID
352
Name
Jones
Phone
3352
Salary
45,000
Office
East
B
876 Inez 8736 47,000 East
372 Stoiko 7632 38,000 East
S
Offices in Los Angeles and New York.
Each has an Employee table (East and West).
E
Need to search data from both tables.
Columns in the two SELECT lines must match.
20
D UNION, INTERSECT, EXCEPT
A
T A B C
List the name of any employee
who has worked for both the
East and West regions.
A
B T1 T2
E
21
D Multiple JOIN Columns
A Breed
Animal
AnimalID
Name
T Category
Breed
Category
Breed
A
DateBorn
Gender
...
B SELECT *
FROM Breed INNER JOIN Animal
A ON Breed.Category = Animal.Category
AND Breed.Breed = Animal.Breed
22
D Reflexive Join
A SQL EID
115
Employee
Name
Sanchez
... Manager
765
T
SELECT Employee.EID, 462 Miller 115
Employee.Name, 523 Hawk 115
Employee.Manager, E2.Name 765 Munoz 886
B ON Employee.Manager = E2.EID
EID Name
Result
Manager Name
115 Sanchez 765 Munoz
A 462
523
Miller
Hawk
115
115
Sanchez
Sanchez
23
D Recursive Joins (SQL 99 and 200x)
A WITH RECURSIVE EmployeeList (EmployeeID, Title, Salary) AS
( SELECT EmployeeID, Title, 0.00
T FROM Manages WHERE Title = “CEO” -- starting level
UNION ALL
SELECT Manages.EmployeeID, Manages.Title, Manages.Salary
B FROM EmployeeList
GROUP BY EmployeEID ;
A List all of the employees and list everyone who reports to them.
E
24
Not available in Microsoft Access. It is in SQL Server and Oracle.
D CASE Function
A Select AnimalID,
CASE
WHEN Date()-DateBorn < 90 Then “Baby”
T WHEN Date()-DateBorn >= 90
AND Date()-DateBorn < 270 Then “Young”
B END
FROM Animal;
S
Less than 3 months
Between 3 months and 9 months
E
Between 9 months and 1 year
Over 1 year
25
D Inequality Join
A AccountsReceivable
Categorize by Days Late
S SELECT *
FROM AR INNER JOIN LateCategory
26
D SQL SELECT
A SELECT DISTINCT Table.Column {AS alias} , . . .
FROM Table/Query
T INNER JOIN Table/Query ON T1.ColA = T2.ColB
WHERE (condition)
A GROUP BY Column
HAVING (group condition)
B ORDER BY Table.Column
{ Union second select }
A
S
E
27
D SQL Mnemonic
A
Someone SELECT
T From FROM
SQL is picky about
putting the
commands in the
A Ireland
Will
INNER JOIN
WHERE
proper sequence.
If you have to
B Grow
Horseradish and
GROUP BY
HAVING
memorize the
sequence, this
mnemonic may be
A Onions ORDER BY helpful.
S
E
28
D SQL Data Definition
A
Create Schema Authorization dbName password
T Create Table TableName (Column Type, . . .)
A more columns
B );
E
30
D Queries with “Every” Need EXISTS
A List the employees who have sold animals from every category.
T
A
B
A
S By hand: List the employees and the categories. Go through the
SaleAnimal list and check off the animals they have sold.
E
31
D Query With EXISTS
A List the Animal categories that have not been sold by an employee (#5).
T
SELECT Category
FROM Category
WHERE (Category <> "Other") And Category NOT IN
A (SELECT Animal.Category
FROM Animal INNER JOIN (Sale INNER JOIN SaleAnimal
ON Sale.SaleID = SaleAnimal.SaleID)
B ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE Sale.EmployeeID = 5)
A If this query returns any rows, then the employee has not sold every animal.
So list all the employees for whom the above query returns no rows:
32
D Query for Every
A SELECT Employee.EmployeeID, Employee.LastName
FROM Employee
B
FROM Animal INNER JOIN (Sale INNER JOIN SaleAnimal
ON Sale.SaleID = SaleAnimal.SaleID)
ON Animal.AnimalID = SaleAnimal.AnimalID
A );
WHERE Sale.EmployeeID = Employee.EmployeeID)
S Result: 3 Reasoner
E
33
D Simpler Query for Every
A Sometimes it is easier to use Crosstab and the Count function.
T
A
B
A
S But some systems do not have Crosstab, and sometimes the
34
D SQL: Foreign Key
A CREATE TABLE Order
(OrderID INTEGER NOT NULL,
T OrderDate DATE,
CustomerID INTEGER
A );
Order Customer
OrderID CustomerID
S OrderDate
CustomerID *
LastName
FirstName
E Address
…
35
D SQL Data Manipulation Commands
A
Insert Into target (column1 . . .) VALUES (value1 . . .)
T Insert Into target (column1 . . .) SELECT . . . FROM. . .
S
E
36
D Copy Old Animal Data
A INSERT INTO OldAnimals
SELECT *
T FROM Animal
WHERE AnimalID IN
(SELECT AnimalOrderItem.AnimalID
A FROM AnimalOrder INNER JOIN AnimalOrderItem
B ON AnimalOrder.OrderID = AnimalOrderItem.OrderID
WHERE (AnimalOrder.OrderDate<’01-Jan-2004’) );
A
S
E
37
D Delete Old Animal Data
A DELETE
FROM Animal
T WHERE AnimalID IN
(SELECT AnimalOrderItem.AnimalID
B WHERE (AnimalOrder.OrderDate<’01-Jan-2004’) );
A
S
E
38
D Update Example
A UPDATE Animal
SET ListPrice = ListPrice*1.10
T WHERE Category = ‘Cat’ ;
A UPDATE Animal
SET ListPrice = ListPrice*1.20
39
D Quality: Building Queries
A Break questions into smaller pieces.
Test each query.
B
Use cut-and-paste to avoid errors.
Who bought dogs?
Check for correlated subqueries.
Who bought cat products?
Test sample data.
A Identify different cases.
Check final query and subqueries.
S Verify calculations.
Test SELECT queries
Dogs and cat products on the same sale.
Dogs and cat products at different times.
E before executing
UPDATE queries.
Dogs and never any cat products.
Cat products and never any Dogs.
40
D Quality Queries: Example
A Which customers who bought Dogs also bought products for Cats?
A. Which customers bought dogs?
A
FROM Sale INNER JOIN (Animal INNER JOIN SaleAnimal
ON Animal.AnimalID = SaleAnimal.AnimalID)
ON Sale.SaleID = SaleAnimal.SaleID
B WHERE (((Animal.Category)=‘Dog’))
AND Sale.CustomerID IN (
S
ON Merchandise.ItemID = SaleItem.ItemID)
ON Sale.SaleID = SaleItem.SaleID
WHERE (((Merchandise.Category)=‘Cat’))
E );
41
D Programming Review: Variables
A Integer Double
T 2 bytes
-32768 32767
8 bytes
+/- 1.79769313486232 E 308
A Long
4 bytes
+/- 4.94065645841247 E-324
Currency
B +/- 2,147,483,648
Single
8 bytes
+/- 922,337,203,685,477.5808
A 4 bytes
+/- 3.402823 E 38
String & String*n
Variant
S
+/- 1.401298 E-45 Any data type
Global, Const, Static Null
E
42
D Programming: Scope and Lifetime
A Scope
Where is the variable, and
Form
Button1
which procedures can
T access it?
Lifetime
Button2
B
Sub Button1_Click()
Dim i1 As Integer
i1 = 3
A Different procedures,
different variables.
End Sub
Sub Button2_Click()
E is clicked.
43
D Programming: Global Variables
A Wider scope and lifetime
Created at a higher level
Form
Button1
T Form
Public module
Button2
A
Accessible to any procedure Form--Module Code
in that form or module. Dim i2 As Integer
Declare it Global to make it
B
Sub Button1_Click()
available to any procedure. i2 = 20
End Sub
E the value.
What if user clicks buttons in a different order?
44
D Programming: Computations
A Standard Math
+ - * /
String
& Concatenation
T \ Integer divide
^ Exponentiation
Left, Right, Mid
Trim, LTrim, RTrim
A
(2^3 = 2*2*2 = 8) String
Mod Chr, Asc
(15 Mod 4 = 3) (12 + 3 = 15) LCase, UCase
B “Frank” & “Rose” “FrankRose”
InStr
Len
A Left(“Jackson”,5) “Jacks”
Trim(“ Maria “) “Maria”
StrComp
Format
S Len(“Ramanujan”) 9
String(5,”a”) “aaaaa”
E InStr(“8764 Main”,” “) 5
45
D Programming: Standard Functions
A Numeric
T =30
?
Exp, Log x = loge (e )
x
92
Atn, Cos, Sin, Tan Trigonometric functions
A
Sqr
Abs
2 = 1.414
Abs(-35) 35
B
Sgn
Int, Fix
Sgn(-35) -1
Int(17.893) 17
A
Rnd, Randomize Rnd() 0.198474
S
E
46
D Programming:
Standard Functions: Date/Time
A Date, Now, Time
T DateAdd, DateDiff
“y”, “m”, “q” . . .
02/19/04 03/21/04
A
Firstweekday
1=Sunday,. . .
today DateDue
S
E
47
D Programming:
Standard Functions: Variant
A Variant
T
IsDate
IsNumeric
A
VarType
IsEmpty
B IsNull
A
S
E
48
D Programming: Debug
A Stop Immediate Window
T
Ctrl-Break
F5: Go
? or Print
Any assignment
A
F8: Step through
S-F8: Step over
Any code
B Breakpoints
A
S
E
49
D Programming:
Output: Message Box
A MsgBox
Message
Icons
vbCritical Stop sign
T
Type vbQuestion Question mark
Title vbExclamation Warning
Types: Use Constants
A
vbInformation Circle i
vbOKOnly vbOKCancel
Responses
vbAbortRetryIgnore
B vbYesNoCancel vbOK vbCancel
vbYesNo vbRetryCancel vbAbort vbRetry
Defaults vbIgnore
A vbDefaultButton1
vbDefaultButton2
vbYes vbNo
S vbDefaultButton3
50
D Programming:
Input: InputBox
A InputBox
Prompt
Returns text or Variant
Cancel = zero string ““
T
Title
Default
Positions
Twips
A X-Pos, Y-Pos
Prompt
Twentieth of inch point
72 points
blank lines.
A Dim str As String
S str = InputBox(
"Enter your name:",
"Sample Input", ,
E 5000, 5000)
51
D Programming: Conditions
A If Conditions
T If (Condition) Then
statements for true
<, <=, >, >=, =, <>
And, Or, Not, Xor
A Else
statements for false
Eqv, Imp (logic)
If (Condition1) Then
B
End If
IIF (Cond., True, False) statements for true
Select Case (expr) Else
A Case value
statements
statements for false
If (Condition2) Then
S Case value2
Case Else
statements for true
End If
E End Select
End If
52
D Message Box
Programming
Select Example
A Could use repeated If
statements
B
If (response == vbYes) Then Select Case response
‘ statements for Yes Case vbYes
Else ‘ statements for Yes
S Else
‘statements for Cancel
Case vbCancel
‘ statements for Cancel
End If End Case
E End If
53
D Programming: Loops
A Do
Initialize value
Statements
T For … Next
For Each
Change value
Test condition
A Do Until (x > 10) Do While (x <= 10)
B ‘ Statements
x=x+1
‘ Statements
x=x+1
A Loop Loop
Do For x = 1 to 10
S ‘ Statements ‘ Statements
E
x=x+1 Next x
Loop Until (x > 10)
54
D Programming: Loops Again
A Do For/Each (objects)
T Do {While | Until}
Exit Do (optional)
For Each element In group
[Exit For] (optional)
B Do
Loop {While | Until}
With object
End With
For/Next
A For counter = start To end
Step increment
S Exit For (optional)
Next counter
E
55
D Programming
Subroutines and Functions
A Sub name (var1 As . . ., var2, . . .)
End Sub
A End Function
Variables are passed by reference
A …
StatusMessage “Verifying access.”
…
B End main program
A
Sub StatusMessage (Msg As String)
‘ Display Msg, location, color
End Sub
S
E
57
D Programming: Parameter Types
A Main
j=3
T DoSum j
… ‘ j is now equal to 8 By Reference
Changes to data in the
A Subroutine DoSum (j2 As Integer)
j2 = 8
subroutine are passed back.
End Sub
B Main
A j=3
DoSum j
… ‘ j is still equal to 3 By Value
S Subroutine DoSum (ByVal j2 As Integer)
Creates a copy of the
variable, so changes are
j2 = 8
E End Sub
not returned.
58
D Programming
Arrays and User Types
A Arrays User defined types
T Dim array(sub, . . .) As
type
Type Tname
ename1 As type
A Dim iSorts(10) As Integer ename2 As type
End Type
Specifying bounds:
A
NPer (rate, pmt, pv, fv, due) DDB (cost, salv, life, period)
Pmt (rate, nper, pv, fv,due) SLN (cost, salvage, life)
PPmt (rate, per, nper, pv, fv, SYD (cost, salv., life, period)
B
due)
Rate (nper, pmt, pv, fv, due,
guess)
60
D Programming: Text File Input/Output
A Open filename As # file# ChDir, ChDirve
T
Close # file#, Reset
Print #,Put, Write
Dir
Kill, (re)Name
A
Spc, Tab
Get, Input #, Line Input #
Lock, Unlock
CurDir, MkDir, RmDir
B
EOF, LOF
Seek # file#, position
A
S
E
61
D OLE: Object Linking & Embedding
A CreateObject (class) Example
T “appname . objecttype”
GetObject (file, class)
Dim obj As Object
set obj =
B
obj.Insert “text”
defined by the software that
obj.SaveAs “file”
exports the object.
A
S
E
62
D DDE: Dynamic Data Exchange
A Shell Application must be running
T
DDEInitiate
DDEExecute
Start a conversation/topic
Issue a command
A DDEPoke, DDE Send
Send data
Place data
B DDE, DDERequest
Request data
Get data
S
E
63