Upload
amice-smith
View
220
Download
0
Embed Size (px)
Citation preview
Jerry PostCopyright © 2013
DATABASE
Database Management Systems
Chapter 5
Advanced Queries
1
2
Objectives
How can SQL be used to answer more complex questions? Why are some business questions more difficult than others? How do you find something that did not happen? How is a subquery used for IN and NOT IN conditions? What are the common uses for subqueries? What are correlated subqueries? What tricky problems arise and how do you handle them in
SQL? What are the SQL data definition commands? What SQL commands alter the data stored in tables? How do you know if your query is correct?
Tables
3
Organization
Harder Questions Not In, LEFT JOIN Subqueries UNION, Multiple JOIN columns, Recursive JOIN Other SQL Commands
DDL: Data Definition LanguageDML: Data Manipulation Language
OLAPMicrosoft SQL ServerOracleMicrosoft Access Crosstab
4
Harder Questions
Which items have not been sold? Which items were not sold in July 2013? Which cat merchandise sold for more than the average sale price of cat
merchandise? Compute the merchandise sales by category in terms of percentage of total sales. List all of the customers who bought something in March and who bought
something in May. (Two tests on the same data!). List dog merchandise with a list price greater than the sale price of the cheapest
cat product.
Has one salesperson made all of the sales on a particular day? Use Not Exists to list customers who have not bought anything. Which merchandise has a list price greater than the average sale price of
merchandise within that category? List all the managers and their direct reports. Convert age ranges into categories. Classify payments by number of days late. Which employees sold merchandise from every category? List customers who adopted dogs and also bought cat products.
5
LEFT JOIN Problem
6
Which merchandise items have not been sold?
ItemID Description1 Dog Kennel-Small2 Dog Kennel-Medium3 Dog Kennel-Large4 Dog Kennel-Extra Large5 Cat Bed-Small6 Cat Bed-Medium7 Dog Toy8 Cat Toy9 Dog Food-Dry-10 pound10 Dog Food-Dry-25 pound11 Dog Food-Dry-50 pound12 Cat Food-Dry-5 pound13 Cat Food-Dry-10 pound14 Cat Food-Dry-25 pound15 Dog Food-Can-Regular
SaleID ItemID4 14 366 206 217 57 197 408 118 168 3610 2310 2510 2610 27
SaleItem Merchandise
INNER JOIN is a filter that returns ONLY rows that exist in both tables.But SaleItem includes ONLY merchandise that HAS been sold.
LEFT JOIN Answer
7
Which merchandise items have not been sold?
SELECT Merchandise.ItemID, Merchandise.Description, SaleItem.SaleIDFROM MerchandiseLEFT JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemIDWHERE SaleItem.SaleID Is Null;
LEFT JOIN includes ALL rows from the table on the SQL left side and matching rows from the right-side table. RIGHT JOIN is similar.
ItemID Description1 Dog Kennel-Small10 Dog Food-Dry-25 pound11 Dog Food-Dry-50 pound12 Cat Food-Dry-5 pound13 Cat Food-Dry-10 pound14 Cat Food-Dry-25 pound15 Dog Food-Can-Regular
SaleID ItemID4 14 366 206 217 57 197 40
SaleItemMerchandise
Query05_Fig03
LEFT JOIN Query
8
Note: LEFT/RIGHT depends on the SQL statement (Merchandise LEFT JOIN SaleItem). It is NOT set by the order of the tables in the display.
LEFT JOIN Result
9
Query1
ItemID Description SaleID12 Cat Food-Dry-5 pound
13 Cat Food-Dry-10 pound
LEFT JOIN: Old Syntax
10
SELECT * (SQL Server)FROM Merchandise, SaleItemWHERE Merchandise.ItemID *= SaleItemID.ItemIDAnd SaleItem.SaleID Is Null
SELECT * (Oracle)FROM Merchandise, SaleItemWHERE Merchandise.ItemID = SaleItemID.ItemID (+)And SaleItem.SaleID Is Null
Note that Oracle’s plus sign is on the opposite side from what you would expect.You should not use this syntax for new queries. It is hard to read.But you will likely encounter older queries in your work that use this syntax, so you need to recognize it and understand it is a LEFT join.
IN Function
11
SELECT *FROM CustomerWHERE FirstName=N’Tim’ Or FirstName=N’David’ Or FirstName=N’Dale’;
SELECT *FROM CustomerWHERE FirstName IN (N’Tim’, N’David’, N’Dale’);
The IN function compares a column to a set of values.IN is easier to write. Items are joined with an “Or” condition.
Query05_Fig06aQuery05_Fig06b
Query Sets (IN)
12
SELECT * FROM Merchandise WHERE ItemID IN (1,2,3,4,5,6,7,8,9,10,11,14,15);
Query05_Fig07a
Field ItemID Description QuantityOnHand
Table Customer Customer SaleItem
Sort Ascending Ascending
Criteria
In (1,2,3,4,5,…)
Or
ItemIDDescriptionQuantityOnHandListPrice
Merchandise
List all merchandise with the ItemIDs of (1,2,3,4,5,6,7,8,9,10,11,14,15).
IN Condition as a JOIN
13
SELECT *FROM MerchandiseWHERE ItemID IN (SELECT ItemID FROM SaleItem);
Match ItemID values in the Merchandise table to those that were sold or listed in the SaleItem table.
Query05_Fig07b
NOT IN: Things that did not happen
14
Which merchandise items have not been sold?
Query05_Fig08
SELECT *FROM MerchandiseWHERE ItemID NOT IN (SELECT ItemID FROM SaleItem);
ItemID Description1 Dog Kennel-Small2 Dog Kennel-Medium3 Dog Kennel-Large4 Dog Kennel-Extra Large5 Cat Bed-Small6 Cat Bed-Medium7 Dog Toy8 Cat Toy9 Dog Food-Dry-10 pound10 Dog Food-Dry-25 pound11 Dog Food-Dry-50 pound12 Cat Food-Dry-5 pound13 Cat Food-Dry-10 pound14 Cat Food-Dry-25 pound15 Dog Food-Can-Regular
Merchandise
Think of taking the main list (Merchandise) and subtracting the items from the second list (SaleItem). Then display the ones that are left.
Not Sold Conditions (Date Subquery)
15
Which items were not sold in July 2013?
Query05_Fig09
SELECT *FROM MerchandiseWHERE ItemID NOT IN (SELECT ItemID FROM SaleItem INNER JOIN Sale ON Sale.SaleID=SaleItem.SaleID WHERE SaleDate BETWEEN ’01-JUL-2013’ AND ’31-JUL-2013’ );
Not Sold Conditions (Date LEFT JOIN--bad)
16
Which items were not sold in July 2013?
Query05_Fig10
SELECT Merchandise.*FROM Sale INNER JOIN (Merchandise LEFT JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID) ON Sale.SaleID = SaleItem.SaleIDWHERE SaleDate BETWEEN ’01-JUL-2013’ AND ’31-JUL-2013’;
Probably will not run and might not return desired results.To work, the query must filter the SaleItem rows FIRST, Then apply the LEFT JOIN.
Not Sold Conditions (Date LEFT JOIN--good)
17
Which items were not sold in July 2013?
JulyItems and Query05_Fig11
CREATE VIEW JulyItems ASSELECT Sale.SaleID, ItemIDFROM SaleINNER JOIN SaleItem ON Sale.SaleID=SaleItem.SaleIDWHERE SaleDate BETWEEN ’01-JUL-2013’ AND ’31-JUL-2013’;
SELECT Merchandise.*FROM MerchandiseLEFT JOIN JulyItems ON Merchandise.ItemID=JulyItems.ItemIDWHERE JulyItems.Sale Is Null;
The saved view forces the selection of July sale items to occur first.Then the LEFT JOIN applies those rows to the Merchandise table.
Subquery: Calculations 1
18
SELECT Merchandise.ItemID, Merchandise.Description, Merchandise.Category, SaleItem.SalePriceFROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemIDWHERE Merchandise.Category=N’Cat’ AND SaleItem.SalePrice > 9;
Query05_Fig12a
Which cat merchandise sold for more than the average sale price of cat merchandise?
If you know (guess) that the average price of cat merchandise is 9; then the query is easy.So write the easy part first.
Subquery: Calculations 2
19
Query05_Fig12b
SELECT Merchandise.ItemID, Merchandise.Description, Merchandise.Category, SaleItem.SalePriceFROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemIDWHERE Merchandise.Category=N’Cat’ AND SaleItem.SalePrice > 9;
Which cat merchandise sold for more than the average sale price of cat merchandise?
SELECT Merchandise.ItemID, Merchandise.Description, Merchandise.Category, SaleItem.SalePriceFROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemIDWHERE Merchandise.Category=N’Cat’ AND SaleItem.SalePrice > (SELECT Avg(SaleItem.SalePrice) AS AvgOfSalePrice FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID WHERE Merchandise.Category=N’Cat’);
Subquery Calculation Notes
20
When building subqueries that use calculations:1. Write the query using a simple number.2. Write the subquery separately to compute the desired number. Test it!3. Isolate the original estimated number in the first query by putting it on a
separate line.4. Delete the number and add parentheses ( ).5. Paste the subquery inside the parentheses.
Subquery for Percentages
21
Query05_Fig13
Compute the merchandise sales by category in terms of percentage of total sales.
SELECT Merchandise.Category, Sum([Quantity]*[SalePrice]) AS [Value], Sum([Quantity]*[SalePrice])/(SELECT Sum([Quantity]*[SalePrice]) FROM SaleItem) As [Pct]FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemIDGROUP BY Merchandise.Category;
Category Value PercentageBird $631.50 7.45063292035315E-02Cat $1,293.30 0.152587546411603Dog $4,863.49 0.573809638983505Fish $1,597.50 0.188478006179955Mammal $90.00 1.06184792214059E-02
Percentages with JOIN using Views
22
SELECT Category, Value, Value/MainTotal AS PercentageFROM CategorySubtotals, TotalItemSales;
Save the first view that computes subtotals.Create a second view to compute totals.Compute the percentages in a third query using a cross join.
CREATE VIEW TotalItemSales ASSELECT Sum(Value) AS MainTotalFROM CategorySubtotals;
Query05_Fig14
CREATE VIEW CategorySubtotals ASSELECT Category, Sum(Quantity*SalePrice) AS ValueFROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemIDGROUP BY Merchandise.Category;
Sets of Data
23
List all of the customers who bought something in March and in May.
Try answering this question the “easy” but wrong way.
Query05_Fig15
SELECT Customer.CustomerID, Customer.Phone, Customer.LastName, Sale.SaleDateFROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerIDWHERE Sale.SaleDate Between ’01-MAR-2013’ And ’31-MAR-2013’ AND Sale.SaleDate Between ’01-MAY-2013’ And ’31-MAY-2013’;
The WHERE clause checks the date on each row to see if it fall in March AND in May. But no date can be in two months!
Two Sets using Subquery
24
SELECT Customer.LastName, Customer.FirstNameFROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerIDWHERE (SaleDate Between ’01-MAR-2013’ And ‘31-MAR-2013’)AND Customer.CustomerID IN (SELECT CustomerID FROM Sale WHERE (SaleDate Between ‘01-MAY-2013’ And ’31-MAY-2013’) );
List all of the customers who bought something in March and in May.
Query05_Fig16
Customers in March and customers in May are two separate sets of data. Two separate SELECT statements are needed to answer the question.This query combines those sets using a subquery.
25
Two Sets of Data Using JOIN
CREATE VIEW MarchCustomers ASSELECT CustomerIDFROM SaleWHERE (SaleDate Between ‘01-MAR-2013’ And ‘31-MAR-2013’);
CREATE VIEW MayCustomers ASSELECT CustomerIDFROM SaleWHERE (SaleDate Between ‘1-MAY-2013’ And ‘31-MAY-2013’);
SELECT Customer.LastName, Customer.FirstNameFROM Customer INNER JOIN MarchCustomers ON Customer.CustomerID=MarchCustomers.CustomerIDINNER JOIN MayCustomers ON MarchCustomers.CustomerID=MayCustomers.CustomerID;
Subquery: Any
26
Query05_Fig18
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. Probably easier to use MIN function in the subquery.
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.
List dog merchandise with a list price greater than the sale price of the cheapest cat product.
SELECT Merchandise.ItemID, Merchandise.Description, Merchandise.Category, Merchandise.ListPriceFROM MerchandiseWHERE Category=N'Dog‘ AND ListPrice > ANY (SELECT SalePrice FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID=SaleItem.ItemID WHERE Merchandise.Category=N'Cat');
Subquery: All
27
Query05_Fig19
Has one salesperson made all of the sales on a particular day (Mar 28)?
SELECT Employee.EmployeeID, Employee.LastNameFROM EmployeeWHERE EmployeeID = ALL (SELECT EmployeeID FROM Sale WHERE SaleDate = #28-MAR-2013#);
ID LastName2 Gibson
Returns a match only if the employee made all of the sales on the specified date. (Or if there were no sales—all null values—on that date.)
Subquery: Exists
28
Use Not Exists to list customers who have not bought anything.
SELECT Customer.CustomerID, Customer.Phone, Customer.LastNameFROM CustomerWHERE NOT EXISTS (SELECT SaleID, SaleDate FROM Sale WHERE Sale.CustomerID=Customer.CustomerID);
EXISTS tests for the existence of rows in the subquery. The subquery can contain multiple columns because none of the returned values matter—only whether any values match the WHERE clause.
This example is better if you use a JOIN command, but it works and illustrates the Exists term.
Query05_Fig20
Correlated Subquery
29
Query05_Fig21
Which merchandise has a list price greater than the average sale price of merchandise within that category?
SELECT Merchandise1.ItemID, Merchandise1.Description, Merchandise1.Category, Merchandise1.ListPriceFROM Merchandise AS Merchandise1 WHERE Merchandise1.ListPrice>(SELECT Avg(SaleItem.SalePrice) AS AvgOfSalePriceFROM Merchandise As Merchandise2 INNER JOIN SaleItem ON Merchandise2.ItemID = SaleItem.ItemIDWHERE Merchandise2.Category=Merchandise1.Category);
The WHERE clause in the subquery depends on values in the outer query. The tables require aliases to tell them apart.
Correlated Subquery Potential Problem
30
Assume small query 100,000 rows 5 categories of 20,000 rows
100,000 * 20,000 = 1 billion rows to read!
1 Dog $45.002 Dog $65.003 Dog $85.004 Dog $110.005 Cat $25.006 Cat $35.007 Dog $4.008 Cat $3.009 Dog $7.50
Merchandise
Compute Avg: $23.32Compute Avg: $23.32Compute Avg: $23.32Compute Avg: $23.32Compute Avg: $8.99Recompute average for every row in the main query!
MerchID Category ListPrice
More Efficient Solution: 2 queries
31
Compute the averages once and save query JOIN saved query to main query Two passes through table: 1 billion / 200,000 => 10,000
Bird $37.60Cat $8.99Dog $23.32Fish $38.18Mammal $9.00
Category AvgOfSalePrice
Saved Query
JOIN
Merchandise.Category = Query05_Fig23a.Category
Query05_Fig23a
1 Dog $45.002 Dog $65.003 Dog $85.004 Dog $110.005 Cat $25.006 Cat $35.007 Dog $4.008 Cat $3.009 Dog $7.50
Merchandise
MerchID Category ListPrice
Uncorrelated Queries
32
SELECT Merchandise.ItemID, Merchandise.Category, Merchandise.ListPrice, Query05_Fig23a.AvgOfSalePriceFROM Query05_Fig23a INNER JOIN Merchandise ON Query05_Fig23a.Category = Merchandise.CategoryWHERE Merchandise.ListPrice>[Query05_Fig23a].[AvgOfSalePrice];
SELECT Merchandise.Category, Avg(SaleItem.SalePrice) AS AvgOfSalePriceFROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemIDGROUP BY Merchandise.Category;
Query05_Fig23b
UNION Operator
33
SELECT EID, Name, Phone, Salary, ‘East’ AS OfficeFROM EmployeeEastUNIONSELECT EID, Name, Phone, Salary, ‘West’ AS OfficeFROM EmployeeWest
EID Name Phone Salary Office352 Jones 3352 45,000 East876 Inez 8736 47,000 East372 Stoiko 7632 38,000 East
890 Smythe 9803 62,000 West361 Kim 7736 73,000 West
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.
UNION, INTERSECT, EXCEPT
34
T1 T2
A B C
SELECT EID, NameFROM EmployeeEastINTERSECTSELECT EID, NameFROM EmployeeWest
List the name of any employee who has worked for both the East and West regions.
T1 UNION T2 A + B + C
T1 INTERSECT T2 B
T1 EXCEPT T2 AMicrosoft Access supports only UNION.SQL Server supports all three.
Multiple JOIN Columns
35
AnimalIDNameCategoryBreedDateBornGender. . .
CategoryBreed
Breed
Animal
SELECT *FROM Breed INNER JOIN AnimalON Breed.Category = Animal.CategoryAND Breed.Breed = Animal.Breed
Query05_Fig26
Sometimes need to JOIN tables on more than one column.PetStore: Category and Breed.
Reflexive Join
36
SELECT Employee.EmployeeID, Employee.LastName, Employee.ManagerID, E2.LastName
FROM Employee INNER JOIN Employee AS E2
ON Employee.ManagerID = E2.EmployeeID
EID Name . . . Manager1 Reeves 112 Gibson 13 Reasoner 14 Hopkins 3
Employee
EID Name Manager Name1 Reeves 11 Smith2 Gibson 1 Reeves3 Reasoner 1 Reeves
SQL
Result
Query05_Fig20
Need to connect a table to itself.Common example: Employee(EID, LastName, . . ., ManagerID)A manager is also an employee.Use a second copy of the table and an alias.
37
Recursive Joins (SQL 99 and 2003)
WITH RECURSIVE EmployeeList (EmployeeID, Title, Salary) AS( SELECT EmployeeID, Title, 0.00FROM Manages WHERE Title = N‘CEO’ -- starting levelUNION ALLSELECT Manages.EmployeeID, Manages.Title, Manages.SalaryFROM EmployeeList INNER JOIN ManagesON EmployeeList.EmployeeID = Manages.ManagerID )
SELECT EmployeeID, Count(Title), Sum(Salary)FROM EmployeeListGROUP BY EmployeEID ;
List all of the managers and list everyone who reports to them.
Available in higher-end systems (SQL Server, Oracle, DB2, etc.), but each vendor uses a different, proprietary syntax. See the Workbooks.
It provides tree spanning capabilities.
Not available in Microsoft Access. Variations are in SQL Server and Oracle.
38
Recursive JOIN: SQL Server
WITH DirectReports(EmployeeID, LastName, ManagerID, Title, Level) AS(
--Root/anchor member (find employee with no manager)SELECT EmployeeID, LastName, ManagerID, Title, 0 As LevelFROM Employee WHERE ManagerID=0 -- starting levelUNION ALL-- Recursive membersSELECT Employee.EmployeeID, Employee.LastName,
Employee.ManagerID, Employee.Title, Level +1FROM Employee INNER JOIN DirectReportsON Employee.ManagerID = DirectReports.EmployeeID
)-- Now execute the common table expressionSELECT ManagerID, EmployeeID, LastName, Title, LevelFROM DirectReportsORDER BY Level, ManagerID, LastName
Recursive Query Results
ManagerID EmployeeID
LastName Title Level
0 11 Smith Owner 0
11 1 Reeves Manager 1
1 2 Gibson Manager 2
1 3 Reasoner Manager 2
2 6 Eaton Animal Friend
3
2 7 Farris Animal Friend
3
2 5 James Animal Friend
3
2 9 O’Connor Animal Friend
3
2 10 Shields Animal Friend
3
3 8 Carpenter Worker 3
3 4 Hopkins Worker 339
CASE Function
40
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’
ENDFROM Animal;
Not available in Microsoft Access. It is in SQL Server and Oracle.
Example: Define age categories for the animals.Less than 3 monthsBetween 3 months and 9 monthsBetween 9 months and 1 yearOver 1 year
Convert age ranges into categories.
Inequality Join
41
AR(TransactionID, CustomerID, Amount, DateDue)
LateCategory(Category, MinDays, MaxDays, Charge, …)
Month 30 90 3%Quarter 90 120 5%Overdue 120 9999 10%
SELECT *FROM AR INNER JOIN LateCategory ON ((Date() - AR.DateDue) >= LateCategory.MinDays) AND ((Date() - AR.DateDue) < LateCategory.MaxDays)
AccountsReceivableCategorize by Days Late
30, 90, 120+Three queries?New table for business rules
Classify payments by number of days late.
Queries with “Every” Need EXISTS
42
List the employees who have sold animals from every category.Bird Cat Dog Fish Mammal Reptile Spider
1. Reeves x2. Gibson x x x x x x3. Reasoner x x x x x x x4. Hopkins x x x x5. J ames6. Eaton7. Farris8. Carpenter9. O’Connor10. Shields11. Smith
By hand: List the employees and the categories. Go through the SaleAnimal list and check off the animals they have sold.
Query With EXISTS
43
List the Animal categories where merchandise has not been sold by an employee (#5).
SELECT CategoryFROM Category WHERE (Category <> 'Other') And Category NOT IN (SELECT Merchandise.Category FROM Merchandise INNER JOIN (Sale INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID) ON Merchandise.ItemID = SaleItem.ItemID 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.)
Query05_Fig31
44
Query for EveryQuery05_Fig32
SELECT Employee.EmployeeID, Employee.LastNameFROM EmployeeWHERE Not Exists (SELECT Category FROM Category WHERE (Category NOT IN (‘Other’, ‘Reptile’, ‘Spider’) And Category NOT IN (SELECT Merchandise.Category FROM Merchandise INNER JOIN (Sale INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID) ON Merchandise.ItemID = SaleItem.ItemID WHERE Sale.EmployeeID = Employee.EmployeeID) ); EmployeeID LastName
2 Gibson3 Reasoner5 James7 Farris
Which employees have merchandise sales from every category?
45
Simpler Query for Every
Sometimes it is easier to use Crosstab and the Count function.
But some systems do not have Crosstab, and sometimes thelists would be too long. So you need to know both techniques.
Query05_Fig33
EID LastName Bird Cat Dog Fish Mammal
1 Reeves 4 15 6 2 Gibson 1 25 24 9 23 Reasoner 2 9 26 5 24 Hopkins 3 21 33 5 James 3 7 8 11 26 Eaton 1 2 8 17 Farris 1 4 24 1 18 Carpenter 3 1 11 5 9 O'Connor 5 10 3 110 Shields 1 5 11 Smith 1
SQL SELECT
46
SELECT DISTINCT Table.Column {AS alias} , . . .FROM Table/Query{INNER or LEFT} JOIN Table/Query ON T1.ColA = T2.ColBWHERE (condition)GROUP BY ColumnHAVING (group condition)ORDER BY Table.Column{ Union second select }
SQL Mnemonic
47
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.
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})
48
Syntax Examples
49
CREATE TABLE Customer
(CustomerID INTEGER NOT NULL,
LastName VARCHAR (20),
more columns
);
ALTER TABLE Customer
DROP COLUMN ZipCode;
ALTER TABLE Customer
ADD COLUMN CellPhone CHAR(15);
SQL: Foreign Key
50
CREATE TABLE Order
(OrderID INTEGER NOT NULL,
OrderDate DATE,
CustomerID INTEGER
CONSTRAINT pkorder PRIMARY KEY (OrderID),
CONSTRAINT fkorder FOREIGN KEY (CustomerID)
REFERENCES Customer (CustomerID)
);
OrderIDOrderDateCustomerID
CustomerIDLastNameFirstNameAddress…
Order Customer
*
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.
51
Copy Old Customer Data
52
INSERT INTO OldCustomersSELECT *FROM CustomerWHERE CustomerID IN
(SELECT Sale.CustomerID
FROM Customer
INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID
GROUP BY Sale.CustomerID
HAVING Max(Sale.SaleDate)<’01-Jul-2013’)
);
Delete Old Customer Data
53
DELETEFROM CustomerWHERE CustomerID IN
(SELECT Sale.CustomerID
FROM Customer
INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID
GROUP BY Sale.CustomerID
HAVING Max(Sale.SaleDate)<’01-Jul-2013’)
);
Update Example
54
UPDATE Merchandise
SET ListPrice = ListPrice*1.10
WHERE Category = N‘Cat’ ;
UPDATE Merchandise
SET ListPrice = ListPrice*1.20
WHERE Category = N‘Dog’ ;
Change the ListPrice of Merchandise 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.
55
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.
Test SELECT queries before executing UPDATE queries.
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 adopted Dogsalso bought products for Cats(at any time)?
Who adopted dogs?Who bought cat products?
56
Quality Queries: Example
Which customers who adopted Dogs also bought products for Cats?
SELECT DISTINCT Animal.Category, Sale.CustomerIDFROM Sale INNER JOIN Animal ON Animal.SaleID = Sale.SaleIDWHERE (Animal.Category='Dog')
AND Sale.CustomerID IN (
SELECT DISTINCT Sale.CustomerIDFROM Sale INNER JOIN (Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID) ON Sale.SaleID = SaleItem.SaleIDWHERE (Merchandise.Category='Cat')
);
A. Which customers adopted dogs?B. Which customers bought cat products?
Query05_Fig38
Programming Review: Variables
Integer 2 bytes -32768 32767
Long 4 bytes +/- 2,147,483,648
Single 4 bytes +/- 3.402823 E 38 +/- 1.401298 E-45
Global, Const, Static
Double 8 bytes +/- 1.79769313486232 E 308 +/- 4.94065645841247 E-324
Currency 8 bytes +/- 922,337,203,685,477.5808
String & String*n Variant
Any data type Null
57
Programming: Scope and Lifetime
ScopeWhere is the variable, and which procedures can access it?
LifetimeWhen is the variable created, and when is it destroyed?
58
Form--Module Code
Sub Button1_Click()Dim i1 As Integeri1 = 3End Sub
Sub Button2_Click()Dim i1 As Integeri1 = 7End Sub
Form
Button1Button2
Different procedures,different variables.Created and destroyedeach time the buttonis clicked.
Programming: Global Variables
Wider scope and lifetimeCreated at a higher level
FormPublic module
Accessible to any procedure in that form or module.Declare it Global to make it available to any procedure.
59
Form--Module Code
Sub Button2_Click()i2 = i2 + 7End Sub
Form
Button1Button2
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 = 20End Sub
Programming: Computations
Standard Math + - * / \ Integer divide ^ Exponentiation
(2^3 = 2*2*2 = 8) Mod
(15 Mod 4 = 3) (12 + 3 = 15)
String & Concatenation Left, Right, Mid Trim, LTrim, RTrim String Chr, Asc LCase, UCase InStr Len StrComp Format
60
“Frank” & “Rose” “FrankRose”
Left(“Jackson”,5) “Jacks”
Trim(“ Maria “) “Maria”
Len(“Ramanujan”) 9
String(5,”a”) “aaaaa”
InStr(“8764 Main”,” “) 5
Programming: Standard Functions
Numeric Exp, Log Atn, Cos, Sin, Tan Sqr Abs Sgn Int, Fix Rnd, Randomize
61
x = loge (ex)
Trigonometric functions
2 = 1.414
Abs(-35) 35
Sgn(-35) -1Int(17.893) 17
Rnd() 0.198474
? =30
92
Programming:Standard Functions: Date/Time
62
Date, Now, Time DateAdd, DateDiff
“y”, “m”, “q” . . . Firstweekday 1=Sunday,. . . Can also be used to find number
of Fridays, between two dates.
today DateDue
02/19/10 03/21/10
DateDue = DateAdd(“d”, 30, Date())
Programming:Standard Functions: Variant
Variant IsDate IsNumericVarType IsEmpty IsNull
63
Programming: Debug
Stop Ctrl-Break F5: Go F8: Step through S-F8: Step over Breakpoints
Immediate Window? or PrintAny assignmentAny code
64
Programming:Output: Message Box
MsgBox Message Type Title
Types: Use Constants vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel
Defaults vbDefaultButton1 vbDefaultButton2 vbDefaultButton3
Icons vbCritical Stop sign vbQuestion Question mark vbExclamation Warning vbInformation Circle i
Responses vbOK vbCancel vbAbort vbRetry vbIgnore vbYes vbNo
65
MsgBox "This is a message box", vbYesNoCancel + vbInformation, "Sample Box"
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
66
Dim str As Stringstr = InputBox( "Enter your name:", "Sample Input", , 5000, 5000)
Programming: Conditions
If If (Condition) Then
statements for trueElse
statements for falseEnd If
IIF (Cond., True, False) Select Case (expr)
Case valuestatements
Case value2Case ElseEnd Select
Conditions<, <=, >, >=, =, <>And, Or, Not, XorEqv, Imp (logic)
67
If (Condition1) Thenstatements for true
Elsestatements for falseIf (Condition2) Then
statements for trueEnd If
End If
ProgrammingSelect Example
68
Message Box Could use repeated If statements Better to use Select Case
response = MsgBox(…)If (response == vbYes) Then
‘ statements for YesElse
If (response == vbNo) Then‘ statements for No
Else ‘statements for Cancel
End IfEnd If
response = MsgBox(…) Select Case response
Case vbYes‘ statements for Yes
Case vbNo‘ statements for No
Case vbCancel‘ statements for Cancel
End Case
Programming: Loops
Do For … Next For Each
69
Do Until (x > 10)
‘ Statements
x = x + 1
Loop
Initialize value
Statements
Change value
Test condition
Do While (x <= 10)
‘ Statements
x = x + 1
LoopDo
‘ Statements
x = x + 1
Loop Until (x > 10)
For x = 1 to 10
‘ Statements
Next x
Programming: Loops Again
DoDo {While | Until}
Exit Do (optional)Loop
DoLoop {While | Until}
For/NextFor 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 objectEnd With
70
ProgrammingSubroutines 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 ByValChanges are made to a copy of the parameter, but are not returned to
the calling program.
71
Programming: Example Subroutine
72
Main program…StatusMessage “Trying to connect.”…StatusMessage “Verifying access.”… End main program
Sub StatusMessage (Msg As String)‘ Display Msg, location, color
End Sub
Programming: Parameter Types
73
Mainj = 3DoSum j… ‘ j is now equal to 8
Subroutine DoSum (j2 As Integer)j2 = 8
End Sub
By ReferenceChanges to data in thesubroutine are passed back.
Mainj = 3DoSum j… ‘ j is still equal to 3
Subroutine DoSum (ByVal j2 As Integer)j2 = 8
End Sub
By ValueCreates a copy of thevariable, so changes arenot returned.
ProgrammingArrays and User Types
ArraysDim array(sub, . . .) As typeDim iSorts(10) As Integer
Specifying bounds: (lower To upper, . . .)ReDim [Preserve] array .. .Option Base 0 | 1v 2.0 arrays less than 64KB
User defined typesType Tname
ename1 As typeename2 As type
End Type
Dim var1 As Tname var1.ename1 = . . . var1.ename2 = . . .
74
Programming: Financial Functions
Fixed payments PV (rate, nper, pmt, fv, due) FV (rate, nper, pmt, pv, due) IPmt (rate, per, nper, pv, fv, due) NPer (rate, pmt, pv, fv, due) Pmt (rate, nper, pv, fv,due) PPmt (rate, per, nper, pv, fv, due) Rate (nper, pmt, pv, fv, due, guess)
rate interest rate per period per specific period number nper # of periods pv present value fv future value due 0=due at end, 1=due at start
Arrays NPV (rate, array) IRR (array, guess) MIRR (array, finrate, re_rate)
Depreciation DDB (cost, salv, life, period) SLN (cost, salvage, life) SYD (cost, salv., life, period)
75
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
76