1 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Queries: Part 1 of 2 IS240 – DBMS Lecture # 6 – 2010-02-13 M. E. Kabay, PhD, CISSP-ISSMP.

Slides:



Advertisements
Similar presentations
The Relational Model and Normalization (1)
Advertisements

SQL IS 240 – Database Management Lecture #15 – Prof. M. E. Kabay, PhD, CISSP Norwich University
Copyright  Oracle Corporation, All rights reserved. 4 Aggregating Data Using Group Functions.
Microsoft Access 3 Database Creation and Management.
Concepts of Database Management Seventh Edition
Concepts of Database Management Sixth Edition
Concepts of Database Management Seventh Edition
Aggregating Data Using Group Functions. Objectives After completing this lesson, you should be able to do the following: Identify the available group.
5 Copyright © Oracle Corporation, All rights reserved. Aggregating Data Using Group Functions.
5 Copyright © Oracle Corporation, All rights reserved. Aggregating Data Using Group Functions.
Chapter 11 Group Functions (up to p.402)
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.
DATABASE APPLICATION DEVELOPMENT SAK 3408 Query Statements.
Chapter 2 Querying a Database
Jerry Post McGraw-Hill/Irwin Copyright © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. Database Management Systems Chapter 4 Data Queries.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
1.NET Web Forms Database Queries © 2002 by Jerry Post.
Microsoft Access 2010 Chapter 7 Using SQL.
1 Copyright © 2010 Jerry Post. All rights reserved. Introduction to DBMS IS240 – DBMS Lecture #2 – M. E. Kabay, PhD, CISSP-ISSMP Assoc. Prof.
Computer Science 101 Web Access to Databases SQL – Extended Form.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Download three SQL script files from wiki page.
Copyright © 2010 M. E. Kabay. All rights reserved. Analyzing and Building Simple Queries in SQL IS240 – Database Management Supplement to Chapter 4 M.
Jerry Post Copyright © Database Management Systems Chapter 4 Queries.
Concepts of Database Management, Fifth Edition
SQL 資料庫查詢語言 取材自 EIS, 3 rd edition By Dunn et al..
Chapter 3 Single-Table Queries
Microsoft Access 2010 Chapter 7 Using SQL. Change the font or font size for SQL queries Create SQL queries Include fields in SQL queries Include simple.
Chapter 4 Querying Based on G. Post, DBMS: Designing & Building Business Applications University of Manitoba Asper School of Business 3500 DBMS Bob Travica.
Microsoft Access 3 Database Creation and Management.
Chapter 5 Advanced Querying
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
 Agenda 2/20/13 o Review quiz, answer questions o Review database design exercises from 2/13 o Create relationships through “Lookup tables” o Discuss.
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.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Select your database – Your database name is.
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.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
STRUCTURED QUERY LANGUAGE SQL-II IST 210 Organization of Data IST210 1.
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.
Structured Query Language SQL Unit 2 An Introduction to Organizing and Retrieving Data with SQL.
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.
Structured Query Language SQL Unit 4 Solving Problems with SQL.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
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.
 Review quiz. Answer questions.  Discuss queries: ◦ What is a query? Turning data stored in a database into information for decision making. ◦ You: Completed.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
Jerry Post Copyright © Database Management Systems Chapter 4 Queries.
Paul A. Harris, Ph.D. Director, GCRC Informatics How to use query function in Microsoft Access.
Structured Query Language SQL-II IST 210 Organization of Data IST2101.
Southern Methodist University CSE CSE 2337 Introduction to Data Management Chapter 2.
1 Structured Query Language (SQL) Pertemuan 09 Matakuliah: F0712 / Lab MS Access Tahun: 2007.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
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.
Advanced Query Analysis
Queries: Part 1 of 2 IS240 – DBMS Lecture # 6 –
M. E. Kabay, PhD, CISSP-ISSMP V:
Advanced Queries in MS Access
Analyzing and Building Simple Queries in SQL
Aggregations Various Aggregation Functions GROUP BY HAVING.
Chapter 4 Summary Query.
Joins and other advanced Queries
Shelly Cashman: Microsoft Access 2016
Presentation transcript:

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 Assoc. Prof. Information Assurance School of Business & Management, Norwich University V:

