l02-06-sql - v180129 · 2018-02-08 · quiz find the first/last names of all actors who appeared in...
TRANSCRIPT
233
L06:SQL
234
Announcements!
• Pleasepickupyournamecard- alwayscomewithyournamecard- Ifnobodyanswersmyquestion,Iwilllikelypickonthosewithoutanamecard orinthe
lastrow
• Pollsonspeed:weslowdownandhaveanotherSQLlecture(likelynoNoSQL)• Usetheanonymousfeedbackform• HW3 andlater:inteams
• Outlinetoday:- HW1 together- outerjoins,nulls
235
SELECT cnameFROM Product P, Company WHERE country = 'USA' AND P.category = 'Gadgets' AND P.manufacturer = cname
Awordoncapitalization 302
Product (pname, price, category, manufacturer)Company (cname, stockprice, country)
Q:FindallUScompaniesthatmanufactureproductsinthe'Gadgets'category!
Myrecommendationforcapitalization
1.SQLkeywordsinALLCAPS,2.TablenameswithInitialCaps3.Columnnamesallinlowercase.
Moreinformation:http://blog.lerner.co.il/quoting-postgresql/ ,https://stackoverflow.com/questions/6331504/omitting-the-double-quote-to-do-query-on-postgresql
PostgreSQLtreatsallinlowercase.Exceptifyouwrite:createtable"Product"(…)ThiswillpreservecapitalizationoftablenameBut… youneedtoalwaysusequotations
236
HW1
237
BigIMDBschema(Postgres)
Actoridfnamelnamegender
Movieidnameyear
Directorsidfnamelname
Castspidmidrole
Movie_directorsdidmid
Genremidgenre
238
QuizFindthefirst/lastnamesofallactorswhoappearedinbothofthefollowingmovies:KillBill:Vol.1andKillBill:Vol.2.
SELECT DISTINCT A.fname, A.lnameFROM Actor A, Casts C, Movie M1, Movie M2WHERE M1.name = 'Kill Bill: Vol. 1'
and M2.name = 'Kill Bill: Vol. 2'and M1.id = C.midand M2.id = C.midand C.pid = A.id
IMDB (postgres)
PictureSource:http://queryviz.com/online
L
239
QuizFindthefirst/lastnamesofallactorswhoappearedinbothofthefollowingmovies:KillBill:Vol.1andKillBill:Vol.2.
IMDB (postgres)
SELECT DISTINCT A.fname, A.lnameFROM Actor A, Casts C, Movie M1, Movie M2, Casts C2WHERE M1.name = 'Kill Bill: Vol. 1'
and M2.name = 'Kill Bill: Vol. 2'and M1.id = C.midand M2.id = C2.midand C.pid = A.idand C2.pid = A.id
PictureSource:http://queryviz.com/online
240
QuizFindthefirst/lastnamesofallactorswhoappearedinbothofthefollowingmovies:KillBill:Vol.1andKillBill:Vol.2.
IMDB (postgres)
SELECT A.id, A.lname, A.fname,FROM actor A, cast C, movie MWHERE M.id = C.mid
AND A.id = C.pidAND (M.name = 'Kill Bill: Vol. 1'
OR M.name = 'Kill Bill: Vol. 2')GROUP BY A.id, A.lname, A.fnameHAVING count(M.id) > 1
WhatifanactorplayedtworolesinKillBill1?
241
Null Values
242
3-valuedlogicexample
• Threelogicianswalkintoabar.Thebartenderasks:"Doallofyouwantadrink?"
• The1stlogiciansays:"Idon'tknow."• The2ndlogiciansays:"Idon'tknow."• The3rdlogiciansays:"Yes!"
243
NullsinSQL
• Wheneverwedon'thaveavalue,wecanputaNULL
• Canmeanmanythings:- Valuedoesnotexists- Valueexistsbutisunknown- Valuenotapplicable- Etc.
• TheschemaspecifiesforeachattributeifitcanbeNULL(nullableattribute)ornot
• HowdoesSQLcopewithtablesthathaveNULLs? 243
244
NullValues
• InSQLtherearethreeBooleanvalues:- FALSE,TRUE,UNKNOWN
• Ifx=NULLthen- ArithmeticoperationsproduceNULL.E.g:4*(3-x)/7- BooleanconditionsarealsoNULL.E.g:x='Joe'- aggregatesignoreNULLvalues
• Logicalreasoning:- FALSE=0 xANDy=min(x,y)- TRUE=1 xORy=max(x,y)- UNKNOWN=0.5 NOTx=(1– x)
244
245
NullValues:exampleSELECT *FROM PersonWHERE (age < 25)
and (height > 6 or weight > 190)
Age Height Weight20 NULL 200NULL 6.5 170
Person
246
NullValues:exampleSELECT *FROM PersonWHERE (age < 25)
and (height > 6 or weight > 190)
RuleinSQL:includeonlytuples thatyieldTRUE
Age Height Weight20 NULL 200NULL 6.5 170
Person
247
NullValues:exampleSELECT *FROM PersonWHERE (age < 25)
and (height > 6 or weight > 190)
RuleinSQL:includeonlytuples thatyieldTRUE
Age Height Weight20 NULL 200NULL 6.5 170
SELECT *FROM PersonWHERE age < 25 or age >= 25
Person
248
NullValues:exampleSELECT *FROM PersonWHERE (age < 25)
and (height > 6 or weight > 190)
RuleinSQL:includeonlytuples thatyieldTRUE
Age Height Weight20 NULL 200NULL 6.5 170
SELECT *FROM PersonWHERE age < 25 or age >= 25
Unexpectedbehavior
SELECT *FROM PersonWHERE age < 25 or age >= 25 or age IS NULL
TestNULLexplicitly
Person
249
NullValuesandAggregates
gid val1 NULL1 NULL2 a2 a2 z2 z2 NULL3 A3 A3 Z
SELECT gid, MAX(val) maxv,MIN(val) minv, COUNT(*) ctr, COUNT(val) ctv, COUNT(DISTINCT val) ctdv
FROM TGROUP BY gidORDER BY gid
T
373
?
250
ctdv032
NullValuesandAggregates
gid val1 NULL1 NULL2 a2 B2 z2 z2 NULL3 A3 A3 Z
SELECT gid, MAX(val) maxv,MIN(val) minv, COUNT(*) ctr, COUNT(val) ctv, COUNT(DISTINCT val) ctdv
FROM TGROUP BY gidORDER BY gid
T
373
gid123
maxvNULLzZ
ctv043
ctr253
minvNULLBA
NULLisignoredbyaggregatefunctionsifyoureferencethecolumnspecifically.Exception:COUNT!
251
Inner Joinsvs. Outer Joins
252
AlternaiveJoinSyntax
SELECT Item.name, Purchase2.storeFROM Item JOIN Purchase2 ON
Item.name = Purchase2.iName
SELECT Item.name, Purchase2.storeFROM Item, Purchase2WHERE Item.name = Purchase2.iNameSameas:
An"innerjoin":
Name CategoryGizmo GadgetCamera PhotoOneClick Photo
ItemName StoreGizmo WizCamera RitzCamera Wiz
ResultiName Store MonthGizmo Wiz 8Camera Ritz 8Camera Wiz 9
Purchase2
Item(name,category)Purchase2(iName,store,month)
334
253
etext eid fid ftextOne 1 1 UnThree 3 3 TroisFour 4 4 QuatreFive 5 5 CinqSix 6 6 Siz
Illustrationfid fText1 Un3 Trois4 Quatre5 Cinq6 Siz7 Sept8 Huit
EnglisheText eidOne 1Two 2Three 3Four 4Five 5Six 6
French
SELECT *FROM English, FrenchWHERE eid = fid
361
SELECT *FROM English JOIN FrenchON eid = fid
Sameas:
An"innerjoin":
"JOIN"sameas
"INNERJOIN"
254
etext eid fid ftextOne 1 1 UnTwo 2 NULL NULLThree 3 3 TroisFour 4 4 QuatreFive 5 5 CinqSix 6 6 SizNULL NULL 7 SeptNULL NULL 8 Huit
Illustrationfid fText1 Un3 Trois4 Quatre5 Cinq6 Siz7 Sept8 Huit
EnglisheText eidOne 1Two 2Three 3Four 4Five 5Six 6
French
SELECT *FROM English FULL JOIN FrenchON English.eid = French.fid
SQLitedoesnotsupport"FULLOUTERJOIN"sL (but"LEFTJOIN")
361
SELECT *FROM English JOIN FrenchON eid = fid
"FULLJOIN"sameas
"FULLOUTERJOIN"