Database Management Systems Chapter 4 Queries Jerry Post
Database Management Systems Chapter 4 Queries Jerry Post Copyright © 1998 1
D A T A B A S E Why do we Need Queries ² Natural languages (English) are too vague ª With 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 2
D A T A B A S E 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? 3
D A T A B A S E Tables 4
D A T A B A S E Organization ² Single table ² Constraints ² Computations ² Groups/Subtotals ² Multiple Tables 5
D A T A B A S E Sample Questions ² List all animals with yellow in their color. ² List all dogs with yellow in their color born after 6/1/98. ² 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/98 and have white in their color. ² What is the average sale price of all animals? ² What is the total cost we paid for all animals? ² List the top 10 customers and total amount they spent. ² How many cats are in the animal list? ² Count the number of animals in each category. ² List the Customer. ID of everyone who bought something between 4/1/98 and 5/31/98. ² List the first name and phone of every customer who bought something between 4/1/98 and 5/31/98. ² List the last name and phone of anyone who bought a registered white cat between 6/1/98 and 12/31/98. ² Which employee has sold the most items? 6
D A T A B A S E Harder Questions ² How many cats are “in-stock” on 10/1/98? ² Which cats sold for more than the average price? ² Which animals sold for more than the average price of animals in their category? ² Which animals have not been sold? ² Which customers (who bought something at least once) did not buy anything between 11/1/98 and 12/31/98? ² Which customers who bought Dogs also bought products for Cats (at any time)? 7
D A T A B A S E Query 04_01 Query By Example & SQL What tables? What conditions? What to see? SELECT Animal. ID, Category, Breed, Color FROM Animal WHERE (Color LIKE “*yellow*”); ² List all animals with yellow in their color. 8
D A T A B A S E DISTINCT SELECT Category FROM Animal; Category Fish Dog Fish Cat Dog Fish Dog Dog Fish Cat Dog. . . SELECT DISTINCT Category FROM Animal; Category Bird Cat Dog Fish Mammal Reptile Spider 9
D A T A B A S E ORDER BY SELECT columns FROM tables JOIN join columns WHERE conditions ORDER BY columns (ASC DESC) SELECT Name, Category, Breed FROM Animal ORDER BY Category, Breed; Name Cathy Category Bird Debbie Bird Terry Bird Charles Bird Curtis Bird Ruby Bird Sandy Bird Hoyt Bird Breed African Grey Canary Cockatiel Lovebird Other Parakeet Parrot 10
D A T A B A S E Query 04_02 Constraints: And SELECT Animal. ID, Category, Date. Born FROM Animal WHERE ((Category="Dog") AND (Color Like "*Yellow*") AND (Date. Born>#6/1/98#)); ² List all dogs with yellow in their color born after 6/1/98. 11
D A T A B A S E Query 04_03 Conditions: AND, OR SELECT Animal. ID, Category, Gender, Registered, Date. Born, Color FROM Animal WHERE (( Category="Dog") AND ( ( (Gender="Male") AND (Registered Is Not Null) ) OR ( (Date. Born<#6/1/98#) AND (Color Like "*White*") ) ) ); ² List all dogs who are male and registered or who were born before 6/1/98 and have white in their color. 12
D A T A B A S E Useful Where Conditions 13
D A T A B A S E Boolean Algebra And: Both must be true. Or: Either one is true. Not: Reverse the value. a=3 b = -1 c=2 (a > 4) And (b < 0) F T F (a > 4) Or (b < 0) F T T NOT (b < 0) T F
D A T A B A S E Boolean Algebra The result is affected by the order of the operations. Parentheses indicate that an operation should be performed first. With no parentheses, operations are performed left-to-right. a=3 b = -1 c=2 ( (a > 4) AND (b < 0) ) OR (c > 1) F T T Always use parentheses, so other people can read and understand your query. (a > 4) AND ( (b < 0) OR (c > 1) ) F T T F
D A T A B A S E De. Morgan’s Law Example 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. " SQL: SELECT. . . WHERE (Category=“cat”) AND NOT ((Registered is NOT NULL) or (Color LIKE “*red*”)). QBE: 16
D A T A B A S E De. Morgan’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 Registered=ASCF Color=Black NOT ((Registered is NOT NULL) OR (Color LIKE “*red*”)) T F or F T not (Registered is NULL) AND NOT (Color LIKE “*red*”) F not F and T F 17
D A T A B A S E Simple Computations Order. Item(Order. ID, Item. ID, Price, Quantity) Select Order. ID, Item. ID, Price, Quantity, Price*Quantity As Extended From Order. Item; Order. ID Item. ID Price Quantity Extended 151 9764 7653 19. 50 8. 35 2 3 39. 00 25. 05 151 8673 6. 89 2 13. 78 Basic computations (+ - * /) can be performed on numeric data. The new display column should be given a meaningful name. 18
D A T A B A S E Query 04_04 Computations: Example--Avg ² ² ² ² Sum Avg Min Max Count St. Dev Var SELECT Avg(Sale. Price) AS Avg. Of. Sale. Price FROM Sale. Animal; ² What is the average sale price of all animals? 19
D A T A B A S E Query 04_05 Computations (Math Operators) ² Order. Total ² 1798. 28 SELECT Sum([Quantity]*[Cost]) AS Order. Total FROM Order. Item WHERE (PONumber=22); ² 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. 20
D A T A B A S E Query 04_06 Subtotals (Where) SELECT Count(Animal. ID) AS Count. Of. Animal. ID FROM Animal WHERE (Category = “Cat”); ² How many cats are in the Animal list? 21
D A T A B A S E Query 04_07 Groups and Subtotals ² ² ² ² SELECT FROM GROUP BY ORDER BY Category Dog 100 Cat 47 Bird 15 Fish 14 Reptile Mammal Spider Count. Of. Animal. ID 6 6 3 Category, Count(Animal. ID) AS Count. Of. Animal. ID Animal Category Count(Animal. ID) DESC; ² 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. 22
D A T A B A S E Query 04_08 Conditions on Totals (Having) ² ² ² SELECT FROM GROUP BY HAVING ORDER BY Category Dog 100 Cat 47 Bird 15 Fish 14 Count. Of. Animal Category, Count(Animal. ID) AS Count. Of. Animal. ID Animal Category Count(Animal. ID) > 10 Count(Animal. ID) DESC; ² Count number of Animals in each Category, but only list them if more than 10. 23
D A T A B A S E Query 04_09 Where (Detail) v Having (Group) Category Count. Of. Animal. ID ² Dog 30 ² Cat 18 SELECT FROM WHERE GROUP BY HAVING ORDER BY Category, Count(Animal. ID) AS Count. Of. Animal. ID Animal Date. Born > #6/1/98# Category Count(Animal. ID) > 10 Count(Animal. ID) DESC; ² Count Animals born after 6/1/98 in each Category, but only list Category if more than 10. 24
D A T A B A S E Query 04_10 Multiple Tables (Intro & Distinct) SELECT DISTINCT Customer. ID FROM Sale WHERE (Sale. Date Between #4/1/98# And #5/31/98#) ORDER BY Customer. ID; ² ² ² ² ² Customer. ID 6 8 14 19 22 24 28 36 37 38 39 Avoid Duplicates 42 with DISTINCT 50 57 58 63 74 80 90 ² List the Customer. ID of everyone who bought something between 4/1/98 and 5/31/98. 25
D A T A B A S E Query 04_11 Joining Tables ² Customer. ID Last. Name ² 22 Adkins ² 57 Carter ² 38 Franklin ² 42 Froedge ² 63 Grimes ² 74 Hinton ² 36 Holland ² 6 Hopkins ² 50 Lee ² 58 Mc. Cain ² 37 Mc. Pherson ² 90 Nichols ² 14 Patterson ² 8 Reid SELECT DISTINCT Sale. Customer. ID, Customer. Last. Name ² 28 Samuels FROM Customer ² 80 Vance INNER JOIN Sale ON Customer. ID = Sale. Customer. ID ² 39 Williams WHERE (Sale. Date Between #4/1/98# And #5/31/98#) ² 24 Young ORDER BY Customer. Last. Name; ² 19 Zhang ² List Last. Names of Customers who bought between 4/1/98 and 5/31/98. 26
D A T A B A S E SQL JOIN FROM table 1 INNER JOIN table 2 ON table 1. column = table 2. column SQL 92 syntax FROM table 1, table 2 WHERE table 1. column = table 2. column SQL 89 syntax FROM table 1, table 2 JOIN table 1. column = table 2. column Informal syntax 27
D A T A B A S E Query 04_12 Multiple Tables (Many) SELECT DISTINCTROW Customer. Last. Name, Customer. Phone FROM Customer INNER JOIN (Sale INNER JOIN (Animal INNER JOIN Sale. Animal ON Animal. ID = Sale. Animal. ID) ON Sale. ID = Sale. Animal. Sale. ID) ON Customer. ID = Sale. Customer. ID WHERE ((Animal. Category="Cat") AND (Animal. Registered Is Not Null) AND (Color Like "*White*") AND (Sale. Date Between #6/1/98# And #12/31/98#)); ² List the Last Name and Phone of anyone who bought a registered White cat between 6/1/98 and 12/31/ 98. 28
D A T A B A S E Building a Query ² List the Last Name and Phone of anyone who bought a registered White cat between 6/1/98 and 12/31/ 98. ² Identify the tables involved. ª Look at the columns you want to see. © Last. Name, 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: Sale. Animal ² ² ² 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. 29
D A T A B A S E Joining Tables (Hints) ² Build Relationships First ª Drag and drop ª From one side to many side ² Avoid multiple ties between tables ² SQL ª FROM Table 1 ª INNER JOIN Table 2 ª ON Table 1. Col. A = Table 2. Col. B ² Join columns are often keys, but they can be any columns--as long as the domains (types of data) match. ² Multiple Tables ª FROM (Table 1 ª INNER JOIN Table 2 ª ON T 1. Col. A = T 2. Col. B ) ª INNER JOIN Table 3 ª ON T 3. Col. C = T 3. Col. D ² Shorter Notation ª FROM T 1, T 2, T 3 ª JOIN T 1. Col. A = T 2. Col. B ª T 1. Col. C = T 3. Col. D ² Shorter Notation is not correct syntax, but it is easier to write. 30
D A T A B A S E 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 Zip. Code as the Supplier. If you only need the Supplier city, just delete the JOIN between Employee and Zip. Code. If you want both cities, add the Zip. Code table again as a fifth table. 31
D A T A B A S E Table Alias SELECT Supplier. SID, Supplier. City. ID, City, Employee. EID, Employee. Last. Name, Employee. City. ID, City 2. City FROM (City INNER JOIN Supplier ON City. ID = Supplier. City. ID) INNER JOIN ((City AS City 2 INNER JOIN Employee ON City 2. City. ID = Employee. City. ID) INNER JOIN Animal. Order ON Employee. ID = Animal. Order. Employee. ID) ON Supplier. ID = Animal. Order. Supplier. ID; SID 4 2 4 9 5 Supplier. City. ID 7972 10896 7972 10740 10893 City Middlesboro Springfield Middlesboro Columbia Smyrna EID 5 1 3 8 3 Last. Name James Reeves Reasoner Carpenter Reasoner Employee. City. ID 7083 9201 8313 10592 8313 City 2. City Orlando Lincoln Springfield Philadelphia Springfield
D A T A B A S E Saved Query: Create View ² Save a query ª Faster: only enter once ª Faster: only analyze once ² Any SELECT statement ² Can use the View within other SQL queries. CREATE VIEW Kittens AS SELECT * FROM Animal WHERE (Category = ‘cat’) AND (Today - Date. Born < 180); SELECT Avg(List. Price) FROM Kittens WHERE (Color LIKE “*Black*”);
D A T A B A S E Updateable Views Order. Item(Order. ID, Item. ID, Quantity) Item(Item. ID, Description) Order. Line(Order. ID, Item. ID, Description, Quantity) ² To be updateable, a view must focus on one primary table. (Order. Item) ª Goal is to change data in only one table. (Order. Item) ª Data can be displayed from other tables. (Item) ª Never include or attempt to change primary keys from more than one table. (Item. ID)
D A T A B A S E Non Updateable View Order. Item(Order. ID, Item. ID, Quantity) 121 122 57 82 57 3 2 1 Item(Item. ID, Description) 57 58 59 Cat food Dog food Bird food Order. Line(Order. ID, Item. ID, Description, Quantity) 121 122 57 82 57 32 Cat food Bird feeder Cat food 3 2 1 If you attempt to change the Item. ID in the Order. Line. View: You will simply change the primary key value in the Item table. It will not add a new row to the Order. Item table.
- Slides: 35