Presentation is loading. Please wait.

Presentation is loading. Please wait.

DATABASE APPLICATION DEVELOPMENT SAK 3408 Query Statements.

Similar presentations


Presentation on theme: "DATABASE APPLICATION DEVELOPMENT SAK 3408 Query Statements."— Presentation transcript:

1 DATABASE APPLICATION DEVELOPMENT SAK 3408 Query Statements

2 SAK3408 by PSS 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

3 SAK3408 by PSS 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 SAK3408 by PSS Tables

5 SAK3408 by PSS Sample Questions  List all animals with yellow in their color.  List all dogs with yellow in their color born after 6/1/04.  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/04 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 CustomerID of everyone who bought something between 4/1/04 and 5/31/04.  List the first name and phone of every customer who bought something between 4/1/04 and 5/31/04.  List the last name and phone of anyone who bought a registered white cat between 6/1/04 and 12/31/04.  Which employee has sold the most items?

6 SAK3408 by PSS Query By Example & SQL SELECTAnimalID, Category, Breed, Color FROMAnimal WHERE(Color LIKE ‘%Yellow%’); What to see? Query04_01 AnimalID Name Category Breed DateBorn Gender Animal FieldAnimalIDCategoryBreedColor TableAnimal Sort CriteriaLike ‘%Yellow%’ Or What tables? What conditions? List all animals with yellow in their color

7 SAK3408 by PSS Basic SQL SELECT SELECTcolumnsWhat do you want to see? FROMtablesWhat tables are involved? JOINconditionsHow are the tables joined? WHEREcriteriaWhat are the constraints?

8 SAK3408 by PSS ORDER BY SELECTcolumns FROMtables JOINjoin columns WHEREconditions ORDER BYcolumns (ASC DESC) SELECT Name, Category, Breed FROM Animal ORDER BY Category, Breed; NameCategoryBreed CathyBirdAfrican Grey BirdCanary DebbieBirdCockatiel BirdCockatiel TerryBirdLovebird BirdOther CharlesBirdParakeet CurtisBirdParakeet RubyBirdParakeet SandyBirdParrot HoytBirdParrot BirdParrot AnimalID Name Category Breed DateBorn Gender Animal FieldNameCategoryBreed TableAnimal SortAscending Criteria Or

9 SAK3408 by PSS DISTINCT SELECT Category FROM Animal; Category Fish Dog Fish Cat Dog Fish Dog Fish Cat Dog... SELECT DISTINCT Category FROM Animal; Category Bird Cat Dog Fish Mammal Reptile Spider

10 SAK3408 by PSS Constraints: And List all dogs with yellow in their color born after 6/1/04. SELECTAnimalID, Category, DateBorn FROMAnimal WHERE((Category=‘Dog’) AND (Color Like ‘%Yellow%’) AND (DateBorn>’01-Jun-2004’)); Query04_02 AnimalID Name Category Breed DateBorn Gender Animal FieldAnimalIDCategoryDateBornColor TableAnimal Sort Criteria‘Dog’>’01-Jun-2004’Like ‘%Yellow%’ Or

11 SAK3408 by PSS Boolean Algebra And:Both must be true. Or:Either one is true. Not:Reverse the value. a = 3 b = -1 c = 2 (a > 4) Or (b < 0) FT F (a > 4) And (b < 0) FT T NOT (b < 0) T F

