structured query language (sql) ask and ye shall receive. the bible

24
Structured Query Language (SQL) Ask and ye shall receive. The Bible

Upload: laureen-nelson

Post on 13-Dec-2015

230 views

Category:

Documents


0 download

TRANSCRIPT

Structured Query Language

(SQL)

Ask and ye shall receive. The Bible

Class Outline

What is SQL? What are the basic SQL select statements and

what is the order in which they are to be used? Which are optional?

Create SQL statements that use expressions and functions to convert data into

information use multiple criteria for searching produce output in a specific order provide summary data from groups of records display data from two tables show data that uses the results of another query as

criteria

SQL SQL is a non-procedural data access language that is used

primarily in programming by embedding it in other languages SQL is not a user-level language SQL accepts one or more relations as input and produces a single

relation as output SQL provides functions for data definition (creates database and

table structures), data management (enter, edit, delete data), and data query (convert data into information)

developed in mid 1970s by IBM; endorsed by ANSI (American National Standards Institute) as the language of choice for manipulating relational databases

language used by DB2, SQL/DS, ORACLE, INGRES, SYBASE, dBase, Paradox, Access (each with its own dialect)

computer systems are able to exchange data by passing SQL requests and responses to one another

our focus

General SQL Query Syntax

SELECT* columns to extract

FROM tables containing columns

WHERE search criteria to restricts rows that are returned

GROUP BY summarizes query results by groups

HAVING search criteria to restrict groups that are returned

ORDER BY sorts results by one or more 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

Projections

SELECT Name, Salary

FROM 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

SELECT Office, EmpID, Name

FROM 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 Projections

SELECT DISTINCT Name, Salary

FROM 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 DISTINCT Office, Salary

FROM Employee

Name SalaryRodney Jones 3000Goro Azuma 1500Francine Moire 2500Anne Abel 1500Mary Chen 3000

Office SalaryToronto 3000Tokyo 1500Brussels 2500Brussels 3000

appears only once

Selections

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, Salary

FROM Employee

WHERE Office = ‘Brussels’

EmpID Name Office Salary35 Francine Moire Brussels 250099 Mary Chen Brussels 5000

SELECT *

FROM Employee

WHERE Office = ‘Brussels’

Combining Selections and Projections

SELECT Name, Salary

FROM Employee

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, Salary

FROM Employee

WHERE EmpID = 35

Name Office SalaryFrancine Moire Brussels 2500

Single quotes necessary around text and dates (but not values) in criteria.

Comparison 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, Salary

FROM Employee

WHERE Salary >= 2500

SELECT EmpID, Name, Office

FROM Employee

WHERE Name <> ‘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 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 % (MS Access uses *)a string of one character (MS Access uses ?)

Missing value IS NULLReverses preceding operators NOT

Examples of Search Conditions

SELECT Name, Salary

FROM Employee

WHERE Office IN (‘Brussels’, ‘Tokyo’)

SELECT Name, Office, Salary

FROM Employee

WHERE Salary between 2000 and 3000

SELECT Name, Office, Salary

FROM Employee

WHERE Name Like ‘%am’

SELECT Name, Office, Salary

FROM Employee

WHERE Name Like ‘Ab_l’

SELECT Name, Office, Salary

FROM Employee

WHERE Office is Null

SELECT Name, Office, Salary

FROM Employee

WHERE Office NOT IN (‘Toronto’)

Compound Comparison Search Conditions

SELECT Name, Salary

FROM Employee

WHERE (Office IN (‘Brussels’, ‘Tokyo’) or Salary is Null)and HireDate <= ‘7/15/99’

SELECT Name, Office, Salary

FROM Employee

WHERE (Salary between 2000 and 3000 and Office <> ‘Tokyo’) or (Name like ‘Gor% and EmpID > 20)

SELECT Name, Office, Salary

FROM Employee

WHERE Name NOT Like ‘%Abel’ and Salary >= 3100

SELECT Name, Office, Salary

FROM Employee

WHERE Office IN (‘Toronto’) or 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

Sorting

SELECT Name, Salary

FROM Employee

WHERE Office = ‘Tokyo’

ORDER BY 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, Salary

FROM Employee

WHERE Salary >= 2000

ORDER BY EmpID DESC

Name SalaryGoro Azuma 1500Mary Chen 1500Anne Abel 3000

Name Office SalaryAnne Abel Tokyo 3000Francine Moire Brussels 2500

Expressions using Arithmetic

SELECT Name, Salary, Commission/Salary

FROM Salesperson

WHERE Commission > .05*Salary

SELECT ContactName, CompanyName

FROM Customer

WHERE Paid is null and OrderDate >= ‘1/1/99’

ORDER BY SysDate-InvoiceDate

SELECT ItemName, Price*1.15

FROM Product

SELECT Name, (Sysdate-Birthdate)/365

FROM Employee

ORDER BY Name

SELECT EmpID, Hiredate+90

FROM Employee

ORDER BY Name

current system date

SQL Built-in Functions

SELECT Count(*)FROM Employee

Count(*)5

SELECT Count(Distinct Office)FROM EmployeeCountDistinctOffice

3

SELECT Sum(Salary)FROM Employee

SumOfSalary13500

SELECT Max(HireDate)FROM EmployeeMaxOfHireDate

1-Aug-97

SELECT Min(Name)FROM Employee

MinOfNameAnne Abel

SELECT Avg(Salary)FROM 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 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(*)

FROM Employee

GROUP BY Office

Office Count(*)Brussels 2Tokyo 3

SELECT Office, Status, Max(Salary)

FROM Employee

GROUP BY 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 Functions

SELECT Category, Avg(Price), Min(Quantity), Sum(Price*Quantity)

FROM Product

WHERE SupplierID in (1, 2) or SupplierID is null

GROUP BY Category

ORDER BY 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”

SELECT Category, Avg(Price), Min(Quantity), Sum(Price*Quantity)

FROM Product

WHERE SupplierID in (‘1’, ‘2’) or SupplierID is null

GROUP BY Category

HAVING 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’ 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)

FROM Employee

WHERE Status = ‘full-time’

GROUP BY Office

HAVING Count(*) > 1

ORDER BY Office

Office MaxOfSalaryBrussels 2500Tokyo 5000

Subqueries

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, Qty

FROM Product

WHERE SupID IN

(SELECT SupplierID

FROM Supplier

WHERE City = ‘London’)

ProdID Price Qty

802 60 20

803 40 40

Subquery is always evaluated before the main query.

SELECT ProdID

FROM Product

WHERE Qty >

(SELECT Avg(Qty)

FROM Product

WHERE SupID IN (‘1’, ‘2’))

ProdID

802

804

Nested 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:

Join (Natural Join)

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 BrakesComponents 25.00 10 2

805 Diablo ATM Mountain BikeAccessories 1,200.00 2 2

SELECT Product ProdID, Product ProdDesc, Supplier SupplierName

FROM Product, Supplier

WHERE Product SupID = Supplier 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 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) “Average Price”, count(*) “# of Items”

FROM Product P, Supplier S

WHERE P SupID = S SupplierIDand Category = ‘Accessories’

GROUP BY SupplierName

ORDER BY SupplierID SupplierName Average Price # of ItemsSmall motor suppliers 50 2All Bikes Allways 40 1

alias

‘Exists’ 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)

NameFrancine 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