Jerry Post Copyright © 2003 1 Database Management Systems Chapter 5 Advanced Queries.

Slides:



Advertisements
Similar presentations
1 All Powder Board and Ski Microsoft Access Workbook Chapter 5: Advanced Queries Jerry Post Copyright © 2007.
Advertisements

1 Materi Pendukung Pertemuan > Transaksi pendukung pada SQL Matakuliah: >/ > Tahun: > Versi: >
COMP 3715 Spring 05. Working with data in a DBMS Any database system must allow user to  Define data Relations Attributes Constraints  Manipulate data.
Database Systems: Design, Implementation, and Management Tenth Edition
1 Copyright © 2010 Jerry Post with additions & narration by M. E. Kabay. All rights reserved. Advanced Queries IS240 – DBMS Lecture # 8 – M.
Introduction to Structured Query Language (SQL)
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
5 Chapter 5 Structured Query Language (SQL2) Revision.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
30-Jun-15 SQL A Brief Introduction. SQL SQL is Structured Query Language Some people pronounce SQL as “sequel” Other people insist that only “ess-cue-ell”
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
SQL Query Extras MIS 433. Rerunning the last Query n Type the forward slash “/” to rerun the last query that was entered.
INFORMATION TECHNOLOGY IN BUSINESS AND SOCIETY SESSION 16 – SQL SEAN J. TAYLOR.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Jerry Post Copyright © 2013 DATABASE Database Management Systems Chapter 5 Advanced Queries 1.
Introduction to SQL J.-S. Chou Assistant Professor.
Chapter 3 Query Language Database Application SAK 3408.
Introduction to Databases Chapter 7: Data Access and Manipulation.
Chapter 4 Querying Based on G. Post, DBMS: Designing & Building Business Applications University of Manitoba Asper School of Business 3500 DBMS Bob Travica.
Jerry Post Copyright © Database Management Systems Chapter 5 Advanced Queries.
Chapter 5 Advanced Querying
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
1 All Powder Board and Ski Oracle 9i Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2003.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
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
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
Jerry Post Copyright © Database Management Systems Chapter 5 Advanced Queries.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
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.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
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.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
School of Computer & Communication of LNPU 辽宁石油化工大学计算机与通信工程学院 刘旸 1 数据库管理系统 Database Management Systems Chapter5 Advanced Queries 第五章 高级查询和子查询.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
1 MySQL and SQL. 2 Topics  Introducing Relational Databases  Terminology  Managing Databases MySQL and SQL.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
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.
 CONACT UC:  Magnific training   
LEC-8 SQL. Indexes The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Chapter 5 Introduction to SQL.
Queries: Part 1 of 2 IS240 – DBMS Lecture # 6 –
M. E. Kabay, PhD, CISSP-ISSMP V:
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
All Powder Board and Ski
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Chapter 7 Introduction to Structured Query Language (SQL)
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Presentation transcript:

Jerry Post Copyright © Database Management Systems Chapter 5 Advanced Queries

DATABASE 2 Tables

DATABASE 3 Organization  Harder Questions  Subqueries  Not In, LEFT JOIN  UNION, Multiple JOIN columns, Recursive JOIN  Other SQL Commands  DDL: Data Definition Language  DML: Data Manipulation Language  OLAP  Microsoft SQL Server  Oracle  Microsoft Access Crosstab

DATABASE 4 Harder Questions  How many cats are “in- stock” on 10/1/04?  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/04 and 12/31/04?  Which customers who bought Dogs also bought products for Cats (at any time)?

DATABASE 5 Sub-query for Calculation  Which cats sold for more than the average sale price of cats?  Assume we know the average price is $170.  Usually we need to compute it first. SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePrice FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE ((Animal.Category=‘Cat’) AND (SaleAnimal.SalePrice>170)); SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePrice FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE ((Animal.Category=‘Cat’) AND (SaleAnimal.SalePrice> (SELECT AVG(SalePrice) FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE (Animal.Category=‘Cat’) ) ) );

DATABASE 6 Query Sets (IN) List all customers (Name) who purchased one of the following items: 1, 2, 30, 32, 33. SELECT Customer.LastName, Customer.FirstName, SaleItem.ItemID FROM (Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID) INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID WHERE (SaleItem.ItemID In (1,2,30,32,33)) ORDER BY Customer.LastName, Customer.FirstName; Query04_13 SaleID SaleDate EmployeeID CustomerID FieldLastNameFirstNameItemID TableCustomer SaleItem SortAscending CriteriaIn (1,2,30,32,33) Or CustomerID Phone FirstName LastName SaleCustomer SaleID ItemID Quantity SalePrice SaleItem

