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

Slides:



Advertisements
Similar presentations
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Advertisements

Concepts of Database Management Seventh Edition
Concepts of Database Management Sixth Edition
Concepts of Database Management Seventh Edition
1 Copyright © 2010 Jerry Post with additions & narration by M. E. Kabay. All rights reserved. Advanced Queries IS240 – DBMS Lecture # 8 – M.
The University of Akron Dept of Business Technology Computer Information Systems The Relational Model: Query-By-Example (QBE) 2440: 180 Database Concepts.
5 Chapter 5 Structured Query Language (SQL2) Revision.
Chapter Eight Managing Data Resources File Organization and Concepts.
Temple University – CIS Dept. CIS331– Principles of Database Systems V. Megalooikonomou Query by example (based on notes by Silberchatz,Korth, and Sudarshan.
DATABASE APPLICATION DEVELOPMENT SAK 3408 Query Statements.
Jerry Post McGraw-Hill/Irwin Copyright © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. Database Management Systems Chapter 4 Data Queries.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
1.NET Web Forms Database Queries © 2002 by Jerry Post.
Microsoft Access 2010 Chapter 7 Using SQL.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Copyright © 2010 M. E. Kabay. All rights reserved. Analyzing and Building Simple Queries in SQL IS240 – Database Management Supplement to Chapter 4 M.
Concepts of Database Management, Fifth Edition
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE) Datalog.
Chapter 4 Querying Based on G. Post, DBMS: Designing & Building Business Applications University of Manitoba Asper School of Business 3500 DBMS Bob Travica.
1 All Powder Board and Ski Microsoft Access Workbook Chapter 4: Queries Jerry Post Copyright © 2007.
Chapter 5 Advanced Querying
SQL 1: GETTING INFORMATION OUT OF A DATABASE MIS2502 Data Analytics.
Jerry Post Copyright © Database Management Systems Chapter 4 Queries.
School of Computer & Communication of LNPU 辽宁石油化工大学计算机与通信工程学院 刘旸 1 数据库管理系统 Database Management Systems Chapter4 Queries 第四章 数据查询.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Concepts of Database Management Seventh Edition
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE)
MIS2502: Data Analytics SQL – Getting Information Out of a Database David Schuff
Querying a Database Access Project 2. 2 What is a Query?  In general, a query is a form of questioning, in a line of inquiry. A query may also refer.
Jerry Post Copyright © Database Management Systems Chapter 5 Advanced Queries.
劉 志 俊 (Chih-Chin Liu) 中華大學 資訊工程系 October 2001 Chap 9 SQL (III): Advanced Queries.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
1 All Powder Board and Ski Oracle 9i Workbook Chapter 4: Queries Jerry Post Copyright © 2003.
Intro to SQL Management Studio. Please Be Sure!! Make sure that your access is read only. If it isn’t, you have the potential to change data within your.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
1 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Queries: Part 2 of 2 IS240 – DBMS Lecture # 7 – M. E. Kabay, PhD, CISSP-ISSMP.
Computing & Information Sciences Kansas State University Monday, 17 Sep 2007CIS 560: Database System Concepts Lecture 12 of 42 Monday, 18 February 2008.
1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
1 All Powder Board and Ski Microsoft Access Workbook Chapter 4: Queries Jerry Post Copyright © 2003.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
1 All Powder Board and Ski Microsoft Access Workbook Chapter 5: Advanced Queries Jerry Post Copyright © 2003.
1 MySQL and SQL. 2 Topics  Introducing Relational Databases  Terminology  Managing Databases MySQL and SQL.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
1 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Queries: Part 1 of 2 IS240 – DBMS Lecture # 6 – M. E. Kabay, PhD, CISSP-ISSMP.
Jerry Post Copyright © Database Management Systems Chapter 4 Queries.
Jerry Post McGraw-Hill/Irwin Copyright © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. Database Management Systems Chapter 4 Data Queries.
MIS2502: Data Analytics SQL – Getting Information Out of a Database.
Jerry Post Copyright © Database Management Systems Chapter 4 Queries.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
1 All Powder Board and Ski SQL Server Workbook Chapter 5: Advanced Queries Jerry Post Copyright © 2003.
Southern Methodist University CSE CSE 2337 Introduction to Data Management Chapter 2.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
1 Ch4 Summary Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
How to: SQL By: Sam Loch.
Queries: Part 1 of 2 IS240 – DBMS Lecture # 6 –
M. E. Kabay, PhD, CISSP-ISSMP V:
Advanced Queries in MS Access
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Analyzing and Building Simple Queries in SQL
Aggregations Various Aggregation Functions GROUP BY HAVING.
Chapter 4 Summary Query.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Structured Query Language – The Fundamentals
Section 4 - Sorting/Functions
Shelly Cashman: Microsoft Access 2016
Presentation transcript:

Jerry Post Copyright © Database Management Systems Chapter 4 Queries

DATABASE 2 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

DATABASE 3 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?

DATABASE 4 Tables

DATABASE 5 Organization  Single table  Constraints  Computations  Groups/Subtotals  Multiple Tables

DATABASE 6 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 CustomerID 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?

DATABASE 7 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)?

DATABASE 8 Query By Example & SQL  List all animals with yellow in their color. SELECTAnimalID, Category, Breed, Color FROMAnimal WHERE(Color LIKE “*yellow*”); What tables? What to see? What conditions? Query04_01

