chapter 4 querying based on g. post, dbms: designing & building business applications university...
TRANSCRIPT
Chapter 4
Querying
Based on G. Post, DBMS: Designing & Building Business Applications
University of ManitobaAsper School of Business
3500 DBMSBob Travica
Updated 2015
DDBB
SSYYSSTTEEMMSS
Why do we Need Queries
To extract meaningful data from database, which help us
answer business questions. Querying databases is where
business value from a DB system is drawn.
We need a standardized system so users and developers can
learn one method that works on any (most) systems. SQL vs. Query By Example (QBE)
2 of 35
DDBB
SSYYSSTTEEMMSS
Four Questions to Create a Query
What data do you need to get? (columns in tables)
What table or tables are involved?
What are the constraints (filtering conditions for data,
search terms)?
If more tables needed, how to join them?
Download Sally’s Pet Store 2010 (queries work with it)
3 of 35
DDBB
SSYYSSTTEEMMSS
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
*
*
*
*
*
*
*
*
*
**
*
*
*
**
*
**
*
Your Querying Play Pen: Sally’s Pet Store Database
4 of 32
Know your data!
Know your data!
DDBB
SSYYSSTTEEMMSS
Sample Questions 1) List all animals with yellow in their
color.
2) List all dogs with yellow in their color
born after 6/1/01.
3) List all merchandise for cats with a list
price greater than $10.
4) List all dogs who are male and
registered or who were born before
6/1/01 and have white in their color.
5) What is the average sale price of all
animals?
6) What is the value of merchandise sold
per transaction record?
7) List the top 10 customers and total
amount they spent.
8) How many cats are in the animal list?
9) Show animals in each category with
the count above 10.
10) List the CustomerID of the
customers that purchased something
between 4/1/01 and 5/31/01.
5 of 35
DDBB
SSYYSSTTEEMMSS
Query By Example vs. SQLQuery #1: List all animals with yellow in their color (only or along with other colors).
SELECT * FROM AnimalWHERE (Color LIKE “*yellow*”);
Which tables?
Which data(columns)
Which constraints
6 of 35
DDBB
SSYYSSTTEEMMSS
SQL Query – Structure(Partial)
SELECT columns - What columns (information) to display?
FROM tables - What tables are involved?
(INNER JOIN - If more than one table used: What columns are the tables joined on -
PK & FK ?)
WHERE constraints - What are the constraints (filtering conditions) on records to be searched and displayed?
7 of 32
DDBB
SSYYSSTTEEMMSS
More on Sample Query #1
Query question: List IDs, category, breed and color for animals that have yellow in their color.
Query statement:SELECTAnimalID, Category, Breed, ColorFROM AnimalWHERE Color LIKE “*yellow*”;
Variations of filtering condition – What do you get?:- WHERE Color like “yellow”, Color = “yellow”- WHERE Color LIKE [Please type color] - Application in parameter query (asking user to enter desired color)
8 of 32
DDBB
SSYYSSTTEEMMSS
ORDER BY (Sorting)
SELECT columnsFROM tablesINNER JOIN columnsWHERE constraintsORDER BY columns ASC {or DESC}
SELECT Category, BreedFROM AnimalORDER BY Category, Breed; Category Breed
Bird ParakeetBird ParakeetBird ParrotBird ParrotBird ParrotCat AbyssinianCat AbyssinianCat American Short…
Output
Try to reverse Breed and Category in ORDER BY (and SELECT).
9 of 32
DDBB
SSYYSSTTEEMMSS
Constraints
SELECTAnimalID, Category, Color, DateBornFROM AnimalWHERE ((Category="Dog") AND (Color Like "*Yellow*") AND (DateBorn > #6/1/2001#));
• Implemented as operators (Relational, Boolean, String)
String OperatorBoolean OperatorRelational Operator
Query #2: List all dogs with yellow in their color and born after 6/1/01.
10 of 35
DDBB
SSYYSSTTEEMMSS
Query #3: List IDs and descriptions for the merchandise for cats with a list price greater than $10.
SQL statement:SELECT ItemID, Description, Category, ListPriceFROM Merchandise WHERE Category = "Cat" AND ListPrice > 10;
More on AND and > Operators
Output:
Note how the ListPrice constraint is presented as a number (no quotes).
ItemID Description Category ListPrice 5 Cat Bed-Small Cat 25,00 $ 6 Cat Bed-Medium Cat 35,00 $
14 Cat Food-Dry-25 pound Cat 18,00 $ 40 Litter Box-Covered Cat 15,00 $
11 of 35
DDBB
SSYYSSTTEEMMSS
The AND vs. OR Operators
Query #4: List all dogs that are male and registered or that were born
before 6/1/2007 and have white in their color.
• Output will include some older non-registered dogs of either gender.• Note the Registered constraint (a null value = a blank cell, missing data).
- cannot be replaced by zero (0)- a reserved word in SQL syntax- can be understood as “we don’t know what the value is”• Best to write this query in two parts, test each separately, then
put them together.
SELECT AnimalID, Category, Gender, Registered, DateBorn, Color
FROM Animal
WHERE (Category="Dog" AND Gender="Male" AND Registered Is Not Null)
OR
(Category="Dog" AND DateBorn < #June 1, 2007# AND Color Like "*White*") ;
12 of 35
DDBB
SSYYSSTTEEMMSS
Boolean Algebra
AND: True if both A and B exist.OR: True if either A or B or both exist.NOT: A (or B) does not exist.
2. Query with OR: (a > 4) OR (b < 0)
FF T
1. Query with AND:(a > 4) AND (b < 0) =(3 > 4) AND (-1 < 0)
F TT
3. Query with NOT: NOT (a > 4)
F
a = 3
b = -1
ExampleRecord
attributes a & b:
No match,Record not fethced
Match!
Match
A B A AND B A OR BT T T TT F F TF T F TF F F F
If ……….. Then…………………..…
-T NOT A F
F - NOT A T
13 of 32
T
DDBB
SSYYSSTTEEMMSS
BOO-lean Algebra
Parentheses indicate order of operations – start working from within parentheses, then work out with resulting values.
a = 7
b = 200
c = 2
F TF
T
( (a > 10) AND (b => 200) ) OR (c > 1)
T
1
2
3
14 of 32
*
DDBB
SSYYSSTTEEMMSS
DeMorgan’s LawCustomer: "I want to look at a cat, but I don’t want any cats that are registered or that have red in their color."
SELECT Category, Registered, Color FROM AnimalWHERE (Category="cat") AND
NOT ((Registered Is NOT NULL) OR (Color LIKE "*red*"));
More…
Category Registered Color
Cat Gray/Blue
Cat White
Cat White
Cat Yellow
Cat White
Used for simplifying cumbersome statements using NOT:
Output:
15 of 32
Transformed into a simpler form by DeMorgan’s Law:
SELECT Category, Registered, Color FROM AnimalWHERE Category="cat" AND Registered Is Null AND
Color NOT LIKE "*red*";
16 of 35
More…
DDBB
SSYYSSTTEEMMSS
Negation of clauses NOT (A AND B) becomes NOT A OR NOT B, and the global NOT is
deleted NOT (A OR B) becomes NOT A AND NOT B, global NOT is deleted IS NOT becomes IS IS, = become NOT
T F
TF
NOT ((Registered IS NOT null) OR (Color LIKE “*red*”))
• Example: Constraints are Registered=ASCF, Color=Black
(Registered IS null) AND NOT (Color LIKE “*red*”)
FT
F
OR
NOT
AND
FNOT
DeMorgan’s Law applied:
17 of 35
DDBB
SSYYSSTTEEMMSS
Computations – Row By Row
Query #6: What is the value of merchandise sold per transaction record?
SELECT SaleID, ItemID, SalePrice, Quantity, SalePrice*Quantity As SumFROM SaleItem;
SaleID ItemID SalePrice Quantity Sum 187 18 $0,90 50 45,00 $ 188 4 $58,50 1 58,50 $ 188 11 $27,00 6 162,00 $ 188 16 $0,72 25 18,00 $ 189 17 $0,45 30 13,50 $ 189 22 $67,50 2 135,00 $
Partial output:
18 of 32
DDBB
SSYYSSTTEEMMSS
Computations On All Rows
Query #5: What is the average donation price of all animals?
SELECT Avg(Donation) AS [Average Donation Price] FROM Animal;
DBMS supports math & stats functions: Sum Avg Min Max Count StDev Var
Play with these functionsto learn more aboutanimals sold!
19 of 35
DDBB
SSYYSSTTEEMMSS
Computations On Select Rows (with WHERE clause)
Query #8: How many cats are in the Animal list?
SELECT Count(AnimalID) AS [Cats Total]FROM AnimalWHERE Category = “Cat” ;
How would you make a general (parameter) query to find the count of animals in any category the user wants?
20 of 35
DDBB
SSYYSSTTEEMMSS
Aggregate Functions – GROUP BY Clause
Arithmetic and statistical functions that work on an appropriate set of records.
Question: What is the average donation price per animal category?
The first idea is to build the query can on the previous, with addition of attribute Category: SELECT Category, Avg(Donation) AS [Average Donation Price] FROM Animal;
But DB system will report an error that Category is not part of an aggregate function.
Correct query is:
SELECT Category, Avg(Donation) AS [Average Donation Price]
FROM Animal
GROUP BY Category ;
21 of 35
DDBB
SSYYSSTTEEMMSS
Computations On Select Rows (with HAVING clause)
Query #9: Show Categories of animals with the count above 10.
SELECT Category, Count(AnimalID) AS CountOfAnimalIDFROM AnimalGROUP BY CategoryHAVING Count(AnimalID) > 10ORDER BY Count(AnimalID) DESC;
optional
Processing order: (1) Group rows by attribute Category; (2) Find theaverage for each group; (3) Count rows in each group; (4) Comparethe counts with number 10; (5) select and display Category names andtheir counts where the count > 10.
22 of 35
DDBB
SSYYSSTTEEMMSS
SQL Syntax(May Be Useful for later use)
23 of 32
DDBB
SSYYSSTTEEMMSS
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}
24 of 32
DDBB
SSYYSSTTEEMMSS
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
25 of 32
DDBB
SSYYSSTTEEMMSS
ALTER TABLE
ALTER TABLE table ADD COLUMN column datatype (size) DROP COLUMN column
See also: CREATE TABLE DROP TABLE
SQL Syntax: COMMIT
COMMIT WORK
See also: ROLLBACK
26 of 32
DDBB
SSYYSSTTEEMMSS
CREATE INDEX
CREATE [UNIQUE] INDEX indexON table (column1, column2, … )WITH {PRIMARY | DISALLOW NULL | IGNORE NULL}
See also: CREATE TABLE
27 of 32
DDBB
SSYYSSTTEEMMSS
DROP
DROP INDEX index ON table
DROP TABLE
DROP VIEW
See also: DELETE
28 of 32
DDBB
SSYYSSTTEEMMSS
DELETE
DELETEFROM tableWHERE condition
See also: DROP
INSERT
INSERT INTO table (column1, column2, …)VALUES (value1, value2, … )
INSERT INTO newtable (column1, column2, …)SELECT …
29 of 32
DDBB
SSYYSSTTEEMMSS
UPDATE
UPDATE TABLE table SET column1 = value1, column2 = value2, … WHERE condition
See also: DELETE
30 of 32
DDBB
SSYYSSTTEEMMSS
GRANT
GRANT privilege privilegesON object ALL, ALTER, DELETE, INDEX,TO user | PUBLIC INSERT, SELECT, UPDATE
See also: REVOKE
31 of 32
DDBB
SSYYSSTTEEMMSS
REVOKE
REVOKE privilege privilegesON object ALL, ALTER, DELETE, INDEX,FROM user | PUBLIC INSERT, SELECT, UPDATE
See also: GRANT
32 of 32
DDBB
SSYYSSTTEEMMSS
ROLLBACK
SAVEPOINT savepoint {optional}
ROLLBACK WORK TO savepoint
See also: COMMIT
33 of 32