42
SQL Queries CPSC 315 – Programming Studio Spring 2009 Team Project 1, Lecture 4 Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch

SQL Queries

  • Upload
    ronni

  • View
    52

  • Download
    9

Embed Size (px)

DESCRIPTION

SQL Queries. CPSC 315 – Programming Studio Spring 2009 Team Project 1, Lecture 4. Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch. Modifying the Database. Data Manipulation Language Given a schema, must “populate” the database with actual data Insert, Delete, Modify. - PowerPoint PPT Presentation

Citation preview

Page 1: SQL Queries

SQL QueriesCPSC 315 – Programming StudioSpring 2009Team Project 1, Lecture 4

Slides adapted from those used byJeffrey Ullman, via Jennifer Welch

Page 2: SQL Queries

Modifying the DatabaseData Manipulation LanguageGiven a schema, must “populate” the database with actual dataInsert, Delete, Modify

Page 3: SQL Queries

InsertionINSERT command:

INSERT INTO <Relation>VALUES (<value list>);

Can specify only certain attributes in Relation

Relation(<attribute list>)Instead of values, can have subquery

Page 4: SQL Queries

Insertion ExampleSenator(Name,Party,State,Years)

INSERT INTO SenatorVALUES (Jill Smith, Republican, NY, 5);

INSERT INTO Senator(Name, State)VALUES (Jill Smith, NY);

Page 5: SQL Queries

DeletionDelete from relation according to condition

DELETE FROM <Relation>WHERE <condition>;

Example: delete Texas Senators:DELETE FROM SenatorWHERE State = ‘TX’;

Page 6: SQL Queries

ModificationUpdate subset according to condition

UPDATE <Relation>SET <list of attribute assignments>WHERE <condition>;

Example: Joe Lieberman becomes Independent

UPDATE SenatorSET Party = ‘Independent’ WHERE Name = ‘Joseph Lieberman’;

Page 7: SQL Queries

QueriesThe heart of SQLQueries can form portion of other commands e.g. INSERT results of a query into a

tableForm: SELECT attributes FROM relation(s) WHERE condition

Page 8: SQL Queries

ExampleName Party Stat

eYears

Jill Smith Republican

NY 5

Joe Adams

Democrat

NJ 0

Sue Jones Democrat

CT 9

Jim Brown

Republican

PA 15

Senator:

Query:SELECT NameFROM SenatorWHERE Party = ‘Republican’;

Result: NameJill SmithJim Brown

Page 9: SQL Queries

Statement ProcessingBegin with the relation(s) in the FROM clause Can be the result of another query!

Apply selection condition in WHERE clause Can potentially be very complex, and include

subqueriesGet the attributes given in the SELECT clauseProcess: iterate through all tuples in FROM, checking vs. WHERE, and for those that match, apply the SELECT

Page 10: SQL Queries

SELECT Clause - *Can use a * for SELECT to indicate all attributes given in the relation listed in FROM.Senator:

Query:SELECT *FROM SenatorWHERE Party = ‘Republican’;

Result:

Name Party State

Years

Jill Smith Republican

NY 5

Joe Adams

Democrat

NJ 0

Sue Jones Democrat

CT 9

Jim Brown

Republican

PA 15Name Party Stat

eYears

Jill Smith Republican

NY 5

Jim Brown

Republican

PA 15

Page 11: SQL Queries

SELECT Clause - ASCan use AS to rename attributes in resultSenator:

Query:SELECT Name AS Person, Party AS Affiliation, StateFROM SenatorWHERE Party = ‘Republican’;

Result:

Name Party State

Years

Jill Smith Republican

NY 5

Joe Adams

Democrat

NJ 0

Sue Jones Democrat

CT 9

Jim Brown

Republican

PA 15

Person Affiliation State

Jill Smith Republican

NY

Jim Brown

Republican

PA

Page 12: SQL Queries

SELECT Clause - Expression

Can include expressions in SELECT ClauseSenator:

Query:SELECT Name, Years * 365 AS DaysInOfficeFROM SenatorWHERE Party = ‘Republican’;

Result:

Name Party State

Years

