View
216
Download
1
Embed Size (px)
Citation preview
Database Management Systems & ProgrammingDatabase Management Systems & Programming
Faculty of Information & Media StudiesFaculty of Information & Media Studies
Summer 2000Summer 2000
LIS 558 - Week 6LIS 558 - Week 6
Structured Query Structured Query LanguageLanguage
Class OutlineClass Outline
SQL -- What is it?SQL -- What is it? Basic SQL select statementsBasic SQL select statements Using expressions and functions to convert Using expressions and functions to convert
data into informationdata into information Using multiple criteria for searchingUsing multiple criteria for searching Producing output in a specific orderProducing output in a specific order Providing summary data from groups of Providing summary data from groups of
recordsrecords Displaying data from more than one tableDisplaying data from more than one table Showing data that uses the results of Showing data that uses the results of
another query as criteriaanother query as criteria
SQL - Structured Query LanguageSQL - Structured Query Language
SQL is a non-procedural data access SQL is a non-procedural data access language that is used primarily in language that is used primarily in programming by embedding it in other programming by embedding it in other languageslanguages
SQL is not a user-level languageSQL is not a user-level language
SQL accepts one or more relations as input SQL accepts one or more relations as input and produces a single relation as outputand produces a single relation as output
SQL provides functions for SQL provides functions for data definitiondata definition (creates database and table structures), (creates database and table structures), data data managementmanagement (enter, edit, delete data), and (enter, edit, delete data), and data querydata query (convert data into information) (convert data into information)
SQLSQL
Developed in mid 1970s by IBM; endorsed by Developed in mid 1970s by IBM; endorsed by ANSI (American National Standards Institute) ANSI (American National Standards Institute) as the language of choice for manipulating as the language of choice for manipulating relational databasesrelational databases
Language used by DB2, SQL/DS, ORACLE, Language used by DB2, SQL/DS, ORACLE, INGRES, SYBASE, dBase, Paradox, Access INGRES, SYBASE, dBase, Paradox, Access (each with its own dialect)(each with its own dialect)
Computer systems are able to exchange data Computer systems are able to exchange data by passing SQL requests and responses to by passing SQL requests and responses to one anotherone another
General SQL Query SyntaxGeneral SQL Query Syntax
SELECTSELECT columns to extractcolumns to extract
FROMFROM tables containing tables containing columnscolumns
WHEREWHERE search criteria to restrictsearch criteria to restrict
rows that are returnedrows that are returned
GROUP BYGROUP BY summarizes query summarizes query results results by groupsby groups
HAVINGHAVING search criteria to restrict search criteria to restrict groups that are returnedgroups that are returned
ORDER BYORDER BY sorts results by one orsorts results by one or
more columnsmore columns
• Preceding is the order in which clauses should appear• Order of processing is as follows: From, Where, Group by, Having,
Order by, Select
required
optional, must be in this order if any or all are used
ProjectionsProjections
SELECTSELECT Name, Salary Name, Salary
FROM EmployeeFROM Employee
Employee
EmpID Name Office Salary27 Rodney Jones Toronto 300044 Goro Azuma Tokyo 150035 Francine Moire Brussels 250037 Anne Abel Tokyo 150099 Mary Chen Brussels 5000
SELECTSELECT Office, EmpID, Name Office, EmpID, Name
FROM EmployeeFROM Employee
Name SalaryRodney Jones 3000Goro Azuma 1500Francine Moire 2500Anne Abel 1500Mary Chen 5000
Office EmpID NameToronto 27 Rodney JonesTokyo 44 Goro AzumaBrussels 35 Francine MoireTokyo 37 Anne AbelBrussels 99 Mary Chen
Unique ProjectionsUnique Projections
SELECT SELECT DISTINCTDISTINCT Name, Salary Name, Salary
FROM EmployeeFROM Employee
Employee
EmpID Name Office Salary27 Rodney Jones Toronto 300044 Goro Azuma Tokyo 150035 Francine Moire Brussels 250037 Anne Abel Tokyo 150099 Mary Chen Brussels 3000
SELECT SELECT DISTINCTDISTINCT Office, Salary Office, Salary
FROM EmployeeFROM Employee
Name SalaryRodney Jones 3000Goro Azuma 1500Francine Moire 2500Anne Abel 1500Mary Chen 3000
Office SalaryToronto 3000Tokyo 1500Brussels 2500Brussels 3000
appears only once
SelectionsSelections
Employee
EmpID Name Office Salary27 Rodney Jones Toronto 300044 Goro Azuma Tokyo 150035 Francine Moire Brussels 250037 Anne Abel Tokyo 150099 Mary Chen Brussels 5000
SELECT EmpID, Name, Office, SalarySELECT EmpID, Name, Office, Salary
FROM EmployeeFROM Employee
WHEREWHERE Office = ‘Brussels’ Office = ‘Brussels’EmpID Name Office Salary
35 Francine Moire Brussels 250099 Mary Chen Brussels 5000
SELECT *SELECT *
FROM EmployeeFROM Employee
WHEREWHERE Office = ‘Brussels’ Office = ‘Brussels’
Combining Selections and ProjectionsCombining Selections and Projections
SELECT Name, SalarySELECT Name, Salary
FROM EmployeeFROM Employee
WHERE Office = ‘Brussels’WHERE Office = ‘Brussels’
Employee
EmpID Name Office Salary27 Rodney Jones Toronto 300044 Goro Azuma Tokyo 150035 Francine Moire Brussels 250037 Anne Abel Tokyo 150099 Mary Chen Brussels 5000
Name SalaryFrancine Moire 2500Mary Chen 5000
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE EmpID = 35WHERE EmpID = 35
Name Office SalaryFrancine Moire Brussels 2500
Single quotes necessary around text and dates (but not values) in
criteria.
Comparison Search ConditionsComparison Search Conditions
Equality and Inequality OperatorsEqual to =Not equal to <> (or !=)Greater than >Less than <Less than or equal to <=Greater than or equal to >=
Employee
EmpID Name Office Salary27 Rodney Jones Toronto 300044 Goro Azuma Tokyo 150035 Francine Moire Brussels 250037 Anne Abel Tokyo 150099 Mary Chen Brussels 5000
SELECT Name, SalarySELECT Name, Salary
FROM EmployeeFROM Employee
WHERE Salary WHERE Salary >= >= 25002500
SELECT EmpID, Name, OfficeSELECT EmpID, Name, Office
FROM EmployeeFROM Employee
WHERE Name WHERE Name <><> ‘Anne Abel’ ‘Anne Abel’
Name SalaryRodney Jones 3000Francine Moire 2500Mary Chen 5000
EmpID Name Office27 Rodney Jones Toronto44 Goro Azuma Tokyo35 Francine Moire Brussels99 Mary Chen Brussels
Comparison Search ConditionsComparison Search Conditions
Comparison Operators
Equal to any member of the list IN(list)
Greater than or equal to one value, and less than or equal to another
BETWEEN low AND high
Matches the following pattern LIKEa string of zero or more characters *a string of one character ?
Missing value IS NULLReverses preceding operators NOT
Examples of Search ConditionsExamples of Search Conditions
SELECT Name, SalarySELECT Name, Salary
FROM EmployeeFROM Employee
WHERE Office WHERE Office ININ (‘Brussels’, ‘Tokyo’) (‘Brussels’, ‘Tokyo’)
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE Salary WHERE Salary betweenbetween 2000 2000 andand 3000 3000
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE Name WHERE Name LikeLike ‘ ‘**am’am’
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE Name WHERE Name LikeLike ‘Ab ‘Ab??’’
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE Office WHERE Office is Nullis Null
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE Office WHERE Office NOT INNOT IN (‘Toronto’) (‘Toronto’)
Compound Comparison Search ConditionsCompound Comparison Search Conditions
SELECT Name, SalarySELECT Name, Salary
FROM EmployeeFROM Employee
WHERE WHERE ((Office IN (‘Brussels’, ‘Tokyo’) or Salary is NullOffice IN (‘Brussels’, ‘Tokyo’) or Salary is Null))and HireDate <= ‘7/15/99’and HireDate <= ‘7/15/99’
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE WHERE ((Salary between 2000 and 3000 and Office <> Salary between 2000 and 3000 and Office <> ‘Tokyo’‘Tokyo’)) or or ((Name like ‘Gor*’ and EmpID > 20Name like ‘Gor*’ and EmpID > 20))
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE Name NOT Like ‘*Abel’ WHERE Name NOT Like ‘*Abel’ andand Salary >= 3100 Salary >= 3100
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE Office IN (‘Toronto’) WHERE Office IN (‘Toronto’) oror Name = ‘Anne Abel’ Name = ‘Anne Abel’
when operators are combined, brackets are evaluated first (inner to outer)
AND means that ALL conditions must be metOR means that ANY condition may be met
SortingSorting
SELECT Name, SalarySELECT Name, Salary
FROM EmployeeFROM Employee
WHERE Office = ‘Tokyo’WHERE Office = ‘Tokyo’
ORDER BYORDER BY Salary, Name Salary, Name
Employee
EmpID Name Office Salary27 Rodney Jones Toronto 150044 Goro Azuma Tokyo 150035 Francine Moire Brussels 250037 Anne Abel Tokyo 300099 Mary Chen Tokyo 1500
SELECT Name, Office, SalarySELECT Name, Office, Salary
FROM EmployeeFROM Employee
WHERE Salary >= 2000WHERE Salary >= 2000
ORDER BY ORDER BY EmpID EmpID DESCDESC
Name SalaryGoro Azuma 1500Mary Chen 1500Anne Abel 3000
Name Office SalaryAnne Abel Tokyo 3000Francine Moire Brussels 2500
Expressions using ArithmeticExpressions using Arithmetic
SELECT Name, Salary, SELECT Name, Salary, Commission/SalaryCommission/Salary
FROM SalespersonFROM Salesperson
WHERE WHERE Commission > .05*SalaryCommission > .05*Salary
SELECT ContactName, CompanyNameSELECT ContactName, CompanyName
FROM CustomerFROM Customer
WHERE Paid is null and OrderDate >= ‘1/1/99’WHERE Paid is null and OrderDate >= ‘1/1/99’
ORDER BY ORDER BY Date-InvoiceDateDate-InvoiceDate
SELECT ItemName, SELECT ItemName, Price*1.15Price*1.15
FROM ProductFROM Product
SELECT Name, SELECT Name, (Date-Birthdate)/365(Date-Birthdate)/365
FROM EmployeeFROM Employee
ORDER BY NameORDER BY Name
SELECT EmpID, SELECT EmpID, Hiredate+90Hiredate+90
FROM EmployeeFROM Employee
ORDER BY NameORDER BY Name
current system date
SQL Built-in FunctionsSQL Built-in Functions
SELECT SELECT Count(*)Count(*)FROM EmployeeFROM Employee
Count(*)5
SELECT SELECT Count(Distinct Office)Count(Distinct Office)FROM EmployeeFROM Employee
CountDistinctOffice
3
SELECT SELECT Sum(Salary)Sum(Salary)FROM EmployeeFROM Employee
SumOfSalary13500
SELECT SELECT Max(HireDate)Max(HireDate)FROM EmployeeFROM Employee
MaxOfHireDate1-Aug-97
SELECT SELECT Min(Name)Min(Name)FROM EmployeeFROM Employee
MinOfNameAnne Abel
SELECT SELECT Avg(Salary)Avg(Salary)FROM EmployeeFROM Employee
AvgOfSalary2700
Employee
EmpID Name Office Salary HireDate27 Rodney Jones Toronto 3000 12-May-9244 Goro Azuma Tokyo 1500 15-Mar-9335 Francine Moire Brussels 2500 22-Dec-8937 Anne Abel Tokyo 1500 1-Aug-9799 Mary Chen Tokyo 5000 17-Aug-95
Aggregate Functions and GroupingAggregate Functions and Grouping
Employee
EmpID Name Office Salary Status HireDate27 Rodney Jones Brussels 3000 part time 12-May-9244 Goro Azuma Tokyo 4000 full time 15-Mar-9335 Francine Moire Brussels 2500 full time 22-Dec-8937 Anne Abel Tokyo 2000 full time 1-Aug-9799 Mary Chen Tokyo 5000 full time 17-Aug-95
SELECT Office, Count(*)SELECT Office, Count(*)
FROM EmployeeFROM Employee
GROUP BYGROUP BY Office Office
Office Count(*)Brussels 2Tokyo 3
SELECT Office, Status, Max(Salary)SELECT Office, Status, Max(Salary)
FROM EmployeeFROM Employee
GROUP BYGROUP BY Office, Status Office, Status
Office Status MaxOfSalaryBrussels full time 2500Brussels part time 3000Tokyo full time 5000
To view the groupings, you must also select them!
More Grouping FunctionsMore Grouping Functions
SELECT Category, Avg(Price), Min(Quantity), SELECT Category, Avg(Price), Min(Quantity), Sum(Price*Quantity)Sum(Price*Quantity)
FROM ProductFROM Product
WHERE SupplierID in (1, 2) or SupplierID is nullWHERE SupplierID in (1, 2) or SupplierID is null
GROUP BYGROUP BY Category Category
ORDER BY ORDER BY Avg(Price)Avg(Price)
Category AvgOfPrice MinOfQuantity SumOfPriceQuantityAccessories 41.2 5 449.5Components 428.3 2 3850
Product
ProdID ProdDesc Category Price Quantity SupplierID
801 Shur-Lock U-Lock Accessories 75.00 5 2
802 SpeedRite CyclecomputerComponents 60.00 20 1
803 SteelHead Microshell HelmetAccessories 40.00 40 3
804 SureStop 133-MB BrakesComponents 25.00 10 2
805 Diablo ATM Mountain BikeComponents 1,200.00 2 2
806 Ultravision Helmet Mount MirrorsAccessories 7.45 10
Restrict Groups with “Having”Restrict Groups with “Having”
SELECT Category, Avg(Price), Min(Quantity), SELECT Category, Avg(Price), Min(Quantity), Sum(Price*Quantity)Sum(Price*Quantity)
FROM ProductFROM Product
WHERE SupplierID in (‘1’, ‘2’) or SupplierID is nullWHERE SupplierID in (‘1’, ‘2’) or SupplierID is null
GROUP BYGROUP BY Category Category
HAVINGHAVING Min(Quantity) < 5 Min(Quantity) < 5
Category AvgOfPrice MinOfQuantity SumOfPriceQuantityComponents 428.3 2 3850
Product
ProdID ProdDesc Category Price Quantity SupplierID
801 Shur-Lock U-Lock Accessories 75.00 5 2
802 SpeedRite CyclecomputerComponents 60.00 20 1
803 SteelHead Microshell HelmetAccessories 40.00 40 3
804 SureStop 133-MB BrakesComponents 25.00 10 2
805 Diablo ATM Mountain BikeComponents 1,200.00 2 2
806 Ultravision Helmet Mount MirrorsAccessories 7.45 10
The ‘WHERE’ clause is always evaluated before the ‘HAVING’ clause.
Another ‘Having’ exampleAnother ‘Having’ example
Employee
EmpID Name Office Salary Status HireDate27 Rodney Jones Brussels 3000 part time 12-May-9244 Goro Azuma Tokyo 4000 full time 15-Mar-9335 Francine Moire Brussels 2500 full time 22-Dec-8937 Anne Abel Tokyo 2000 full time 1-Aug-9799 Mary Chen Tokyo 5000 full time 17-Aug-9525 Brigit Sanchez Toronto 10000 full time 3-Jan-0010 Joki Singh Brussels 1000 full time 3-Jan-00
SELECT Office, Max(Salary)SELECT Office, Max(Salary)
FROM EmployeeFROM Employee
WHERE Status = ‘full-time’WHERE Status = ‘full-time’
GROUP BYGROUP BY Office Office
HAVINGHAVING Count(*) > 1 Count(*) > 1
ORDER BY OfficeORDER BY Office
Office MaxOfSalaryBrussels 2500Tokyo 5000
SubqueriesSubqueries
Supplier
SupplierID SupplierName City1 Bikes-R-Us London2 Small moter suppliersToronto3 All Bikes AllwaysLondon
Product
ProdID ProdDesc Category Price Qty SupID
801 Shur-Lock U-LockAccessories 75 5 2
802 SpeedRite CyclecomputerComponents 60 20 1
803 SteelHead Microshell HelmetAccessories 40 40 3
804 SureStop 133-MB BrakesComponents 25 10 2
805 Diablo ATM Mountain BikeAccessories1,200 2 2
SELECT ProdID, Price, QtySELECT ProdID, Price, Qty
FROM ProductFROM Product
WHERE SupID WHERE SupID ININ
(SELECT SupplierID(SELECT SupplierID
FROM SupplierFROM Supplier
WHERE City = ‘London’) WHERE City = ‘London’)
ProdID Price Qty
802 60 20
803 40 40
Subquery is always evaluated before the main query.
SELECT ProdIDSELECT ProdID
FROM ProductFROM Product
WHERE Qty > WHERE Qty >
(SELECT Avg(Qty)(SELECT Avg(Qty)
FROM ProductFROM Product
WHERE SupID IN (‘1’, ‘2’))WHERE SupID IN (‘1’, ‘2’))
ProdID
802
804
Nested SubqueriesNested Subqueries
SELECT Count(Unique PolicyNum)FROM PolicyPlanWHERE PlanCode = ‘45’ and PolicyNum
IN(SELECT PolicyNumFROM CommissionWHERE AgentNum IN
(SELECT AgentNumFROM AgentWHERE Area = 100))
Agent
AgentID AgentName Area1 Anne Abel 1002 Goro Azuma 2003 Mary Chen 100
Commission
AgentID PolicyNo. Comm1 5 5%1 9 7%3 3 3%2 7 5%
PolicyPlan
PlanCodePolicyNo. Category45 3 FG98 5 SR45 9 JR45 9 FR
CountOfPolicyNo.2
Determine the number of policies sold in area 100 of type 45:
Product
ProdID ProdDesc Category Price Qty SupID
801 Shur-Lock U-Lock Accessories 75.00 5 2
802 SpeedRite CyclecomputerComponents 60.00 20 1
803 SteelHead Microshell HelmetAccessories 40.00 40 3
804 SureStop 133-MB BrakesComponents 25.00 10 2
805 Diablo ATM Mountain BikeAccessories 1,200.00 2 2
Join (Natural Join)Join (Natural Join)
Supplier
SupplierID SupplierName1 Bikes-R-Us2 Small moter suppliers3 All Bikes Allways
SELECT SELECT ProductProduct ProdID, ProdID, ProductProduct ProdDesc, ProdDesc, SupplierSupplier SupplierNameSupplierName
FROMFROM Product, Supplier Product, Supplier
WHEREWHERE Product Product SupID = SupplierSupID = Supplier SupplierID SupplierID
ProdID ProdDesc SupplierName
801 Shur-Lock U-Lock Small motor suppliers
802 SpeedRite Cyclecomputer Bikes-R-Us
803 SteelHead Microshell Helmet All Bikes Allways
804 SureStop 133-MB Brakes Small motor suppliers
805 Diablo ATM Mountain Bike Small motor suppliers
Table names required in Select statement only if there’s a possibility of ambiguity
Renaming Attributes and Relations with an AliasRenaming Attributes and Relations with an Alias
Supplier
SupplierID SupplierName1 Bikes-R-Us2 Small moter suppliers3 All Bikes Allways
Product
ProdID ProdDesc Category Price Qty SupID
801 Shur-Lock U-Lock Accessories 75.00 5 2
802 SpeedRite CyclecomputerComponents 60.00 20 1
803 SteelHead Microshell HelmetAccessories 40.00 40 3
804 SureStop 133-MB BrakesAccessories 25.00 10 2
805 Diablo ATM Mountain BikeBike 1,200.00 2 2
SELECT SupplierName, avg(price) As SELECT SupplierName, avg(price) As “Average Price”“Average Price”, count(*) As , count(*) As “# of Items”“# of Items”
FROM Product FROM Product PP, Supplier , Supplier SS
WHERE WHERE PP SupID = SupID = SS SupplierIDSupplierIDand Category = ‘Accessories’and Category = ‘Accessories’
GROUP BY SupplierNameGROUP BY SupplierName
ORDER BY SupplierIDORDER BY SupplierID
SupplierName Average Price # of ItemsSmall motor suppliers 50 2All Bikes Allways 40 1
alias
‘‘Exists’ and ‘not exists’ in SubqueriesExists’ and ‘not exists’ in SubqueriesEmployee
EmpID Name Office Sex27 Rodney Jones Brussels M44 Goro Azuma Tokyo M35 Francine Moire Brussels F
Dependent
EmpID DepName DepSex27 Jane Jones F27 Jenny Jones F35 Mary Moire F35 Melvin Moire M35 Minnie Moire F
SELECT NameFROM Employee EWHERE EXISTS
(SELECT *FROM Dependent DWHERE E.EmpID =
D.EmpIDand E.Sex = D.DepSex)Name
Francine Moire
Which employees have dependents of the same sex as themselves? Which employees have no
dependents?SELECT NameFROM Employee EWHERE NOT EXISTS
(SELECT *FROM Dependent DWHERE E.EmpID =
D.EmpID)NameGoro Azuma