DATABASE 9 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

DATABASE 10 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

DATABASE 11 Constraints: And  List all dogs with yellow in their color born after 6/1/98. SELECTAnimalID, Category, DateBorn FROMAnimal WHERE((Category="Dog") AND (Color Like "*Yellow*") AND (DateBorn>#6/1/98#)); Query04_02

DATABASE 12 Conditions: AND, OR  List all dogs who are male and registered or who were born before 6/1/98 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<#6/1/98#) AND (Color Like "*White*") ) ) ); Query04_03

DATABASE 13 Useful Where Conditions

DATABASE 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

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

DATABASE 16 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." SQL:SELECT... WHERE (Category=“cat”) AND NOT ((Registered is NOT NULL) or (Color LIKE “*red*”)). QBE:

DATABASE 17 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 TF T F NOT ((Registered is NOT NULL) OR (Color LIKE “*red*”)) Registered=ASCF Color=Black (Registered is NULL) AND NOT (Color LIKE “*red*”) F T F or not and F not

DATABASE 18 Simple Computations OrderItem(OrderID, ItemID, Price, Quantity) Select OrderID, ItemID, Price, Quantity, Price*Quantity As Extended From OrderItem; Basic computations (+ - * /) can be performed on numeric data. The new display column should be given a meaningful name. OrderIDItemIDPriceQuantityExtended

DATABASE 19 Computations: Example--Avg  What is the average sale price of all animals? SELECT Avg(SalePrice) AS AvgOfSalePrice FROM SaleAnimal;  Sum  Avg  Min  Max  Count  StDev  Var Query04_04

DATABASE 20 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  SELECT Sum([Quantity]*[Cost]) AS OrderTotal FROM OrderItem WHERE (PONumber=22); Query04_05

DATABASE 21 Subtotals (Where)  How many cats are in the Animal list? SELECTCount(AnimalID) AS CountOfAnimalID FROMAnimal WHERE(Category = “Cat”); Query04_06

DATABASE 22 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;  CategoryCountOfAnimalID  Dog100  Cat47  Bird15  Fish14  Reptile6  Mammal6  Spider3 Query04_07

DATABASE 23 Conditions on Totals (Having)  Count number of Animals in each Category, but only list them if more than 10.  CategoryCountOfAnimal  Dog100  Cat47  Bird15  Fish14 SELECTCategory, Count(AnimalID) AS CountOfAnimalID FROMAnimal GROUP BYCategory HAVINGCount(AnimalID) > 10 ORDER BYCount(AnimalID) DESC; Query04_08

DATABASE 24 Where (Detail) v Having (Group)  Count Animals born after 6/1/98 in each Category, but only list Category if more than 10. CategoryCountOfAnimalID  Dog30  Cat18 SELECTCategory, Count(AnimalID) AS CountOfAnimalID FROMAnimal WHEREDateBorn > #6/1/98# GROUP BYCategory HAVINGCount(AnimalID) > 10 ORDER BYCount(AnimalID) DESC; Query04_09

DATABASE 25 Multiple Tables (Intro & Distinct)  List the CustomerID of everyone who bought something between 4/1/98 and 5/31/98.  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 #4/1/98# And #5/31/98#) ORDER BY CustomerID; Avoid Duplicates with DISTINCT Query04_10

DATABASE 26 Joining Tables  List LastNames of Customers who bought between 4/1/98 and 5/31/98.  CustomerIDLastName  22Adkins  57Carter  38Franklin  42Froedge  63Grimes  74Hinton  36Holland  6Hopkins  50Lee  58McCain  37McPherson  90Nichols  14Patterson  8Reid  28Samuels  80Vance  39Williams  24Young  19Zhang SELECT DISTINCT Sale.CustomerID, Customer.LastName FROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID WHERE (Sale.SaleDate Between #4/1/98# And #5/31/98#) ORDER BY Customer.LastName; Query04_11

DATABASE 27 SQL JOIN FROM table1 INNER JOIN table2 ON table1.column = table2.column FROM table1, table2 JOIN table1.column = table2.column SQL 92 syntax Informal syntax FROM table1, table2 WHERE table1.column = table2.column SQL 89 syntax

DATABASE 28 Multiple Tables (Many)  List the Last Name and Phone of anyone who bought a registered White cat between 6/1/98 and 12/31/ 98. 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 #6/1/98# And #12/31/98#)); Query04_12

DATABASE 29 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. 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.

DATABASE 30 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.

DATABASE 31 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.

DATABASE Table Alias SIDSupplier.CityIDCity.CityEIDLastNameEmployee.CityIDCity2.City 47972Middlesboro5James7083Orlando Springfield1Reeves9201Lincoln 47972Middlesboro3Reasoner8313Springfield Columbia8Carpenter10592Philadelphia Smyrna3Reasoner8313Springfield 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 ((City AS City2 INNER JOIN Employee ON City2.CityID = Employee.CityID) INNER JOIN AnimalOrder ON Employee.EmployeeID = AnimalOrder.EmployeeID) ON Supplier.SupplierID = AnimalOrder.SupplierID;

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

DATABASE 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)

DATABASE Non Updateable View OrderItem(OrderID, ItemID, Quantity)Item(ItemID, Description) OrderLine(OrderID, Item.ItemID, Description, Quantity) Cat food 58Dog food 59Bird food 12157Cat food Bird feeder Cat food1 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