0% found this document useful (0 votes)
150 views52 pages

Database Management Systems

DBNote04

Uploaded by

M. Zainal Abidin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views52 pages

Database Management Systems

DBNote04

Uploaded by

M. Zainal Abidin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 52

Database Management Systems

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?

B  We need a query system with more structure


 We need a standardized system so users and
A developers can learn one method that works on any
(most) systems.
S  Query By Example (QBE)
 SQL
E
2
D Four Questions to Create a Query
A
 What output do you want to see?
T  What do you already know (or what constraints are
given)?
A  What tables are involved?

B  How are the tables joined together?

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

A with a list price greater than


$10.
who bought something between
4/1/04 and 5/31/04.
 List all dogs who are male  List the first name and phone of
B and registered or who were
born before 6/1/04 and have
every customer who bought
something between 4/1/04 and
white in their color.
A  What is the average sale
price of all animals?
5/31/04.
 List the last name and phone of
anyone who bought a registered
S  What is the total cost we paid
for all animals?
white cat between 6/1/04 and
12/31/04.

E  List the top 10 customers


and total amount they spent.
 Which employee has sold the
most items?

6
Query04_01

D Query By Example & SQL


A What tables? SELECTAnimalID, Category, Breed, Color

T Animal
FROM Animal
WHERE (Color LIKE ‘%Yellow%’);

A AnimalID
Name
Category
What to see?

B Breed
DateBorn
Gender
What conditions?

A Field AnimalID Categor


y
Breed Color

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?

B WHERE criteria What are the constraints?

A
S
E
8
D ORDER BY
A SELECT
FROM
JOIN
columns
tables
join columns
T WHERE
ORDER BY
conditions
columns (ASC DESC)

A Animal SELECT Name, Category, Breed Name Category Breed


AnimalID FROM Animal Cathy Bird African Grey

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

A Field AnimalID Categor


y
DateBorn Color

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

A And: Both must be true.


Or: Either one is true.
b = -1
c=2
T Not: Reverse the value.
(a > 4) And (b < 0)
A F
F
T

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

T Parentheses indicate that an


operation should be performed first.
b = -1
With no parentheses, operations are c=2
A performed left-to-right.
( (a > 4) AND (b < 0) ) OR (c > 1)
B F
F
T T
T
A T

(a > 4) AND ( (b < 0) OR (c > 1) )


S Always use parentheses,
so other people can read
F T T
F T
E and understand your query. F

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."

T Animal SELECT AnimalID, Category, Registered, Color


A AnimalID
Name
Category
FROM Animal
WHERE (Category=‘Cat’) AND
NOT ((Registered is NOT NULL)
B Breed
DateBorn
Gender
OR (Color LIKE ‘%Red%’)).

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

A Field AnimalID Categor


y
Gender Registere
d
DateBorn Color

Table Animal Animal Animal Animal Animal Animal

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’

B Pattern match one


Pattern match any
License LIKE ‘A_ _82_’
Name LIKE ‘J%’

A Dates SaleDate BETWEEN ’15-Aug-2004’


AND ’31-Aug-2004’

S
Missing Data City IS NULL
Negation Name IS NOT NULL

E Sets Category IN (‘Cat’, ‘Dog’, ‘Hamster’)

17
D Simple Computations
A SaleItem(OrderID, ItemID, SalePrice, Quantity)

T Select OrderID, ItemID, SalePrice, Quantity,


SalePrice*Quantity As Extended

A From SaleItem;
OrderID ItemID Price Quantity Extended

B 151
151
9764
7653
19.50
8.35
2
3
39.00
25.05

A 151 8673 6.89 2 13.78

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

What is the average sale price of all animals?

25
Query04_05

D Computations (Math Operators)


A OrderItem

T PONumber SELECT Sum(Quantity*Cost) AS OrderTotal


ItemID FROM OrderItem
Quantity WHERE (PONumber=22);
Cost

A Field PONumber OrderTotal: Quantity*Cost

B
Table OrderItem OrderItem
Total
Sort
OrderTotal

A Criteria
Or
=22
1798.28

S  What is the total value of the order for PONumber 22?

E  Use any common math operators on numeric data.


 Operate on data in one row at a time.

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

Field AnimalID Category

A
Table Animal Animal
Total Count Where
Sort

S Criteria
Or
‘Cat’

E How many cats are in the Animal list?

28
Query04_07

D Groups and Subtotals


A Animal
SELECT
FROM
GROUP BY
Category, Count(AnimalID) AS CountOfAnimalID
Animal
Category