Jill Smith Republican

NY 5

Joe Adams

Democrat

NJ 0

Sue Jones Democrat

CT 9

Jim Brown

Republican

PA 15

Name DaysInOfficeJill Smith 1825Jim Brown

5475

Page 13: SQL Queries

SELECT Clause - ConstantsCan include constant attributesSenator:

Query:SELECT Name, ‘Senator’ AS OfficeHeldFROM SenatorWHERE Party = ‘Republican’;

Result:

Name Party State

Years

Jill Smith Republican

NY 5

Joe Adams

Democrat

NJ 0

Sue Jones Democrat

CT 9

Jim Brown

Republican

PA 15

Name OfficeHeldJill Smith SenatorJim Brown

Senator

Page 14: SQL Queries

AggregationsSUM, AVG, COUNT, MIN, MAX COUNT(*) counts number of tuplesApplied to column in SELECT clauseUse DISTINCT to eliminate duplicatesNULLs are ignoredIf Aggregation is used, every selected column must be aggregated or in the GROUP BY list

Page 15: SQL Queries

Grouping AggregationsAdding GROUP BY <attribute> at the end will apply aggregation only to group e.g. to get the total number of U.S.

Representatives from each state:SELECT State, COUNT(*)FROM USRepresentativesGROUP BY State

Page 16: SQL Queries

WHERE Clause – Complex Expressions

Can include NOT, AND, OR operatorsSenator:

Query:SELECT *FROM SenatorWHERE Party = ‘Republican’ OR Years > 3;

Result:

Name Party State

Years

Jill Smith Republican

NY 5

Joe Adams

Democrat

NJ 0

Sue Jones Democrat

CT 9

Jim Brown

Republican

PA 15Name Party Stat

eYears

Jill Smith Republican

NY 5

Sue Jones Democrat

CT 9

Jim Brown

Republican

PA 15

Page 17: SQL Queries

WHERE Clause – other effects

Order of operations, including parenthesesLIKE: String comparisons with wildcards % means any string _ means any character

Page 18: SQL Queries

WHERE Clause – NULL values

Tuples may contain NULL values Undefined/Unknown InapplicableAll conditions evaluate to either TRUE, FALSE, or UNKNOWNComparisons to NULL are UNKNOWNTuples selected only if TRUE

Page 19: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: (T AND ((NOT U OR F) AND NOT (U OR T)))

Page 20: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: (T AND ((NOT U OR F) AND NOT (U OR T))) MAX(1- ½,0) = MAX(½,0) = ½ = U

Page 21: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: (T AND (U AND NOT (U OR T)))

Page 22: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: (T AND (U AND NOT (U OR T))) MAX(½, 1) = 1 = T

