Professional Documents
Culture Documents
DBNote 04
DBNote 04
Chapter 4
Queries
Jerry Post
Copyright © 2003
1
D Why do we Need Queries
A
Natural languages (English) are too vague
T With complex questions, it can be hard to verify that the
question was interpreted correctly, and that the answer we
A received is truly correct.
Consider the question: Who are our best customers?
A
S
E
3
D Tables Animal
A
AnimalOrder Animal A nimalID
OrderItem N ame SaleAnimal
OrderID * * *
OrderID C ategory
Orde rDate * SaleID
AnimalID Breed
* R eceiveD ate AnimalID
Cost Breed * D ateBorn
T
SupplierID * SalePrice
Gender
ShippingCost Category
R egistered
EmployeeID * Breed
C olor
Employee
ListPrice
Supplier C ustomer
EmployeeID Photo
A SupplierID
Name
ContactName
Phone
C ity
C ityID
ZipCode
LastName
FirstName
Phone
Address
Sale
SaleID
SaleDate
C ustomerID
Phone
FirstName
LastName
B
Address ZipCode * Address
C ity Employe eID
ZipCode * CityID ZipCode
State CustomerID * *
CityID TaxPayerID C ityID
AreaCode SalesTax
* DateHired Category
Population1990
DateReleased
Population1980 Category
A
C oun try Registration
SaleItem
Latitude
*
Longitude Merchandise SaleID
OrderItem
ItemID
* ItemID
PONumber * Quantity
S
Merchandise * Description
Orde r ItemID SalePrice
QuantityO nHand
Quantity
PONumber ListPrice
Cost
Orde rDate Category
R eceiveD ate *
E
SupplierID
* EmployeeID
ShippingCost *
4
D Organization
A
Single table
T Constraints
A Computations
Groups/Subtotals
B Multiple Tables
A
S
E
5
D Sample Questions
A List all animals with yellow in
their color.
List all dogs with yellow in
How many cats are in the
animal list?
Count the number of animals in
T their color born after 6/1/04.
List all merchandise for cats
each category.
List the CustomerID of everyone
6
Query04_01
T Animal
FROM Animal
WHERE (Color LIKE ‘%Yellow%’);
A AnimalID
Name
Category
What to see?
B Breed
DateBorn
Gender
What conditions?
S Table
Sort
Animal Animal Animal Animal
E
Criteria Like ‘%Yellow%’
Or
List all animals with yellow in their color
7
D Basic SQL SELECT
A
T SELECT columns
FROM tables
What do you want to see?
What tables are involved?
A JOIN conditions How are the tables joined?
A
S
E
8
D ORDER BY
A SELECT
FROM
JOIN
columns
tables
join columns
T WHERE
ORDER BY
conditions
columns (ASC DESC)
B Name
Category
Breed
ORDER BY Category, Breed; Bird
Debbie Bird
Canary
Cockatiel
Bird Cockatiel
A DateBorn
Gender
Terry Bird
Bird
Lovebird
Other
Field Name Category Breed Charles Bird Parakeet
S Table
Sort
Animal Animal
Ascending
Animal
Ascending
Curtis
Ruby
Bird
Bird
Parakeet
Parakeet
Sandy Bird Parrot
E Criteria
Or
Hoyt Bird
Bird
Parrot
Parrot
9
D DISTINCT
A SELECT Category
FROM Animal;
SELECT DISTINCT Category
FROM Animal;
T Category
Fish
Category
Bird
Dog
A Fish
Cat
Cat
Dog
Fish
B Cat
Dog
Fish
Mammal
Reptile
Spider
A Dog
Dog
Dog
S Fish
Cat
E Dog
...
10
Query04_02
D Constraints: And
A
T Animal
SELECTAnimalID, Category, DateBorn
A AnimalID
Name
Category
FROM Animal
WHERE ((Category=‘Dog’)
AND (Color Like ‘%Yellow%’)
B
Breed
DateBorn AND (DateBorn>’01-Jun-2004’));
Gender
S
Table Animal Animal Animal Animal
Sort
Criteria ‘Dog’ >’01-Jun-2004’ Like ‘%Yellow%’
E Or
List all dogs with yellow in their color born after 6/1/04.
11
D Boolean Algebra a=3
B (a > 4) Or (b < 0)
F T
A T
S NOT (b < 0)
T
E F
12
D Boolean Algebra
A The result is affected by the order
of the operations. a=3
13
D DeMorgan’s Law Example
A Customer: "I want to look at a cat, but I don’t want any cats that are
registered or that have red in their color."
A Field
Table
AnimalID
Animal
Category
Animal
Registered
Animal
Color
Animal
S
Sort
Criteria ‘Cat’ Is Null Not Like ‘%Red%’
Or
E
14
D DeMorgan’s Law
A Negation of clauses
Not (A And B) becomes
T Not A Or Not B
Not (A Or B) becomes Registered=ASCF
Not A And Not B Color=Black
A NOT ((Registered is NOT NULL) OR (Color LIKE ‘%Red%’))
B T
not
or
T
F
A F
(Registered is NULL) AND NOT (Color LIKE ‘%Red%’)
S F
and
not
T
F
E F
15
Query04_03
D Conditions: AND, OR
SELECT AnimalID, Category, Gender, Registered, DateBorn, Color
A FROM Animal
WHERE (( Category=‘Dog’) AND
( ( (Gender=‘Male’) AND (Registered Is Not Null) ) OR
T Animal
( (DateBorn<’01-Jun-2004’) AND (Color Like ‘%White%’) ) ) );
A AnimalID
Name
Category
B Breed
DateBorn
Gender
S Sort
Criteria ‘Dog’ ‘Male’ Is Not Null
E Or
List all dogs who are‘Dog’ < ’01-Jun-
male and registered or who were
have white in their color.
born before Like
2004’
‘%White%’
6/1/2004 and
16
D Useful Where Conditions
A Comparisons Examples
T Operators
Numbers
<, =, >, <>, BETWEEN, LIKE, IN
AccountBalance > 200
A Text
Simple Name > ‘Jones’
S
Missing Data City IS NULL
Negation Name IS NOT NULL
17
D Simple Computations
A SaleItem(OrderID, ItemID, SalePrice, Quantity)
A From SaleItem;
OrderID ItemID Price Quantity Extended
B 151
151
9764
7653
19.50
8.35
2
3
39.00
25.05
S
Basic computations (+ - * /) can be performed on numeric data.
E The new display column should be given a meaningful name.
24
Query04_04
D Computations: Aggregation--Avg
A
SELECT Avg(SalePrice) AS AvgOfSalePrice
T FROM SaleAnimal;
SaleAnimal Sum
A SaleID
AnimalID
Avg
Min
SalePrice
B Max
Count
StDev or StdDev
Field SalePrice
A Table
Total
SaleAnimal
Avg
Var
S Sort
Criteria
E
Or
25
Query04_05
B
Table OrderItem OrderItem
Total
Sort
OrderTotal
A Criteria
Or
=22
1798.28
26
D SQL Differences
A
T
A
B
A
S
E
27
Query04_06
D Subtotals (Where)
A
T Animal
AnimalID
Name
SELECT Count(AnimalID) AS CountOfAnimalID
A Category
Breed
DateBorn
FROM Animal
WHERE (Category = ‘Cat’);
B
Gender
A
Table Animal Animal
Total Count Where
Sort
S Criteria
Or
‘Cat’
28
Query04_07
T AnimalID
Name
Category
ORDER BY Count(AnimalID) DESC;
A
Breed
DateBorn Category CountOfAnimalID
Gender Dog 100
A
Total Group Count
By Reptile 6
Mammal 6
Sort Descendin
Spider 3
S
g
Criteria
OrCount the number of animals in each category.
29
Query04_08
T AnimalID
Name
Category
FROM
GROUP BY
HAVING
Animal
Category
Count(AnimalID) > 10
Breed
A DateBorn
Gender
ORDER BY Count(AnimalID) DESC;
B
Field Category AnimalID
Table Animal Animal
Category CountOfAnimalID
Dog 100
Total Group Count
A Sort
By
Descending
Cat
Bird
Fish
47
15
14
S
Criteria >10
Or
E Count number of Animals in each Category, but only list them if more than 10.
30
Query04_09
T
AnimalID
Name WHERE DateBorn > ’01-Jun-2004’
Category GROUP BY Category
Breed HAVING Count(AnimalID) > 10
A DateBorn
Gender
ORDER BY Count(AnimalID) DESC;
B Field
Table
Category
Animal
AnimalID
Animal
DateBorn
Animal
A
Total Group Count Where Category CountOfAnimalID
By
Dog 30
Sort Descendin Cat 18
S
g
Criteria >10 >’01-Jun-
2004’
E Or
Count Animals born after 6/1/2004 in each Category, but only list Category if more
than 10.
31
Query04_10
T SaleID
SaleDate
EmployeeID
FROM Sale
WHERE (SaleDate Between ’01-Apr-2004’
And ’31-May-2004’)
14
19
22
A
CustomerID ORDER BY CustomerID; 24
SalesTax 28
36
37
B Field
Table
CustomerI
D
Sale
SaleDate
Sale
38
39
42
A Sort
Criteria
Ascending
Between ’01-Apr-2004’
50
57
58
S
And ’31-May-2004’ 63
74
Or
80
90
E List the CustomerID of everyone who bought something between 01-Apr-2004 and
31-May-2004.
32
Query04_11
D Joining Tables
A SELECT DISTINCT Sale.CustomerID, Customer.LastName
FROM Customer
INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID
A
Sale Customer
SaleID CustomerID
SaleDate Phone CustomerID LastName
22 Adkins
B
EmployeeID FirstName
CustomerID LastName 57 Carter
38 Franklin
42 Froedge
Field CustomerI LastName SaleDate
A
63 Grimes
D 74 Hinton
Table Sale Customer Sale 36 Holland
6 Hopkins
S
Sort Ascendin
50 Lee
g 58 McCain
Criteria Between ’01-Apr-2004’ …
E
And ’31-May-2004’
List LastNames of Customers who bought between 4/1/2004 and
Or
5/31/2004.
33
D SQL JOIN
A FROM table1
INNER JOIN table2
T ON table1.column = table2.column
E Informal syntax
34
D Syntax for Three Tables
A SQL ‘92 syntax to join three tables
T
FROM Table1
INNER JOIN (Table2 INNER JOIN Table3
A ON Table2.ColA = Table3.ColA)
ON Table1.ColB = Table2.ColB
B
A Easier notation, but not correct syntax
FROM Table1, Table2, Table3
E
35
Query04_12
A FROM Customer INNER JOIN (Sale INNER JOIN (Animal INNER JOIN SaleAnimal
ON Animal.AnimalID = SaleAnimal.AnimalID) ON Sale.SaleID = SaleAnimal.SaleID)
ON Customer.CustomerID = Sale.CustomerID
A
Animal SaleAnimal Sale Customer
AnimalID SaleID SaleID CustomerID
Name AnimalID SaleDate Phone
B
Category SalePrice EmployeeID FirstName
Breed CustomerID LastName
A
Table Customer Customer
y
Animal
d
Animal Animal Sale
S
Sort Ascendin
g
Criteria ‘Cat’ Is Not Null Like ‘%White%’ Between ’01-Jun-2004’
E
And ’31-Dec-2004’
List the Last Name and Phone of anyone who bought a registered
Or White cat between 6/1/2004 and 12/31/2004.
36
D Oracle
A select lastname, phone
A ;
S
E
37
D Building a Query
A List the Last Name and Phone of anyone who bought a registered
White cat between 6/1/04 and 12/31/04.
T
Identify the tables involved.
Look at the columns you want to see.
LastName, Phone: Customer
A Look at the columns used in the constraints.
Registered, Color, Category: Animal
A
To connect Animal to Sale: SaleAnimal
Select the desired columns and test the query.
S
Enter the constraints.
Set Order By columns.
E
Add Group By columns.
Add summary computations to the SELECT statement.
38
D Joining Tables (Hints)
A Build Relationships First Multiple Tables
B FROM Table1
INNER JOIN Table2
Shorter Notation
FROM T1, T2, T3
A ON Table1.ColA = Table2.ColB
Join columns are often keys, but
JOIN T1.ColA = T2.ColB
T1.ColC = T3.ColD
they can be any columns--as Shorter Notation is not correct
S long as the domains (types of
data) match.
syntax, but it is easier to write.
E
39
D Tables with Multiple Joins
A Potential problem with three or more tables.
Access uses predefined relationships to
A
OrderID
Most queries will not work with loops. OrderDate
¥ ReceiveDate
SupplierID
ShippingCost
¥
B
EmployeeID
A query with these four tables
with four JOINS would only return Supplier
1 1
Employee
SupplierID
rows where the Employee had the EmployeeID
A
Name
LastName
ContactName
same ZipCode as the Supplier. If Phone
City
FirstName
Phone
Address
you only need the Supplier city, ZipCode CityID
Address
ZipCode
S
CityID
just delete the JOIN between ZipCode
City
CityID
TaxPayerID
Employee and ZipCode. If you State
AreaCode
DateHired
DateReleased
want both cities, add the ZipCode Population1990
E
Population1980
table again as a fifth table. Country
Latitude
Longitude
40
D Table Alias
A CityID
City Supplier
SupplierID
AnimalOrder
OrderDate
Employee
EmployeeID
City2
CityID
ZipCode Address SupplierID LastName ZipCode
T City
State
ZipCode
CityID
ShippingCost
EmployeeID
ZipCode
CityID
City
State
S 2
4
9
10896
7972
10740
Springfield
Middlesboro
Columbia
1
3
8
Reeves
Reasoner
Carpenter
9201
8313
10592
Lincoln
Springfield
Philadelphia
41
D Saved Query: Create View
A Save a query
T
CREATE VIEW Kittens AS
Faster: only enter once
Faster: only analyze once SELECT *
A SELECT Avg(ListPrice)
S FROM Kittens
WHERE (Color LIKE ‘%Black%’);
E
42
D Updateable Views
A
OrderItem(OrderID, ItemID, Quantity) Item(ItemID, Description)
T
A OrderLine(OrderID, ItemID, Description, Quantity)
E
43
D Non Updateable View
A OrderItem(OrderID, ItemID, Quantity)
121 57 3
Item(ItemID, Description)
57 Cat food
T 121
122
82
57
2
1
58
59
Dog food
Bird food
A
B
OrderLine(OrderID, Item.ItemID, Description, Quantity)
121 57 Cat food 3
A
121 82 Bird feeder 2
122 57 Cat food 1
32
44
D SQL Syntax: ALTER TABLE
A ALTER TABLE table
T ADD COLUMN column datatype (size)
DROP COLUMN column
A
B
A
S See also:
CREATE TABLE
E DROP TABLE
45
D SQL Syntax: COMMIT
A COMMIT WORK
T
A
B
A
S See also: ROLLBACK
E
46
D SQL Syntax: CREATE INDEX
A CREATE [UNIQUE] INDEX index
T ON table (column1, column2, … )
WITH {PRIMARY | DISALLOW NULL | IGNORE NULL}
A
B
A
S See also: CREATE TABLE
E
47
D SQL Syntax: CREATE TABLE
A CREATE TABLE table
T (
column1 datatype (size) [NOT NULL] [index1] ,
A column2
…,
datatype (size) [NOT NULL] [index2],
E DROP TABLE
48
D SQL Syntax: CREATE VIEW
A CREATE VIEW viewname AS
T SELECT …
A
B
A
S See also: SELECT
E
49
D SQL Syntax: DELETE
A DELETE
T FROM table
WHERE condition
A
B
A
S See also: DROP
E
50
D SQL Syntax: DROP
A DROP INDEX index ON table
T DROP TABLE
A DROP VIEW
B
A
S See also: DELETE
E
51
D SQL Syntax: INSERT
A INSERT INTO table (column1, column2, …)
T VALUES (value1, value2, … )
B
A
S See also: SELECT
E
52
D SQL Syntax: GRANT
A GRANT privilege privileges
T ON object
TO user | PUBLIC
ALL, ALTER, DELETE, INDEX,
INSERT, SELECT, UPDATE
A
B
A
S See also: REVOKE
E
53
D SQL Syntax: REVOKE
A REVOKE privilege privileges
T ON object
FROM user | PUBLIC
ALL, ALTER, DELETE, INDEX,
INSERT, SELECT, UPDATE
A
B
A
S See also: GRANT
E
54
D SQL Syntax: ROLLBACK
A SAVEPOINT savepoint {optional}
T ROLLBACK WORK
A TO savepoint
B
A
S See also: COMMIT
E
55
D SQL Syntax: 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)
ORDER BY table.column
B { UNION, INTERSECT, EXCEPT … }
A
S
E
56
D SQL Syntax: SELECT INTO
A SELECT column1, column2, …
T INTO newtable
FROM tables
A WHERE condition
B
A
S See also: SELECT
E
57
D SQL Syntax: UPDATE
A UPDATE TABLE table
T SET column1 = value1, column2 = value2, …
WHERE condition
A
B
A
S See also: DELETE
E
58