12 SAK3408 by PSS Boolean Algebra FT F T ( (a > 4) AND (b 1) T T FT F F (a > 4) AND ( (b 1) ) T T a = 3 b = -1 c = 2 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. Always use parentheses, so other people can read and understand your query.

13 SAK3408 by PSS DeMorgan’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." SELECT AnimalID, Category, Registered, Color FROM Animal WHERE (Category=‘Cat’) AND NOT ((Registered is NOT NULL) OR (Color LIKE ‘%Red%’)). AnimalID Name Category Breed DateBorn Gender Animal FieldAnimalIDCategoryRegisteredColor TableAnimal Sort Criteria‘Cat’Is NullNot Like ‘%Red%’ Or

14 SAK3408 by PSS 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 Registered=ASCF Color=Black TF T F NOT ((Registered is NOT NULL) OR (Color LIKE ‘%Red%’)) or not (Registered is NULL) AND NOT (Color LIKE ‘%Red%’) F T F and F not

15 SAK3408 by PSS Conditions: AND, OR List all dogs who are male and registered or who were born before 6/1/2004 and have white in their color. SELECT AnimalID, Category, Gender, Registered, DateBorn, Color FROM Animal WHERE (( Category=‘Dog’) AND ( ( (Gender=‘Male’) AND (Registered Is Not Null) ) OR ( (DateBorn<’01-Jun-2004’) AND (Color Like ‘%White%’) ) ) ); AnimalID Name Category Breed DateBorn Gender Animal FieldAnimalIDCategoryGenderRegisteredDateBornColor TableAnimal Sort Criteria‘Dog’‘Male’Is Not Null Or‘Dog’< ’01-Jun- 2004’ Like ‘%White%’

16 SAK3408 by PSS Useful Where Conditions ComparisonsExamples Operators, <>, BETWEEN, LIKE, IN NumbersAccountBalance > 200 Text Simple Pattern match one Pattern match any Name > ‘Jones’ License LIKE ‘A_ _82_’ Name LIKE ‘J%’ DatesSaleDate BETWEEN ’15-Aug-2004’ AND ’31-Aug-2004’ Missing DataCity IS NULL NegationName IS NOT NULL SetsCategory IN (‘Cat’, ‘Dog’, ‘Hamster’)

17 SAK3408 by PSS Simple Computations SaleItem(OrderID, ItemID, SalePrice, Quantity) Select OrderID, ItemID, SalePrice, Quantity, SalePrice*Quantity As Extended From SaleItem; Basic computations (+ - * /) can be performed on numeric data. The new display column should be given a meaningful name. OrderIDItemIDPriceQuantityExtended 151976419.50239.00 1517653 8.35325.05 1518673 6.89213.78

18 SAK3408 by PSS Computations: Aggregation--Avg What is the average sale price of all animals? SELECT Avg(SalePrice) AS AvgOfSalePrice FROM SaleAnimal; Query04_04 SaleID AnimalID SalePrice SaleAnimal FieldSalePrice TableSaleAnimal TotalAvg Sort Criteria Or Sum Avg Min Max Count StDev or StdDev Var

19 SAK3408 by PSS 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. SELECT Sum(Quantity*Cost) AS OrderTotal FROM OrderItem WHERE (PONumber=22); PONumber ItemID Quantity Cost OrderItem FieldPONumberOrderTotal: Quantity*Cost TableOrderItem Total Sort Criteria=22 Or OrderTotal 1798.28

20 SAK3408 by PSS SQL Differences

21 SAK3408 by PSS Subtotals (Where) How many cats are in the Animal list? SELECTCount(AnimalID) AS CountOfAnimalID FROMAnimal WHERE(Category = ‘Cat’); AnimalID Name Category Breed DateBorn Gender Animal FieldAnimalIDCategory TableAnimal TotalCountWhere Sort Criteria‘Cat’ Or

22 SAK3408 by PSS 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. SELECTCategory, Count(AnimalID) AS CountOfAnimalID FROMAnimal GROUP BYCategory ORDER BYCount(AnimalID) DESC; Query04_07 AnimalID Name Category Breed DateBorn Gender Animal FieldCategory AnimalID TableAnimal TotalGroup ByCount SortDescending Criteria Or CategoryCountOfAnimalID Dog100 Cat47 Bird15 Fish14 Reptile6 Mammal6 Spider3

23 SAK3408 by PSS Conditions on Totals (Having) Count number of Animals in each Category, but only list them if more than 10. SELECTCategory, Count(AnimalID) AS CountOfAnimalID FROMAnimal GROUP BYCategory HAVINGCount(AnimalID) > 10 ORDER BYCount(AnimalID) DESC; AnimalID Name Category Breed DateBorn Gender Animal FieldCategoryAnimalID TableAnimal TotalGroup ByCount SortDescending Criteria>10 Or CategoryCountOfAnimalID Dog100 Cat47 Bird15 Fish14

24 SAK3408 by PSS Where (Detail) v Having (Group) Count Animals born after 6/1/2004 in each Category, but only list Category if more than 10. SELECTCategory, Count(AnimalID) AS CountOfAnimalID FROMAnimal WHEREDateBorn > ’01-Jun-2004’ GROUP BYCategory HAVINGCount(AnimalID) > 10 ORDER BYCount(AnimalID) DESC; AnimalID Name Category Breed DateBorn Gender Animal FieldCategoryAnimalIDDateBorn TableAnimal TotalGroup ByCountWhere SortDescending Criteria>10>’01-Jun-2004’ Or CategoryCountOfAnimalID Dog30 Cat18

25 SAK3408 by PSS Multiple Tables (Intro & Distinct) List the CustomerID of everyone who bought something between 01- Apr-2004 and 31-May-2004. CustomerID 6 8 14 19 22 24 28 36 37 38 39 42 50 57 58 63 74 80 90 SELECT DISTINCT CustomerID FROM Sale WHERE (SaleDate Between ’01-Apr-2004’ And ’31-May-2004’) ORDER BY CustomerID; SaleID SaleDate EmployeeID CustomerID SalesTax Sale FieldCustomerIDSaleDate TableSale SortAscending CriteriaBetween ’01-Apr-2004’ And ’31-May-2004’ Or

26 SAK3408 by PSS Joining Tables List LastNames of Customers who bought between 4/1/2004 and 5/31/2004. SELECT DISTINCT Sale.CustomerID, Customer.LastName FROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID WHERE (SaleDate Between ’01-Apr-2004’ And ’31-May-2004’) ORDER BY Customer.LastName; FieldCustomerIDLastNameSaleDate TableSaleCustomerSale SortAscending CriteriaBetween ’01-Apr-2004’ And ’31-May-2004’ Or CustomerID LastNam e 22Adkins 57Carter 38Franklin 42Froedge 63Grimes 74Hinton 36Holland 6Hopkins 50Lee 58McCain … SaleID SaleDate EmployeeID CustomerID Sale CustomerID Phone FirstName LastName Customer

27 SAK3408 by PSS SQL JOIN FROM 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)