T AnimalID
Name
Category
ORDER BY Count(AnimalID) DESC;

A
Breed
DateBorn Category CountOfAnimalID
Gender Dog 100

B Field Category AnimalID Cat 47


Table Animal Animal
Bird 15
Fish 14

A
Total Group Count
By Reptile 6
Mammal 6
Sort Descendin
Spider 3
S
g
Criteria
OrCount the number of animals in each category.

E  You could type in each WHERE clause, but that is slow.


 And you would have to know all of the Category values.

29
Query04_08

D Conditions on Totals (Having)


A Animal
SELECT Category, Count(AnimalID) AS CountOfAnimalID

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

D Where (Detail) v Having (Group)


A Animal SELECT Category, Count(AnimalID) AS CountOfAnimalID
FROM Animal

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

D Multiple Tables (Intro & Distinct)


A Sale SELECT DISTINCT CustomerID
CustomerI D
6
8

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

T WHERE (SaleDate Between ’01-Apr-2004’ And ’31-May-2004’)


ORDER BY Customer.LastName;

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

A SQL 92 syntax (Access and SQL Server)


FROM table1, table2
B WHERE table1.column = table2.column
SQL 89 syntax (Oracle)
A
FROM table1, table2
S JOIN 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

S JOIN Table1.ColB = Table2.ColB


Table2.ColA = Table3.ColA

E
35
Query04_12

D Multiple Tables (Many)


SELECT DISTINCTROW Customer.LastName, Customer.Phone

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

T WHERE ((Animal.Category=‘Cat’) AND (Animal.Registered Is Not Null)


AND (Color Like ‘%White%’) AND (SaleDate Between ’01-Jun-2004’ And ’31-Dec-2004’));

A
Animal SaleAnimal Sale Customer
AnimalID SaleID SaleID CustomerID
Name AnimalID SaleDate Phone

B
Category SalePrice EmployeeID FirstName
Breed CustomerID LastName

Field LastName Phone Categor Registere Color SaleDate

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

T from customer inner join sale on customer.customerid = sale.customerid


inner join saleanimal on sale.saleid = saleanimal.saleid

A inner join animal on saleanimal.animalid = animal.animalid


where (category = 'Cat') and (Registered is not null) and (color like '%White
B %')
AND (saledate between '01-Jun-2004' and '31-Dec-2004')

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

B  Sale Date: Sale


 Find connector tables.

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

T  Drag and drop


 From one side to many side
 FROM (Table1
 INNER JOIN Table2

A  Avoid multiple ties between  ON T1.ColA = T2.ColB )


tables  INNER JOIN Table3
 SQL  ON T3.ColC = T3.ColD

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

T automatically determine JOINs.


 JOINS might loop. AnimalOrder

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

A SELECT Supplier.SID, Supplier.CityID, City.City, Employee.EID,


Employee.LastName, Employee.CityID, City2.City
FROM (City INNER JOIN Supplier ON City.CityID = Supplier.CityID) INNER JOIN

B ((City AS City2 INNER JOIN Employee ON City2.CityID = Employee.CityID)


INNER JOIN AnimalOrder ON Employee.EmployeeID = AnimalOrder.EmployeeID)
ON Supplier.SupplierID = AnimalOrder.SupplierID;

A SID Supplier.CityID City.City EID LastName Employee.CityID City2.City


4 7972 Middlesboro 5 James 7083 Orlando

S 2
4
9
10896
7972
10740
Springfield
Middlesboro
Columbia
1
3
8
Reeves
Reasoner
Carpenter
9201
8313
10592
Lincoln
Springfield
Philadelphia

E 5 10893 Smyrna 3 Reasoner 8313 Springfield

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  Any SELECT statement


 Can use the View within
FROM Animal
WHERE (Category = ‘Cat’) AND

B other SQL queries. (Today - DateBorn < 180);

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)

B  To be updateable, a view must focus on one primary


table. (OrderItem)
A  Goal is to change data in only one table. (OrderItem)
 Data can be displayed from other tables. (Item)

S  Never include or attempt to change primary keys from


more than one table. (Item.ItemID)

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

S If you attempt to change the Item.ItemID in the OrderLineView:


You will simply change the primary key value in the Item table.
E It will not add a new row to the OrderItem table.

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],

B CONSTRAINT pkname PRIMARY KEY (column, …),


CONSTRAINT fkname FOREIGN KEY (column)
REFERENCES existing_table (key_column)
A ON DELETE CASCASDE
)
S See also:
ALTER TABLE

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, … )

A INSERT INTO newtable (column1, column2, …)


SELECT …

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

You might also like