Jerry Post Copyright © 2001 1 Database Management Systems Chapter 4 Queries.

Post on 02-Jan-2016

214 views 1 download

Transcript of Jerry Post Copyright © 2001 1 Database Management Systems Chapter 4 Queries.

1

Jerry PostCopyright © 2001

Database Management Database Management SystemsSystems

Chapter 4

Queries

2

DDAATTAABBAASSEE

Why do we Need Queries

Natural languages (English) are too vagueWith complex questions, it can be hard to verify that the

question was interpreted correctly, and that the answer we received is truly correct.

Consider the question: Who are our best customers?

We need a query system with more structure We need a standardized system so users and

developers can learn one method that works on any (most) systems.Query By Example (QBE)SQL

3

DDAATTAABBAASSEE

Four Questions to Create a Query

What output do you want to see? What do you already know (or what constraints are

given)? What tables are involved? How are the tables joined together?

4

DDAATTAABBAASSEE

Tables

SupplierIDNameContactNamePhoneAddressZipCodeCityID

Supplier

PONumberOrderDateReceiveDateSupplierIDEmployeeIDShippingCost

MerchandiseOrder

OrderIDOrderDateReceiveDateSupplierIDShippingCostEmployeeID

AnimalOrder

OrderIDAnimalIDCost

AnimalOrderItem

CityIDZipCodeCityStateAreaCodePopulation1990Population1980CountryLatitudeLongitude

City

EmployeeIDLastNameFirstNamePhoneAddressZipCodeCityIDTaxPayerIDDateHiredDateReleased

Employee

PONumberItemIDQuantityCost

OrderItem

CategoryRegistration

Category

CategoryBreed

Breed

AnimalIDNameCategoryBreedDateBornGenderRegisteredColorListPricePhoto

Animal

SaleIDSaleDateEmployeeIDCustomerIDSalesTax

Sale

SaleIDItemIDQuantitySalePrice

SaleItem

ItemIDDescriptionQuantityOnHandListPriceCategory

Merchandise

SaleIDAnimalIDSalePrice

SaleAnimal

CustomerIDPhoneFirstNameLastNameAddressZipCodeCityID

Customer

*

*

*

*

*

*

*

*

*

**

*

*

*

**

*

**

*

5

DDAATTAABBAASSEE

Organization

Single table Constraints Computations Groups/Subtotals Multiple Tables

6

DDAATTAABBAASSEE

Sample Questions List all animals with yellow in

their color. (Query04 _01) List all dogs with yellow in their

color born after 6/1/01. (Query04 _02)

List all merchandise for cats with a list price greater than $10.

List all dogs who are male and registered or who were born before 6/1/01 and have white in their color. (Query04 _03)

What is the average sale price of all animals? (Query04 _04)

What is the total cost we paid for all animals? (Query04 _05)

List the top 10 customers and total amount they spent.

How many cats are in the animal list? (Query04 _06)

Count the number of animals in each category. (Query04 _07)

List the CustomerID of everyone who bought something between 4/1/01 and 5/31/01.

List the first name and phone of every customer who bought something between 4/1/01 and 5/31/01.

List the last name and phone of anyone who bought a registered white cat between 6/1/01 and 12/31/01.

Which employee has sold the most items?

7

DDAATTAABBAASSEE

Query By Example & SQL

List all animals with yellow in their color.

SELECTAnimalID, Category, Breed, ColorFROM AnimalWHERE (Color LIKE “*yellow*”);

What tables?

What to see?

What conditions?

Query04_01

8

DDAATTAABBAASSEE

Basic SQL SELECT

SELECT columns What do you want to see?

FROM tables What tables are involved?

JOIN conditions How are the tables joined?

WHERE criteria What are the constraints?

9

DDAATTAABBAASSEE

ORDER BYSELECT columnsFROM tablesJOIN join columnsWHERE conditionsORDER BY columns (ASC DESC)

SELECT Name, Category, BreedFROM AnimalORDER BY Category, Breed;

Name Category BreedCathy Bird African Grey

Bird CanaryDebbie Bird Cockatiel

Bird CockatielTerry Bird Lovebird