DATABASE 7 Using IN with a Sub-query  List all customers who bought items for cats. SELECT Customer.LastName, Customer.FirstName, SaleItem.ItemID FROM (Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID) INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID WHERE (SaleItem.ItemID In (SELECT ItemID FROM Merchandise WHERE Category=‘Cat’) );

DATABASE 8 SubQuery (IN: Look up a Set) List all of the customers who bought something in March and who bought something in May. (Two tests on the same data!) LastNameFirst AdkinsInga McCainSam GrimesEarl SELECT Customer.LastName, Customer.FirstName FROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID WHERE ((Month([SaleDate])=3)) And Customer.CustomerID In (SELECT CustomerID FROM Sale WHERE (Month([SaleDate])=5) ); Query04_14 SaleID SaleDate EmployeeID CustomerID FieldLastNameFirstNameMonth(SaleDate)CustomerID TableCustomer SaleCustomer SortAscending Criteria3In (SELECT CustomerID FROM State WHERE (Month(SaleDAte)=5) Or CustomerID Phone FirstName LastName SaleCustomer

DATABASE 9 SubQuery (ANY, ALL)  Any: value is compared to each item in the list. If it is True for any of the items, the statement is evaluated to True.  All: value is compared to each item in the list. If it is True for every item in the list, the statement is evaluated to True (much more restrictive than any. SELECT Animal.AnimalID, Name, SalePrice, ListPrice FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE ((SalePrice > Any (SELECT 0.80*ListPrice FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE Category = ‘Cat’)) AND (Category=‘Cat’); Query04_15

DATABASE 10 SubQuery: NOT IN (Subtract)  Which animals have not been sold?  Start with list of all animals.  Subtract out list of those who were sold. AnimalIDNameCategory 12LeishaDog 19GeneDog 25VivianDog 34RhondaDog 88BrandyDog 181Fish SELECT Animal.AnimalID, Animal.Name, Animal.Category FROM Animal WHERE (Animal.AnimalID Not In (SELECT AnimalID From SaleAnimal)); Query04_16 FieldAnimalIDNameCategory TableAnimal Sort CriteriaNot In (SELECT AnimalID FROM SaleAnimal) Or AnimalID Name Category Breed Animal

DATABASE 11 SubQuery: NOT IN (Data) IDNameCategoryBreed 2FishAngel 4GaryDogDalmation 5FishShark 6RosieCatOriental Shorthair 7EugeneCatBombay 8MirandaDogNorfolk Terrier 9FishGuppy 10SherriDogSiberian Huskie 11SusanDogDalmation 12LeishaDogRottweiler IDSaleIDSalePrice 235$ $ $ $ $ $ $ AnimalSaleAnimal Which animals have not been sold?

DATABASE 12 Left Outer Join  Which animals have not been sold?  LEFT JOIN includes all rows from left table (Animal)  But only those from right table (SaleAnimal) that match a row in Animal.  Rows in Animal without matching data in Sale Animal will have Null. SELECT Animal.AnimalID, Animal.Name, Animal.Category FROM Animal LEFT JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE (SaleAnimal.SaleID Is Null); AnimalIDNameCategory 12LeishaDog 19GeneDog 25VivianDog 34RhondaDog 88BrandyDog 181Fish Query04_17 SaleID AnimalID SalePrice FieldAnimalIDSaleIDNameCategory TableAnimalSaleAnimalAnimal Sort CriteriaIs Null Or AnimalID Name Category Breed SaleAnimalAnimal

DATABASE 13 Left Outer Join (Example) IDNameCategoryBreed 2FishAngel 4GaryDogDalmation 5FishShark 6RosieCatOriental Shorthair 7EugeneCatBombay 8MirandaDogNorfolk Terrier 9FishGuppy 10SherriDogSiberian Huskie 11SusanDogDalmation 12LeishaDogRottweiler IDSaleIDSalePrice 235$ $ NullNullNull 627$ $ $ NullNullNull 1018$ $ NullNullNull

DATABASE 14 Older Syntax for Left Join  Which animals have not been sold? SELECT ALL FROM Animal, SaleAnimal WHERE Animal.AnimalID *= SaleAnimal.AnimalID And SaleAnimal.SaleID Is Null; SELECT ALL FROM Animal, SaleAnimal WHERE Animal.AnimalID = SaleAnimal.AnimalID (+) And SaleAnimal.SaleID Is Null; Old Oracle syntax— note that the (+) symbol is on the reversed side.

DATABASE 15 SubQuery for Computation  Don’t know the average, so use a subquery to look it up.  Watch parentheses. Query04_18 SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePrice FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE ((Animal.Category=‘Cat’) AND (SaleAnimal.SalePrice> (SELECT AVG(SalePrice) FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE (Animal.Category=‘Cat’) ) ) ); SaleID AnimalID SalePrice FieldAnimalIDNameCategorySalePrice TableAnimal SaleAnimal SortDescending Criteria3> (SELECT Avg(SalePrice) FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE Animal.Category = ‘Cat’) Or AnimalID Name Category Breed SaleAnimalAnimal

DATABASE 16 Correlated Subquery SELECT AnimalID, Name, Category, SalePrice FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE (SaleAnimal.SalePrice> (SELECT Avg(SaleAnimal.SalePrice) FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE (Animal.Category = Animal.Category) ) ) ORDER BY SaleAnimal.SalePrice DESC;  List the Animals that have sold for a price higher than the average for animals in that Category.  The subquery needs to compute the average for a given category.  Problem: Which category?  Answer: the category that matches the category from the main part of the query.  Problem: How do we refer to it? Both tables are called Animal. This query will not work yet.

DATABASE 17 Correlated SubQuery (Avoid) List the Animals that have sold for a price higher than the average for animals in that Category.  Match category in subquery with top level  Rename tables (As)  Correlated Subquery  Recompute subquery for every row in top level--slow!  Better to compute and save Subquery, then use in join. SELECT A1.AnimalID, A1.Name, A1.Category, SaleAnimal.SalePrice FROM Animal As A1 INNER JOIN SaleAnimal ON A1.AnimalID = SaleAnimal.AnimalID WHERE (SaleAnimal.SalePrice> (SELECT Avg(SaleAnimal.SalePrice) FROM Animal As A2 INNER JOIN SaleAnimal ON A2.AnimalID = SaleAnimal.AnimalID WHERE (A2.Category = A1.Category) ) ) ORDER BY SaleAnimal.SalePrice DESC; Query04_19

DATABASE 18 Correlated Subquery Problem Fish$10.80 Dog$ Fish$19.80 Cat$ Cat$ Dog$ Fish$1.80 Dog$ Dog$ CategorySalePrice Animal + SaleAnimal Compute Avg: $37.78 Compute Avg: $ Compute Avg: $37.78 Compute Avg: $ Recompute average for every row in the main query!  Assume small query  100,000 rows  5 categories of 20,000 rows  100,000 * 20,000 = 1 billion rows to read!

DATABASE 19 More Efficient Solution: 2 queries  Compute the averages once and save query  JOIN saved query to main query  Two passes through table: 1 billion / 200,000 => 10,000 Fish$10.80 Dog$ Fish$19.80 Cat$ Cat$ Dog$ Fish$1.80 Dog$ Dog$ CategorySalePrice Animal + SaleAnimal Bird$ Cat$ Dog$ Fish$37.78 Mammal$80.72 Reptile$ Spider$ CategoryAvgOfSalePrice Saved Query JOIN Animal.Category = Query1.Category

DATABASE 20 UNION Operator  Offices in Los Angeles and New York.  Each has an Employee table (East and West).  Need to search data from both tables.  Columns in the two SELECT lines must match. SELECT EID, Name, Phone, Salary, ‘East’ AS Office FROM EmployeeEast UNION SELECT EID, Name, Phone, Salary, ‘West’ AS Office FROM EmployeeWest EIDNamePhoneSalaryOffice 352Jones335245,000East 876Inez873647,000East 372Stoiko763238,000East 890Smythe980362,000West 361Kim773673,000West

DATABASE 21 UNION, INTERSECT, EXCEPT T1T2 ABC SELECT EID, Name FROM EmployeeEast INTERSECT SELECT EID, Name FROM EmployeeWest List the name of any employee who has worked for both the East and West regions.

DATABASE 22 Multiple JOIN Columns  Sometimes need to JOIN tables on more than one column.  PetStore: Category and Breed. AnimalID Name Category Breed DateBorn Gender... Category Breed Animal SELECT * FROM Breed INNER JOIN Animal ON Breed.Category = Animal.Category AND Breed.Breed = Animal.Breed

DATABASE 23 Reflexive Join  Need to connect a table to itself.  Common example: Employee(EID, Name,..., Manager)  A manager is also an employee.  Use a second copy of the table and an alias. SELECT Employee.EID, Employee.Name, Employee.Manager, E2.Name FROM Employee INNER JOIN Employee AS E2 ON Employee.Manager = E2.EID EIDName...Manager 115Sanchez Miller Hawk Munoz886 Employee EIDNameManagerName 115Sanchez765Munoz 462Miller115Sanchez 523Hawk115Sanchez SQL Result

DATABASE 24 Recursive Joins (SQL 99 and 200x) WITH RECURSIVE EmployeeList (EmployeeID, Title, Salary) AS ( SELECT EmployeeID, Title, 0.00 FROM Manages WHERE Title = “CEO”-- starting level UNION ALL SELECT Manages.EmployeeID, Manages.Title, Manages.Salary FROM EmployeeList INNER JOIN Manages ON EmployeeList.EmployeeID = Manages.ManagerID ) SELECT EmployeeID, Count(Title), Sum(Salary) FROM EmployeeList GROUP BY EmployeEID ; List all of the employees and list everyone who reports to them. Not yet supported by vendors. It provides tree spanning capabilities.

DATABASE 25 CASE Function  Used to change data to a different context.  Example: Define age categories for the animals.  Less than 3 months  Between 3 months and 9 months  Between 9 months and 1 year  Over 1 year Select AnimalID, CASE WHEN Date()-DateBorn < 90 Then “Baby” WHEN Date()-DateBorn >= 90 AND Date()-DateBorn < 270 Then “Young” WHEN Date()-DateBorn >= 270 AND Date()-DateBorn < 365 Then “Grown” ELSE “Experienced” END FROM Animal; Not available in Microsoft Access. It is in SQL Server and Oracle.

DATABASE 26 Inequality Join AR(TransactionID, CustomerID, Amount, DateDue)  AccountsReceivable  Categorize by Days Late  30, 90, 120+  Three queries?  New table for business rules LateCategory(Category, MinDays, MaxDays, Charge, …) Month30903% Quarter901205% Overdue % SELECT * FROM AR INNER JOIN LateCategory ON ((Date() - AR.DateDue) >= LateCategory.MinDays) AND ((Date() - AR.DateDue) < LateCategory.MaxDays)

DATABASE 27 SQL SELECT SELECT DISTINCT Table.Column {AS alias},... FROM Table/Query INNER JOIN Table/Query ON T1.ColA = T2.ColB WHERE (condition) GROUP BY Column HAVING (group condition) ORDER BY Table.Column { Union second select }

DATABASE 28 SQL Mnemonic Someone From Ireland Will Grow Horseradish and Onions SELECT FROM INNER JOIN WHERE GROUP BY HAVING ORDER BY SQL is picky about putting the commands in the proper sequence. If you have to memorize the sequence, this mnemonic may be helpful.

DATABASE 29 SQL Data Definition  Create Schema Authorization dbName password  Create Table TableName (Column Type,...)  Alter Table Table {Add, Column, Constraint, Drop}  Drop {Table Table | Index Index On table}  Create Index IndexName ON Table (Column {ASC|DESC})

DATABASE 30 Syntax Examples CREATE TABLE Customer (CustomerID INTEGER NOT NULL, LastName CHAR (10), more columns ); ALTER TABLE Customer DROP COLUMN ZipCode; ALTER TABLE Customer ADD COLUMN CellPhone CHAR(15);

DATABASE 31 Queries with “Every” Need EXISTS List the employees who have sold animals from every category. By hand: List the employees and the categories. Go through the SaleAnimal list and check off the animals they have sold.

DATABASE 32 Query With EXISTS List the Animal categories that have not been sold by an employee (#5). SELECT Category FROM Category WHERE (Category <> "Other") And Category NOT IN (SELECT Animal.Category FROM Animal INNER JOIN (Sale INNER JOIN SaleAnimal ON Sale.SaleID = SaleAnimal.SaleID) ON Animal.AnimalID = SaleAnimal.AnimalID WHERE Sale.EmployeeID = 5) If this query returns any rows, then the employee has not sold every animal. So list all the employees for whom the above query returns no rows: SELECT EmployeeID, LastName FROM Employee WHERE NOT EXISTS (above query slightly modified.)

DATABASE 33 Query for Every SELECT Employee.EmployeeID, Employee.LastName FROM Employee WHERE Not Exists (SELECT Category FROM Category WHERE (Category <> "Other") And Category NOT IN (SELECT Animal.Category FROM Animal INNER JOIN (Sale INNER JOIN SaleAnimal ON Sale.SaleID = SaleAnimal.SaleID) ON Animal.AnimalID = SaleAnimal.AnimalID WHERE Sale.EmployeeID = Employee.EmployeeID) ); Result: 3 Reasoner

DATABASE 34 Simpler Query for Every Sometimes it is easier to use Crosstab and the Count function. But some systems do not have Crosstab, and sometimes the lists would be too long. So you need to know both techniques.

DATABASE 35 SQL: Foreign Key CREATE TABLE Order (OrderID INTEGER NOT NULL, OrderDate DATE, CustomerID INTEGER CONSTRAINT pkorder PRIMARY KEY (OrderID), CONSTRAINT fkorder FOREIGN KEY (CustomerID) REFERENCES Customer (CustomerID) ); OrderID OrderDate CustomerID LastName FirstName Address … OrderCustomer *

DATABASE 36 SQL Data Manipulation Commands Insert Into target (column1...) VALUES (value1...) Insert Into target (column1...) SELECT... FROM... Delete From table WHERE condition Update table SET Column=Value,... Where condition Note the use of the Select and Where conditions. Synatx is the same--only learn it once. You can also use subqueries.

DATABASE 37 Copy Old Animal Data INSERT INTO OldAnimals SELECT * FROM Animal WHERE AnimalID IN (SELECT AnimalOrderItem.AnimalID FROM AnimalOrder INNER JOIN AnimalOrderItem ON AnimalOrder.OrderID = AnimalOrderItem.OrderID WHERE (AnimalOrder.OrderDate<’01-Jan-2004’) );

DATABASE 38 Delete Old Animal Data DELETE FROM Animal WHERE AnimalID IN (SELECT AnimalOrderItem.AnimalID FROM AnimalOrder INNER JOIN AnimalOrderItem ON AnimalOrder.OrderID = AnimalOrderItem.OrderID WHERE (AnimalOrder.OrderDate<’01-Jan-2004’) );

DATABASE 39 Update Example  Change the ListPrice of Animals at the PetStore.  For cats, increase the ListPrice by 10%.  For dogs, increase the ListPrice by 20%.  Typically use two similar UPDATE statements.  With the CASE function, the statements can be combined. UPDATE Animal SET ListPrice = ListPrice*1.10 WHERE Category = ‘Cat’ ; UPDATE Animal SET ListPrice = ListPrice*1.20 WHERE Category = ‘Dog’ ;

DATABASE 40 Quality: Building Queries  Break questions into smaller pieces.  Test each query.  Check the SQL.  Look at the data.  Check computations  Combine into subqueries.  Use cut-and-paste to avoid errors.  Check for correlated subqueries.  Test sample data.  Identify different cases.  Check final query and subqueries.  Verify calculations. Dogs and cat products on the same sale. Dogs and cat products at different times. Dogs and never any cat products. Cat products and never any Dogs. Which customers who bought Dogs also bought products for Cats (at any time)? Who bought dogs? Who bought cat products?  Test SELECT queries before executing UPDATE queries.

DATABASE 41 Quality Queries: Example Which customers who bought Dogs also bought products for Cats? SELECT DISTINCT Animal.Category, Sale.CustomerID FROM Sale INNER JOIN (Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID) ON Sale.SaleID = SaleAnimal.SaleID WHERE (((Animal.Category)=‘Dog’)) SELECT DISTINCT Sale.CustomerID FROM Sale INNER JOIN (Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID) ON Sale.SaleID = SaleItem.SaleID WHERE (((Merchandise.Category)=‘Cat’)) A. Which customers bought dogs? B. Which customers bought cat products? AND Sale.CustomerID IN ( );

DATABASE 42 Programming Review: Variables  Integer  2 bytes   Long  4 bytes  +/- 2,147,483,648  Single  4 bytes  +/ E 38  +/ E-45  Global, Const, Static  Double  8 bytes  +/ E 308  +/ E-324  Currency  8 bytes  +/- 922,337,203,685,  String & String*n  Variant  Any data type  Null

DATABASE 43 Programming: Scope and Lifetime  Scope  Where is the variable, and which procedures can access it?  Lifetime  When is the variable created, and when is it destroyed? Form--Module Code Sub Button1_Click() Dim i1 As Integer i1 = 3 End Sub Sub Button2_Click() Dim i1 As Integer i1 = 7 End Sub Form Button1 Button2 Different procedures, different variables. Created and destroyed each time the button is clicked.

DATABASE 44 Programming: Global Variables  Wider scope and lifetime  Created at a higher level Form Public module  Accessible to any procedure in that form or module.  Declare it Global to make it available to any procedure. Form--Module Code Sub Button2_Click() i2 = i2 + 7 End Sub Form Button1 Button2 Dim i2 As Integer Variable is created when form is opened. Clicking Button1 sets the initial value. Clicking Button2 modifies the value. What if user clicks buttons in a different order? Sub Button1_Click() i2 = 20 End Sub

DATABASE 45 Programming: Computations  Standard Math  + - * /  \ Integer divide  ^ Exponentiation (2^3 = 2*2*2 = 8)  Mod (15 Mod 4 = 3) ( = 15)  String  & Concatenation  Left, Right, Mid  Trim, LTrim, RTrim  String  Chr, Asc  LCase, UCase  InStr  Len  StrComp  Format “Frank” & “Rose”  “FrankRose” Left(“Jackson”,5)  “Jacks” Trim(“ Maria “)  “Maria” Len(“Ramanujan”)  9 String(5,”a”)  “aaaaa” InStr(“8764 Main”,” “)  5

DATABASE 46 Programming: Standard Functions  Numeric  Exp, Log  Atn, Cos, Sin, Tan  Sqr  Abs  Sgn  Int, Fix  Rnd, Randomize x = log e (e x ) Trigonometric functions  2 = Abs(-35)  35 Sgn(-35)  -1 Int(17.893)  17 Rnd()  ?  =30 92

DATABASE 47 Programming: Standard Functions: Date/Time  Date, Now, Time  DateAdd, DateDiff  “y”, “m”, “q”...  Firstweekday  1=Sunday,...  Can also be used to find number of Fridays, between two dates. todayDateDue 02/19/0403/21/04 DateDue = DateAdd(“d”, 30, Date())

DATABASE 48 Programming: Standard Functions: Variant  Variant  IsDate  IsNumeric  VarType  IsEmpty  IsNull

DATABASE 49 Programming: Debug  Stop  Ctrl-Break  F5: Go  F8: Step through  S-F8: Step over  Breakpoints  Immediate Window  ? or Print  Any assignment  Any code

DATABASE 50 Programming: Output: Message Box  MsgBox  Message  Type  Title  Types: Use Constants  vbOKOnlyvbOKCancel  vbAbortRetryIgnore  vbYesNoCancel  vbYesNovbRetryCancel  Defaults  vbDefaultButton1  vbDefaultButton2  vbDefaultButton3  Icons  vbCritical Stop sign  vbQuestion Question mark  vbExclamation Warning  vbInformation Circle i  Responses  vbOKvbCancel  vbAbortvbRetry  vbIgnore  vbYesvbNo MsgBox "This is a message box", vbYesNoCancel + vbInformation, "Sample Box"

DATABASE 51 Programming: Input: InputBox  InputBox  Prompt  Title  Default  X-Pos, Y-Pos  Prompt  Cannot change box size  Use Chr(10) & Chr(13) for blank lines.  Returns text or Variant  Cancel = zero string ““  Positions  Twips  Twentieth of inch point  72 points  1440 twips per inch Dim str As String str = InputBox( "Enter your name:", "Sample Input",, 5000, 5000)

DATABASE 52 Programming: Conditions  If  If (Condition) Then statements for true  Else statements for false  End If  IIF (Cond., True, False)  Select Case (expr)  Case value statements  Case value2  Case Else  End Select  Conditions , >=, =, <>  And, Or, Not, Xor  Eqv, Imp (logic) If (Condition1) Then statements for true Else statements for false If (Condition2) Then statements for true End If

DATABASE 53 Programming Select Example  Message Box  Could use repeated If statements  Better to use Select Case response = MsgBox(…) If (response == vbYes) Then ‘ statements for Yes Else If (response == vbNo) Then ‘ statements for No Else ‘statements for Cancel End If response = MsgBox(…) Select Case response Case vbYes ‘ statements for Yes Case vbNo ‘ statements for No Case vbCancel ‘ statements for Cancel End Case

DATABASE 54 Programming: Loops  Do  For … Next  For Each Do Until (x > 10) ‘ Statements x = x + 1 Loop Initialize value Statements Change value Test condition Do While (x <= 10) ‘ Statements x = x + 1 Loop Do ‘ Statements x = x + 1 Loop Until (x > 10) For x = 1 to 10 ‘ Statements Next x

DATABASE 55 Programming: Loops Again  Do  Do {While | Until} Exit Do (optional)  Loop  Do  Loop {While | Until}  For/Next  For counter = start To end Step increment Exit For (optional)  Next counter  For/Each (objects)  For Each element In group [Exit For] (optional)  Next element  With (objects)  With object  End With

DATABASE 56 Programming Subroutines and Functions  Sub name (var1 As..., var2,...)  End Sub  Function fname (var1 As...) As datatype  fname = … ‘ returns a specific value  End Function  Variables are passed by reference  Changes made to the parameters in the subroutine are passed back to the caller.  Unless you use ByVal  Changes are made to a copy of the parameter, but are not returned to the calling program.

DATABASE 57 Programming: Example Subroutine Main program … StatusMessage “Trying to connect.” … StatusMessage “Verifying access.” … End main program Sub StatusMessage (Msg As String) ‘ Display Msg, location, color End Sub

DATABASE 58 Programming: Parameter Types Main j = 3 DoSum j …‘ j is now equal to 8 Subroutine DoSum (j2 As Integer) j2 = 8 End Sub By Reference Changes to data in the subroutine are passed back. Main j = 3 DoSum j …‘ j is still equal to 3 Subroutine DoSum (ByVal j2 As Integer) j2 = 8 End Sub By Value Creates a copy of the variable, so changes are not returned.

DATABASE 59 Programming Arrays and User Types u Arrays l Dim array(sub,...) As type l Dim iSorts(10) As Integer u Specifying bounds: l (lower To upper,...) l ReDim [Preserve] array... l Option Base 0 | 1 l v 2.0 arrays less than 64KB u User defined types l Type Tname v ename1 As type v ename2 As type l End Type u Dim var1 As Tname u var1.ename1 =... u var1.ename2 =...

DATABASE 60 Programming: Financial Functions u Fixed payments l PV (rate, nper, pmt, fv, due) l FV (rate, nper, pmt, pv, due) l IPmt (rate, per, nper, pv, fv, due) l NPer (rate, pmt, pv, fv, due) l Pmt (rate, nper, pv, fv,due) l PPmt (rate, per, nper, pv, fv, due) l Rate (nper, pmt, pv, fv, due, guess) u rate interest rate per period u per specific period number u nper # of periods u pv present value u fv future value u due 0=due at end, 1=due at start u Arrays l NPV (rate, array) l IRR (array, guess) l MIRR (array, finrate, re_rate) u Depreciation l DDB (cost, salv, life, period) l SLN (cost, salvage, life) l SYD (cost, salv., life, period)

DATABASE 61 Programming: Text File Input/Output  Open filename As # file#  Close # file#, Reset  Print #,Put, Write  Spc, Tab  Get, Input #, Line Input #  EOF, LOF  Seek # file#, position  ChDir, ChDirve  Dir  Kill, (re)Name  Lock, Unlock  CurDir, MkDir, RmDir

DATABASE 62 OLE: Object Linking & Embedding  CreateObject (class)  “appname. objecttype”  GetObject (file, class)  Methods and syntax are defined by the software that exports the object.  Example  Dim obj As Object  set obj = CreateObject(“Word.Basic”)  obj.Bold  obj.Insert “text”  obj.SaveAs “file”

DATABASE 63 DDE: Dynamic Data Exchange  Shell  DDEInitiate  DDEExecute  DDEPoke, DDE Send  Send data  DDE, DDERequest  Request data  DDETerminate  Application must be running  Start a conversation/topic  Issue a command  Place data  Get data  Close the session