28 SAK3408 by PSS 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 JOINTable1.ColB = Table2.ColB Table2.ColA = Table3.ColA Easier notation, but not correct syntax SQL ‘92 syntax to join three tables

29 SAK3408 by PSS Multiple Tables (Many)  List the Last Name and Phone of anyone who bought a registered White cat between 6/1/2004 and 12/31/2004. SELECT DISTINCTROW Customer.LastName, Customer.Phone 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 WHERE ((Animal.Category=‘Cat’) AND (Animal.Registered Is Not Null) AND (Color Like ‘%White%’) AND (SaleDate Between ’01-Jun-2004’ And ’31-Dec-2004’)); FieldLastNamePhoneCategoryRegisteredColorSaleDate TableCustomer Animal Sale SortAscending Criteria‘Cat’Is Not NullLike ‘%White%’Between ’01-Jun- 2004’ And ’31-Dec- 2004’ Or SaleID SaleDate EmployeeID CustomerID Sale CustomerID Phone FirstName LastName Customer SaleID AnimalID SalePrice SaleAnimal AnimalID Name Category Breed Animal

30 SAK3408 by PSS Building a Query  List the Last Name and Phone of anyone who bought a registered White cat between 6/1/04 and 12/31/04.  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.

31 SAK3408 by PSS 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.

32 SAK3408 by PSS


Download ppt "DATABASE APPLICATION DEVELOPMENT SAK 3408 Query Statements."

Similar presentations


Ads by Google