Bird OtherCharles Bird ParakeetCurtis Bird ParakeetRuby Bird ParakeetSandy Bird ParrotHoyt Bird Parrot

Bird Parrot

10

DDAATTAABBAASSEE

DISTINCTSELECT Category FROM Animal;

CategoryFishDogFishCatCatDogFishDogDogDogFishCatDog. . .

SELECT DISTINCT Category FROM Animal;

CategoryBirdCatDogFishMammalReptileSpider

11

DDAATTAABBAASSEE

Constraints: And

List all dogs with yellow in their color born after 6/1/01.

SELECTAnimalID, Category, DateBornFROM AnimalWHERE ((Category="Dog") AND (Color Like "*Yellow*") AND (DateBorn>#6/1/2001#));

Query04_02

12

DDAATTAABBAASSEE

Conditions: AND, OR

List all dogs who are male and registered or who were born before 6/1/2001 and have white in their color.

SELECT AnimalID, Category, Gender, Registered, DateBorn, ColorFROM AnimalWHERE (( Category="Dog") AND

( ( (Gender="Male") AND (Registered Is Not Null) ) OR ( (DateBorn<#6/1/2001#) AND (Color Like "*White*") ) ) );

Query04_03

13

DDAATTAABBAASSEE

Boolean AlgebraAnd: Both must be true.Or: Either one is true.Not: Reverse the value.

a = 3

b = -1

c = 2

(a > 4) Or (b < 0)

F TF

(a > 4) And (b < 0)

F TT

NOT (b < 0)

TF

14

DDAATTAABBAASSEE

Boolean Algebra

F TF

T

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

F T

FF

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

T

a = 3

b = -1

c = 2

The result is affected by the order of the operations.Parentheses indicate that anoperation should be performed first.With no parentheses, operations areperformed left-to-right.

Always use parentheses,so other people can readand understand your query.

15

DDAATTAABBAASSEE

DeMorgan’s Law ExampleCustomer: "I want to look at a cat, but I don’t want any cats that are

registered or that have red in their color."

SQL: SELECT . . . WHERE (Category=“cat”) ANDNOT ((Registered is NOT NULL) or (Color LIKE “*red*”)).

QBE:

16

DDAATTAABBAASSEE

DeMorgan’s Law Negation of clauses

Not (A And B) becomes Not A Or Not B

Not (A Or B) becomes Not A And Not B

T F

TF

NOT ((Registered is NOT NULL) OR (Color LIKE “*red*”))

Registered=ASCFColor=Black

(Registered is NULL) AND NOT (Color LIKE “*red*”)

FT

F

or

not

and

Fnot

17

DDAATTAABBAASSEE

Useful Where Conditions

18

DDAATTAABBAASSEE

Oracle Views

19

DDAATTAABBAASSEE

Oracle Views and SQL

CREATE VIEW Pets.Example AS

SELECT Pets.Animal.AnimalID,

Pets.Animal.Breed,

Pets.Animal.Category,

Pets.Animal.Color

FROM Pets.Animal

WHERE (Pets.Animal.Color LIKE ‘%Yellow%’)

SQL version is created by the Oracle View Wizard.The CREATE VIEW command saves it with the specified name.

20

DDAATTAABBAASSEE

Oracle View Wizard

21

DDAATTAABBAASSEE

Oracle Schema Manager: Views

22

DDAATTAABBAASSEE

Oracle Content Viewer

23

DDAATTAABBAASSEE

SQL Server Views

24

DDAATTAABBAASSEE

Simple Computations

OrderItem(OrderID, ItemID, Price, Quantity)

Select OrderID, ItemID, Price, Quantity, Price*Quantity As ExtendedFrom OrderItem;

Basic computations (+ - * /) can be performed on numeric data.The new display column should be given a meaningful name.

OrderID ItemID Price Quantity Extended

151 9764 19.50 2 39.00

151 7653 8.35 3 25.05

151 8673 6.89 2 13.78

25

DDAATTAABBAASSEE

Computations: Aggregation--Avg

What is the average sale price of all animals?

SELECT Avg(SalePrice) AS AvgOfSalePriceFROM SaleAnimal;

Sum Avg Min Max Count StDev Var

Query04_04

26

DDAATTAABBAASSEE

Computations (Math Operators)

What is the total value of the order for PONumber 22? Use any common math operators on numeric data. Operate on data in one row at a time.

OrderTotal 1798.28

SELECT Sum([Quantity]*[Cost]) AS OrderTotalFROM OrderItemWHERE (PONumber=22);

Query04_05

27

DDAATTAABBAASSEE

SQL Differences

28

DDAATTAABBAASSEE

Subtotals (Where)

How many cats are in the Animal list?

SELECT Count(AnimalID) AS CountOfAnimalIDFROM AnimalWHERE (Category = “Cat”);

Query04_06

29

DDAATTAABBAASSEE

Groups and Subtotals

Count the number of animals in each category. You could type in each WHERE clause, but that is slow. And you would have to know all of the Category values.

SELECT Category, Count(AnimalID) AS CountOfAnimalIDFROM AnimalGROUP BY CategoryORDER BY Count(AnimalID) DESC;

Category CountOfAnimalID Dog 100 Cat 47 Bird 15 Fish 14 Reptile 6 Mammal 6 Spider 3

Query04_07

30

DDAATTAABBAASSEE

Conditions on Totals (Having)

Count number of Animals in each Category, but only list them if more than 10.

Category CountOfAnimal Dog 100 Cat 47 Bird 15 Fish 14

SELECT Category, Count(AnimalID) AS CountOfAnimalIDFROM AnimalGROUP BY CategoryHAVING Count(AnimalID) > 10ORDER BY Count(AnimalID) DESC;

Query04_08

31

DDAATTAABBAASSEE

Where (Detail) v Having (Group)

Count Animals born after 6/1/2001 in each Category, but only list Category if more than 10.

CategoryCountOfAnimalID

Dog 30 Cat 18

SELECT Category, Count(AnimalID) AS CountOfAnimalIDFROM AnimalWHERE DateBorn > #6/1/2001#GROUP BY CategoryHAVING Count(AnimalID) > 10ORDER BY Count(AnimalID) DESC;

Query04_09

32

DDAATTAABBAASSEE

Multiple Tables (Intro & Distinct)

List the CustomerID of everyone who bought something between 4/1/01 and 5/31/01.

CustomerID 6 8 14 19 22 24 28 36 37 38 39 42 50 57 58 63 74 80 90

SELECT DISTINCT CustomerIDFROM SaleWHERE (SaleDate Between #4/1/01# And #5/31/01#)ORDER BY CustomerID;

Avoid Duplicateswith DISTINCT

Query04_10

33

DDAATTAABBAASSEE

Joining Tables

List LastNames of Customers who bought between 4/1/2001 and 5/31/2001.

CustomerID LastName

22 Adkins 57 Carter 38 Franklin 42 Froedge 63 Grimes 74 Hinton 36 Holland 6 Hopkins 50 Lee 58 McCain 37 McPherson 90 Nichols 14 Patterson 8 Reid 28 Samuels 80 Vance 39 Williams 24 Young 19 Zhang

SELECT DISTINCT Sale.CustomerID, Customer.LastNameFROM CustomerINNER JOIN Sale ON Customer.CustomerID = Sale.CustomerIDWHERE (Sale.SaleDate Between #4/1/2001# And #5/31/2001#)ORDER BY Customer.LastName;

Query04_11

34

DDAATTAABBAASSEE

SQL JOINFROM table1

INNER JOIN table2

ON table1.column = table2.column

FROM table1, table2

JOIN table1.column = table2.column

SQL 92 syntax (Access and SQL Server)

Informal syntax

FROM table1, table2

WHERE table1.column = table2.column

SQL 89 syntax (Oracle)

35

DDAATTAABBAASSEE

Syntax for Three Tables

FROM Table1

INNER JOIN (Table2 INNER JOIN Table3

ON Table2.ColA = Table3.ColA)

ON Table1.ColB = Table2.ColB

FROM Table1, Table2, Table3

JOIN Table1.ColB = Table2.ColB

Table2.ColA = Table3.ColA

Easier notation, but not correct syntax

SQL ‘92 syntax to join three tables

36

DDAATTAABBAASSEE

Multiple Tables (Many)

List the Last Name and Phone of anyone who bought a registered White cat between 6/1/2001 and 12/31/2001.

SELECT DISTINCTROW Customer.LastName, Customer.PhoneFROM Customer INNER JOIN (Sale INNER JOIN (Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID) ON Sale.SaleID = SaleAnimal.SaleID) ON Customer.CustomerID = Sale.CustomerIDWHERE ((Animal.Category="Cat") AND (Animal.Registered Is Not Null) AND (Color Like "*White*") AND (SaleDate Between #6/1/2001# And #12/31/2001#));

Query04_12

37

DDAATTAABBAASSEE

Building a Query List the Last Name and Phone of anyone who bought a registered

White cat between 6/1/01 and 12/31/ 01.

Identify the tables involved. Look at the columns you want to see.

LastName, Phone: Customer

Look at the columns used in the constraints. Registered, Color, Category: Animal Sale Date: Sale

Find connector tables. To connect Animal to Sale: SaleAnimal

Select the desired columns and test the query. Enter the constraints. Set Order By columns. Add Group By columns. Add summary computations to the SELECT statement.

38

DDAATTAABBAASSEE

Joining Tables (Hints)

Build Relationships First Drag and drop From one side to many side

Avoid multiple ties between tables

SQL FROM Table1 INNER JOIN Table2 ON Table1.ColA = Table2.ColB

Join columns are often keys, but they can be any columns--as long as the domains (types of data) match.

Multiple Tables FROM (Table1 INNER JOIN Table2 ON T1.ColA = T2.ColB ) INNER JOIN Table3 ON T3.ColC = T3.ColD

Shorter Notation FROM T1, T2, T3 JOIN T1.ColA = T2.ColB T1.ColC = T3.ColD

Shorter Notation is not correct syntax, but it is easier to write.

39

DDAATTAABBAASSEE

Tables with Multiple Joins Potential problem with three or more tables. Access uses predefined relationships to

automatically determine JOINs. JOINS might loop. Most queries will not work with loops.

A query with these four tables with four JOINS would only return rows where the Employee had the same ZipCode as the Supplier. If you only need the Supplier city, just delete the JOIN between Employee and ZipCode. If you want both cities, add the ZipCode table again as a fifth table.

AnimalOrder

OrderIDOrderDateReceiveDateSupplierIDShippingCostEmployeeID

Supplier

SupplierIDNameContactNamePhoneAddressZipCodeCityID

City

CityIDZipCodeCityStateAreaCodePopulation1990Population1980CountryLatitudeLongitude

Employee

EmployeeIDLastNameFirstNamePhoneAddressZipCodeCityIDTaxPayerIDDateHiredDateReleased

¥

¥

1 1

40

DDAATTAABBAASSEE

Table Alias

SID Supplier.CityID City.City EID LastName Employee.CityID City2.City4 7972 Middlesboro 5 James 7083 Orlando2 10896 Springfield 1 Reeves 9201 Lincoln4 7972 Middlesboro 3 Reasoner 8313 Springfield9 10740 Columbia 8 Carpenter 10592 Philadelphia5 10893 Smyrna 3 Reasoner 8313 Springfield

SELECT Supplier.SID, Supplier.CityID, City.City, Employee.EID, Employee.LastName, Employee.CityID, City2.CityFROM (City INNER JOIN Supplier ON City.CityID = Supplier.CityID) INNER JOIN ((City AS City2 INNER JOIN Employee ON City2.CityID = Employee.CityID) INNER JOIN AnimalOrder ON Employee.EmployeeID = AnimalOrder.EmployeeID) ON Supplier.SupplierID = AnimalOrder.SupplierID;

41

DDAATTAABBAASSEE

Saved Query: Create View

CREATE VIEW Kittens AS

SELECT *

FROM Animal

WHERE (Category = ‘cat’) AND (Today - DateBorn < 180);

SELECT Avg(ListPrice)

FROM Kittens

WHERE (Color LIKE “*Black*”);

Save a query Faster: only enter once Faster: only analyze once

Any SELECT statement Can use the View within

other SQL queries.

42

DDAATTAABBAASSEE

Updateable Views

OrderItem(OrderID, ItemID, Quantity) Item(ItemID, Description)

OrderLine(OrderID, ItemID, Description, Quantity)

To be updateable, a view must focus on one primary table. (OrderItem) Goal is to change data in only one table. (OrderItem) Data can be displayed from other tables. (Item) Never include or attempt to change primary keys from

more than one table. (Item.ItemID)

43

DDAATTAABBAASSEE

Non Updateable ViewOrderItem(OrderID, ItemID, Quantity) Item(ItemID, Description)

OrderLine(OrderID, Item.ItemID, Description, Quantity)

121 57 3121 82 2122 57 1

57 Cat food58 Dog food59 Bird food

121 57 Cat food 3121 82 Bird feeder 2122 57 Cat food 1

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

You will simply change the primary key value in the Item table.

It will not add a new row to the OrderItem table.

32

44

DDAATTAABBAASSEE

SQL Syntax: ALTER TABLE

ALTER TABLE table ADD COLUMN column datatype (size) DROP COLUMN column

See also:

CREATE TABLE

DROP TABLE

45

DDAATTAABBAASSEE

SQL Syntax: COMMIT

COMMIT WORK

See also: ROLLBACK

46

DDAATTAABBAASSEE

SQL Syntax: CREATE INDEX

CREATE [UNIQUE] INDEX indexON table (column1, column2, … )WITH {PRIMARY | DISALLOW NULL | IGNORE NULL}

See also: CREATE TABLE

47

DDAATTAABBAASSEE

SQL Syntax: CREATE TABLE

CREATE TABLE table( column1 datatype (size) [NOT NULL] [index1] , column2 datatype (size) [NOT NULL] [index2], … , CONSTRAINT pkname PRIMARY KEY (column, …), CONSTRAINT fkname FOREIGN KEY (column)

REFERENCES existing_table (key_column),)

See also:

ALTER TABLE

DROP TABLE

48

DDAATTAABBAASSEE

SQL Syntax: CREATE VIEW

CREATE VIEW viewname ASSELECT …

See also: SELECT

49

DDAATTAABBAASSEE

SQL Syntax: DELETE

DELETEFROM tableWHERE condition

See also: DROP

50

DDAATTAABBAASSEE

SQL Syntax: DROP

DROP INDEX index ON table

DROP TABLE

DROP VIEW

See also: DELETE

51

DDAATTAABBAASSEE

SQL Syntax: INSERT

INSERT INTO table (column1, column2, …)VALUES (value1, value2, … )

INSERT INTO newtable (column1, column2, …)SELECT …

See also: SELECT

52

DDAATTAABBAASSEE

SQL Syntax: GRANT

GRANT privilege privilegesON object ALL, ALTER, DELETE, INDEX,TO user | PUBLIC INSERT, SELECT, UPDATE

See also: REVOKE

53

DDAATTAABBAASSEE

SQL Syntax: REVOKE

REVOKE privilege privilegesON object ALL, ALTER, DELETE, INDEX,FROM user | PUBLIC INSERT, SELECT, UPDATE

See also: GRANT

54

DDAATTAABBAASSEE

SQL Syntax: ROLLBACK

SAVEPOINT savepoint {optional}

ROLLBACK WORK TO savepoint

See also: COMMIT

55

DDAATTAABBAASSEE

SQL Syntax: SELECTSELECT DISTINCT table.column {AS alias} , . . .FROM table/queryINNER JOIN table/query ON T1.ColA = T2.ColBWHERE (condition)GROUP BY columnHAVING (group condition)ORDER BY table.column{ UNION, INTERSECT, EXCEPT … }

GROUP BY CUBE (dimension1, dimension2, …)

TRANSFORM aggfunction {Crosstab values}SELECT . . . FROM . . . GROUP BY {Crosstab rows}PIVOT pivot column {Crosstab columns}

56

DDAATTAABBAASSEE

SQL Syntax: SELECT INTO

SELECT column1, column2, … INTO newtableFROM tablesWHERE condition

See also: SELECT

57

DDAATTAABBAASSEE

SQL Syntax: UPDATE

UPDATE TABLE table SET column1 = value1, column2 = value2, … WHERE condition

See also: DELETE