2 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Topics  Why do we Need Queries  Four Questions to Create a Query  Query By Example & SQL  Boolean Algebra  DeMorgan’s Law  SQL Server Views  Simple Computations  SQL Differences  Groups and Subtotals  Where (Detail) v Having (Group)  Student Databases from Website  HOMEWORK

3 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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

4 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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?

5 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Tables

6 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Organization  Single table  Constraints  Computations  Groups/Subtotals  Multiple Tables

7 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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?

8 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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 Or Like ‘%Yellow%’Criteria Sort Animal Table ColorBreedCategoryAnimalIDField What tables? What conditions? List all animals with yellow in their color

9 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Basic SQL SELECT SELECTcolumnsWhat do you want to see? FROMtablesWhat tables are involved? JOINconditionsHow are the tables joined? WHEREcriteriaWhat are the constraints?

10 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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 Or Criteria Ascending Sort Animal Table BreedCategoryNameField

11 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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

12 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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 Color Animal FieldAnimalIDCategoryDateBornColor TableAnimal Sort Criteria‘Dog’>’01-Jun-2004’Like ‘%Yellow%’ Or

13 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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

14 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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. 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 Always use parentheses so other people can read and understand your query. It will also help you when you come back to one of your own queries later.

15 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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

16 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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 CAT: Registered=ASCF Color=Black 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." TF T F NOT ((Registered is NOT NULL) OR (Color LIKE ‘%Red%’)) (Registered is NULL) AND NOT (Color LIKE ‘%Red%’) F T F or not and F not

17 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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%’) ) ) ); Query04_03 AnimalID Name Category Breed DateBorn Gender Animal FieldAnimalIDCategoryGenderRegisteredDateBornColor TableAnimal Sort Criteria‘Dog’‘Male’Is Not Null Or‘Dog’< ’01-Jun-2004’Like ‘%White%’

18 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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’)

19 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. SQL in MS-ACCESS View | Design View View | SQL View

20 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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

21 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Computations: Aggregation- -Avg What is the average sale price of all animals? SELECT Avg(SalePrice) AS AvgOfSalePrice FROM SaleAnimal; SaleID AnimalID SalePrice SaleAnimal FieldSalePrice TableSaleAnimal TotalAvg Sort Criteria Or Sum Avg Min Max Count StDev or StdDev Var

22 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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

23 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. SQL Differences

24 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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

25 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. 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; AnimalID Name Category Breed DateBorn Gender Animal FieldCategoryAnimalID TableAnimal TotalGroup ByCount SortDescending Criteria Or CategoryCountOfAnimalID Dog100 Cat47 Bird15 Fish14 Reptile6 Mammal6 Spider3

26 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Conditions on Totals (Having) Count number of Animals in each Category, but list Category only if more than 10 in that Category. 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

27 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Where (Detail) v Having (Group) Count Animals born after 6/1/2004 in each Category, but list Category only if more than 10 in that Category. 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

28 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Student Databases from Website

29 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. HOMEWORK REQUIRED  By Sun 28 Feb 2010 at 23:59  Study Chapter 4 pp thoroughly using SQ3R  Answer Review Questions 1-12 for yourself to be sure they all make sense to you and you can easily answer them later in quizzes  Download the PetStore2000.mdb or PetStore2002.mdb file (as appropriate for your system) from Jerry Post’s site  Create SQL code and the records you find to Ch 4 Sally’s Pet Store exercises 1-7 (there’s no way to learn SQL without actually using it).

30 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. HOMEWORK OPTIONAL  By Sun 28 Feb 2010 at 23:59  For extra credit, answer any of the questions in  Rolling Thunder Bicycles #26-35  Corner Med #51-70

31 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. DISCUSSION