Page 23: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: (T AND (U AND NOT T)

Page 24: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: (T AND (U AND NOT T) ) MIN(½, 1-1) = MIN(½,0) = 0 = F

Page 25: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: (T AND F)

Page 26: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: (T AND F) MIN(0,1) = 0 = F

Page 27: SQL Queries

3-valued LogicCan think of values as TRUE = 1 FALSE = 0 UNKNOWN = ½

Operations would be OR = MAX AND = MIN NOT = 1-x

Example: F (T AND ((NOT U OR F) AND NOT (U OR T)))

Page 28: SQL Queries

Unexpected Results for NULLs

WHERE (Years > 2) OR (Years < 3)This should “cover” all casesIf Years is NULL Years > 2 is UNKNOWN Years < 3 is UNKNOWN So the OR is UNKNOWN And thus the tuple is NOT selected!

Page 29: SQL Queries

WHERE Clause – IN operator

<tuple> IN <relation> TRUE iff the tuple is a

member of the relation

SELECT *FROM ElectedOfficialWHERE Name IN USRep

ElectedOfficialName PartyChet Edwards

Democrat

John Cornyn RepublicanJohn Adams FederalistRon Paul Republican

ResultName PartyChet Edwards

Democrat

Ron Paul Republican

USRepNameRon PaulChet Edwards

Page 30: SQL Queries

WHERE Clause – EXISTS operator

EXISTS (<relation>) TRUE iff the

relation is not empty relation

SELECT *FROM ElectedOfficialWHERE EXISTS(USRep)

ElectedOfficialName PartyChet Edwards

Democrat

John Cornyn RepublicanJohn Adams FederalistRon Paul Republican

USRepNameRon PaulChet Edwards

ResultName PartyChet Edwards

Democrat

John Cornyn RepublicanJohn Adams FederalistRon Paul Republican

Page 31: SQL Queries

EXISTS (and other) operators

Usually applied to the results of a subqueryExample: is any Senator a Whig?

EXISTS( SELECT * FROM Senator WHERE Party = ‘Whig’ )

Page 32: SQL Queries

WHERE Clause – ANY and ALL operators

x = ANY(<relation>) TRUE iff x is equal to at least one tuple in

the relationx = ALL(<relation>) TRUE iff x is equal to all tuples in the

relationThe = can also be >, >=, <, <=, <>The relation should have only one attribute

Page 33: SQL Queries

Example: ANY

SELECT *FROM ElectedOfficialWHERE Party = ANY (CurrentParties)

ElectedOfficialName PartyChet Edwards

Democrat

John Cornyn RepublicanJohn Adams FederalistRon Paul Republican

CurrentPartiesName

DemocratRepublican

ResultName PartyChet Edwards

Democrat

John Cornyn RepublicanRon Paul Republican

Page 34: SQL Queries

Example: ALLSenator

Name Party State

Years

Jill Smith Republican

NY 5

Joe Adams

Democrat NJ 0

Sue Jones Democrat CT 9Jim Brown Republica

nPA 15SELECT *

FROM SenatorWHERE Years > ALL (YearsPresidentsInSenate)

YearsPresidentsInSenate

Years Served601260

Name Party State

Years

Jim Brown Republican

PA 15

Page 35: SQL Queries

UNION, INTERSECT, DIFFERENCE

Can combine subqueries with Boolean operations e.g. (subquery) UNION (subquery)

Default: duplicates are removed by these operations unless ALL is included (subquery) INTERSECT ALL (subquery)

Likewise, can remove duplicates in normal SELECT by including DISTINCT SELECT DISTINCT Years …

Page 36: SQL Queries

“Bag” vs. “Set” semanticsItems are in a “bag” Duplicates OKItems are in a “set” Duplicates removed

Page 37: SQL Queries

JoinsCombining relations into one new relation Used to merge tables Many ways, variations<relation> CROSS JOIN <relation> Takes every possible combination

Page 38: SQL Queries

CROSS JOIN exampleVanTypes

Make ModelDodge CaravanHonda Odyssey

ResultMake Model Seats PaintDodge Caravan Cloth StandardDodge Caravan Leather StandardDodge Caravan Leather PremiumHonda Odyssey Cloth StandardHonda Odyssey Leather StandardHonda Odyssey Leather Premium

SeatsAndPaintSeats PaintCloth StandardLeather StandardLeather Premium

Page 39: SQL Queries

Inner JoinsInner Joins are based on the Cross JoinJoin is usually limited by some comparison using ONe.g. Senator INNER JOIN Representative ON Senator.State = Representative.State

Creates table with one (Senator, Representative) tuple for every pair from the same state.(Note: both State attributes still appear)

Page 40: SQL Queries

Natural JoinsAutomatically looks for matching columnsOnly one column for each match, and only select tuples that match in those columnsExample: SELECT * FROM

Students NATURAL JOIN SchoolLocations

Page 41: SQL Queries

Natural Join ExampleStudents

Name SchoolJoe Smith RiceJill Smith LSUSam Jones Texas A&MSue Jones Rice

SchoolLocationsSchool CityTexas A&M College

StationRice HoustonLSU Baton Rouge

ResultName School CityJoe Smith Rice HoustonJill Smith LSU Baton RougeSam Jones Texas A&M College StationSue Jones Rice Houston

Page 42: SQL Queries

OUTER JOINIncludes tuples from both relations, even if no match in the other Those attributes are set to NULLLEFT, RIGHT, FULL Keep all records from left table, or

from right table, or from both