Unit4_Lecture-sql.ppt and data science relate

umang2782love 9 views 97 slides May 12, 2024
Slide 1
Slide 1 of 97
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97

About This Presentation

More valuable for data science student


Slide Content

Unit-4:SQL for data science
Dr. Tarun Pal

Definitions of Database
Def 1:Database is an organized collectionof
logically related data
Def 2:A database is a sharedcollection of logically
relateddatathat is stored to meet the requirements of
different users of an organization
Def 3:A database is a self-describingcollection of
integrated records
Def 4:A database models a particular real world
systemin the computer in the form of data

3
What is a Database
Shared collection of logically related data (and a
description of this data), designed to meet the
information needs of an organization.
System catalog(metadata) provides description of
data to enable program–data independence.
Logically related data comprises entities,
attributes, and relationships of an organization’s
information.

University Database Example
•Application program examples
–Add new students, instructors, and
courses
–Register students for courses, and
generate class rosters
–Assign grades to students, compute
grade point averages (GPA) and generate
transcripts
•In the early days, database
applications were built directly on top
of file systems

Types of Databases
Thereareseveraltypesofdatabases,fewimportant
ofthemarebrieflyexplainedbelow.
Hierarchicaldatabases
Object-orienteddatabases
Relationaldatabases
NoSQLdatabases

Hierarchical Databases
•Thisdatabasefollowstheprogressionofdatabeingcategorized
inranksorlevels,whereindataiscategorizedbasedona
commonpointoflinkage.

Object-OrientedDatabases
Informationstoredinadatabaseiscapableofbeing
representedasanobjectwhichresponseasaninstanceof
thedatabasemodel.Therefore,theobjectcanbereferenced
andcalledwithoutanydifficulty

Relational Databases
Inthisdatabase,everypieceofinformationhasarelationshipwith
everyotherpieceofinformation.Thisisonaccountofeverydata
valueinthedatabasehavingauniqueidentityintheformofarecord.

NoSQL Databases
ANoSQLoriginallyreferringtononSQLornon-relationalisa
databasethatprovidesamechanismforstorageandretrievalofdata.
Thisdataismodeledinmeansotherthanthetabularrelationsusedin
relationaldatabases.

Database Management System
(DBMS)
•DBMS contains information about a particular enterprise
–Collection of interrelated data
–Set of programs to access the data
–An environment that is both convenientand efficientto use
•Database Applications:
–Banking: transactions
–Airlines: reservations, schedules
–Universities: registration, grades
–Sales: customers, products, purchases
–Online retailers: order tracking, customized recommendations
–Manufacturing: production, inventory, orders, supply chain
–Human resources: employee records, salaries, tax deductions
•Databases can be very large.
•Databases touch all aspects of our lives

Drawbacks of using file systems to store data
•Data redundancy and inconsistency
–Multiple file formats, duplication of
information in different files
•Difficulty in accessing data
–Need to write a new program to carry out each
new task
•Data isolation
–Multiple files and formats
•Integrity problems
–Integrity constraints (e.g., account balance >
0) become “buried” in program code rather

Drawbacks of using file systems to store data (Cont.)
•Atomicity of updates
–Failures may leave database in an inconsistent state
with partial updates carried out
–Example: Transfer of funds from one account to
another should either complete or not happen at all
•Concurrent access by multiple users
–Concurrent access needed for performance
–Uncontrolled concurrent accesses can lead to
inconsistencies
•Example: Two people reading a balance (say 100) and
updating it by withdrawing money (say 50 each) at the
same time. Database systems offer solutions to all the
above problems

SQL Introduction
Standard language for querying and manipulating data
Structured Query Language
Many standards out there:
•ANSI SQL, SQL92 (a.k.a. SQL2), SQL99 (a.k.a. SQL3), ….
•Vendors support various subsets: watch for fun discussions in class !

SQL
•Data Definition Language (DDL)
–Create/alter/delete tables and their attributes
–Following lectures...
•Data Manipulation Language (DML)
–Query one or more tables –discussed next !
–Insert/delete/modify tuples in tables

Syntax to create a database
>Create database DabaseName;
--Syntax to create a table
>CREATE TABLE Table_Name(
Column_Name1 Data_Type(Size),
Column_Name2 Data_Type(Size));
>ALTER TABLE Table_NameADD New_Column_Name
Data_Type(Size);
>TRUNCATE TABLE Table_Name
>DROP TABLE Table_Name
DDL Syntax Commands

ListofDDLcommands:
•CREATE: This command is used to create the database or
its objects (like table, index, function, views, store
procedure, and triggers).
•DROP: This command is used to delete objects from the
database.
•ALTER:This is used to alter the structure of the database.
•TRUNCATE:This is used to remove all records from a
table, including all spaces allocated for the records are
removed.
•COMMENT: This is used to add comments to the data
dictionary.
•RENAME:This is used to rename an object existing in the
database.

Tables in SQL
PName Price CategoryManufacturer
Gizmo $19.99 GadgetsGizmoWorks
Powergizmo $29.99 GadgetsGizmoWorks
SingleTouch$149.99Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Attribute names
Table name
Tuples or rows

Tables Explained
•The schemaof a table is the table name and
its attributes:
Product(PName, Price, Category, Manfacturer)
•A keyis an attribute whose values are unique;
we underline a key
Product(PName, Price, Category, Manfacturer)

Data Types in SQL
•Atomic types:
–Characters: CHAR(20), VARCHAR(50)
–Numbers: INT, BIGINT, SMALLINT, FLOAT
–Others: MONEY, DATETIME, …
•Every attribute must have an atomic type
–Hence tables are flat
–Why ?

Tables Explained
•A tuple = a record
–Restriction: all attributes are of atomic type
•A table = a set of tuples
–Like a list…
–…but it is unorderd:
no first(), no next(), no last().

SQL Query
Basic form: (plus many manymore bells and whistles)
Retrieving Data
SELECT <attributes>
FROM <one or more relations>
WHERE<conditions>
•SELECTidentifiesthecolumnsto bedisplayed
•FROMidentifiesthetablecontainingthosecolumns

SelectingAllColumns
SELECT*
FROM departments;

Selecting SpecificColumns
department_id,location_idSELECT
FROM departments;

Simple SQL Query
PName Price CategoryManufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECT*
FROM Product
WHEREcategory=‘Gadgets’
Product
PName Price CategoryManufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
“selection”

Simple SQL Query
PName Price CategoryManufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECTPName, Price, Manufacturer
FROM Product
WHEREPrice > 100
Product
PName Price Manufacturer
SingleTouch $149.99 Canon
MultiTouch $203.99 Hitachi
“selection” and
“projection”

Notation
Product(PName, Price, Category, Manfacturer)
Answer(PName, Price, Manfacturer)
Input Schema
Output Schema
SELECTPName, Price, Manufacturer
FROM Product
WHEREPrice > 100

Details
•Case insensitive:
–Same: SELECT Select select
–Same: Product product
–Different: ‘Seattle’ ‘seattle’
•Constants:
–‘abc’ -yes
–“abc” -no

The LIKEoperator
•s LIKEp: pattern matching on strings
•p may contain two special symbols:
–% = any sequence of characters
–_ = any single character
SELECT*
FROM Products
WHEREPName LIKE‘%gizmo%’

Eliminating Duplicates
SELECTDISTINCTcategory
FROM Product
Compare to:
SELECTcategory
FROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household

Ordering the Results
SELECTpname, price, manufacturer
FROM Product
WHEREcategory=‘gizmo’ AND price > 50
ORDER BYprice
Ordering is ascending, unless you specify the DESC keyword.

SELECTCategory
FROM Product
ORDER BYPName
PName Price CategoryManufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
?
SELECTDISTINCTcategory
FROM Product
ORDER BYcategory
SELECTDISTINCTcategory
FROM Product
ORDER BYPName
?
?

Keys and Foreign Keys
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch$149.99Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
CName StockPriceCountry
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
Key
Foreign
key

Filtering Data
Structured Query Language (SQL) allows filtering data
during querying.
TheGROUPBYstatementformsgroupsofthoserows
withthesamevaluesorsatisfyaspecific
expression.Forexample,supposeinadatabaseofschool
students,youmayneedtofindthestudentsinparticularage
groups.ThisiswhereGROUPBYstatementhelps.
TheGROUPBYstatementisusuallyusedalongwith
aggregate functions such
asCOUNT(),MIN(),MAX(),AVG(),SUM(),etc.Thishelps
usgrouptheresultantoutputofaquerybyoneormore
columns.

QUERY...
GROUP BY
EXPRESSION...

After insertion of the above entries table is displayed as shown
below :
Assumethatweneedtoprintalltheemploymentstatutesin
ourrelation(tableTEST)alongwiththenumberof
occurrencesintherelation.

Joins
JOINclauseisusedtocombinerowsfromtwoormoretables,
basedonarelatedcolumnbetweenthem.
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all products under $200 manufactured in Japan;
return their names and prices.
SELECTPName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
Join
between Product
and Company

Joins
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch$149.99Photography Canon
MultiTouch$203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
PName Price
SingleTouch$149.99
SELECTPName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200

More Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all Chinese companies that manufacture products
both in the ‘electronic’ and ‘toy’ categories
SELECTcname
FROM
WHERE

A Subtlety about Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all countries that manufacture some product in the
‘Gadgets’ category.
SELECTCountry
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’
Unexpected duplicates

A Subtlety about Joins
Name Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch$149.99Photography Canon
MultiTouch$203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
Country
??
??
What is
the problem ?
What’s the
solution ?
SELECTCountry
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’

Tuple Variables
SELECTDISTINCTpname, address
FROM Person, Company
WHERE worksfor = cname
Which
address ?
Person(pname, address, worksfor)
Company(cname, address)
SELECTDISTINCTPerson.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname
SELECTDISTINCTx.pname, y.address
FROM Person AS x, Company AS y
WHERE x.worksfor = y.cname

Meaning (Semantics) of SQL
Queries
SELECTa
1, a
2, …, a
k
FROMR
1AS x
1, R
2AS x
2, …, R
nAS x
n
WHEREConditions
Answer = {}
forx
1inR
1do
forx
2inR
2do
…..
forx
ninR
ndo
ifConditions
thenAnswer = Answer {(a
1,…,a
k)}
returnAnswer

SELECTDISTINCTR.A
FROMR, S, T
WHERER.A=S.A OR R.A=T.A
An Unintuitive Query
Computes R (S T) But what if S = f?
What does it compute ?

Subqueries Returning Relations
SELECTCompany.city
FROM Company
WHERECompany.name IN
(SELECTProduct.maker
FROMPurchase , Product
WHEREProduct.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
Return cities where one can find companies that manufacture
products bought by Joe Blow
Company(name, city)
Product(pname, maker)
Purchase(id, product, buyer)

Subqueries Returning Relations
SELECTCompany.city
FROM Company, Product, Purchase
WHERECompany.name= Product.maker
AND Product.pname = Purchase.product
AND Purchase.buyer = ‘Joe Blow’
Is it equivalent to this ?
Beware of duplicates !

Removing Duplicates
Now
they are
equivalent
SELECTDISTINCTCompany.city
FROM Company
WHERECompany.name IN
(SELECTProduct.maker
FROMPurchase , Product
WHEREProduct.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
SELECTDISTINCTCompany.city
FROM Company, Product, Purchase
WHERECompany.name= Product.maker
AND Product.pname = Purchase.product
AND Purchase.buyer = ‘Joe Blow’

Subqueries Returning Relations
SELECTname
FROM Product
WHEREprice > ALL(SELECTprice
FROM Purchase
WHEREmaker=‘Gizmo-Works’)
Product ( pname, price, category, maker)
Find products that are more expensive than all those produced
By “Gizmo-Works”
You can also use: s > ALL R
s > ANY R
EXISTS R

Question for Database Fans
and their Friends
•Can we express this query as a single
SELECT-FROM-WHERE query, without
subqueries ?

Question for Database Fans
and their Friends
•Answer: all SFW queries are
monotone(figure out what this means).
A query with ALLis not monotone

Correlated Queries
SELECTDISTINCTtitle
FROMMovie AS x
WHEREyear <> ANY
(SELECTyear
FROMMovie
WHEREtitle = x.title);
Movie (title, year, director, length)
Find movies whose title appears more than once.
Note (1) scope of variables (2) this can still be expressed as single SFW
correlation

Complex Correlated Query
Product ( pname, price, category, maker, year)
•Find products (and their manufacturers) that are more expensive
than all products made by the same manufacturer before 1972
Very powerful ! Also much harder to optimize.
SELECT DISTINCTpname, maker
FROM Product AS x
WHEREprice > ALL(SELECTprice
FROMProduct AS y
WHEREx.maker = y.maker AND y.year < 1972);

Aggregation
SELECTcount(*)
FROM Product
WHEREyear > 1995
Except count, all aggregations apply to a single attribute
SELECTavg(price)
FROM Product
WHERE maker=“Toyota”
SQL supports several aggregation operations:
sum, count, min, max, avg

COUNT applies to duplicates, unless otherwise stated:
SELECTCount(category)
FROM Product
WHEREyear > 1995
same as Count(*)
We probably want:
SELECTCount(DISTINCTcategory)
FROM Product
WHEREyear > 1995
Aggregation: Count

Purchase(product, date, price, quantity)
More Examples
SELECTSum(price * quantity)
FROM Purchase
SELECTSum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
What do
they mean ?

Simple Aggregations
Purchase
ProductDate PriceQuantity
Bagel 10/21 1 20
Banana 10/3 0.5 10
Banana10/10 1 10
Bagel 10/25 1.50 20
SELECTSum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
50 (= 20+30)

Grouping and Aggregation
Purchase(product, date, price, quantity)
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BYproduct
Let’s see what this means…
Find total sales after 10/1/2005 per product.

Grouping and Aggregation
1. Compute the FROMand WHEREclauses.
2. Group by the attributes in the GROUPBY
3. Compute the SELECTclause: grouped attributes and aggregates.

1&2. FROM-WHERE-GROUPBY
ProductDate PriceQuantity
Bagel 10/21 1 20
Bagel 10/25 1.50 20
Banana 10/3 0.5 10
Banana10/10 1 10

3. SELECT
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BYproduct
ProductDate PriceQuantity
Bagel10/21 1 20
Bagel10/251.50 20
Banana 10/3 0.5 10
Banana10/10 1 10
ProductTotalSales
Bagel 50
Banana 15

GROUP BY v.s. Nested Quereis
SELECT product, Sum(price*quantity) ASTotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BYproduct
SELECT DISTINCTx.product, (SELECTSum(y.price*y.quantity)
FROM Purchase y
WHEREx.product = y.product
AND y.date > ‘10/1/2005’)
ASTotalSales
FROM Purchase x
WHERE x.date > ‘10/1/2005’

Another Example
SELECT product,
sum(price * quantity) AS SumSales
max(quantity) AS MaxQuantity
FROM Purchase
GROUP BYproduct
What does
it mean ?

HAVING Clause
SELECT product, Sum(price * quantity)
FROM Purchase
WHERE date > ‘10/1/2005’
GROUPBYproduct
HAVING Sum(quantity) > 30
Same query, except that we consider only products that had
at least 100 buyers.
HAVING clause contains conditions on aggregates.

General form of Grouping and
Aggregation
SELECTS
FROM R
1,…,R
n
WHERE C1
GROUP BYa
1,…,a
k
HAVING C2
S = may contain attributes a
1,…,a
kand/or any aggregates but NO OTHER
ATTRIBUTES
C1 = is any condition on the attributes in R
1,…,R
n
C2 = is any condition on aggregate expressions
Why ?

General form of Grouping and
Aggregation
Evaluation steps:
1.Evaluate FROM-WHERE, apply condition C1
2.Group by the attributes a
1,…,a
k
3.Apply condition C2 to each group (may have aggregates)
4.Compute aggregates in S and return the result
SELECTS
FROM R
1,…,R
n
WHERE C1
GROUP BYa
1,…,a
k
HAVING C2

Advanced SQLizing
1.Getting around INTERSECT and EXCEPT
2.Quantifiers
3.Aggregation v.s. subqueries

1. INTERSECT and EXCEPT:
(SELECTR.A, R.B
FROMR)
INTERSECT
(SELECTS.A, S.B
FROMS)
SELECTR.A, R.B
FROMR
WHERE
EXISTS(SELECT*
FROMS
WHERER.A=S.A and R.B=S.B)
(SELECTR.A, R.B
FROMR)
EXCEPT
(SELECTS.A, S.B
FROMS)
SELECTR.A, R.B
FROMR
WHERE
NOTEXISTS(SELECT*
FROMS
WHERER.A=S.A and R.B=S.B)
If R, S have no
duplicates, then can
write without
subqueries
(HOW ?)
INTERSECT and EXCEPT: not in SQL Server

2. Quantifiers
Product ( pname, price, company)
Company( cname, city)
Find all companies that make someproducts with price < 100
SELECT DISTINCTCompany.cname
FROM Company, Product
WHERECompany.cname = Product.company and Product.price < 100
Existential: easy ! 

2. Quantifiers
Product ( pname, price, company)
Company( cname, city)
Find all companies s.t. allof their products have price < 100
Universal: hard ! 
Find all companies that make onlyproducts with price < 100
same as:

2. Quantifiers
2. Find all companies s.t. alltheir products have price < 100
1. Find the other companies: i.e. s.t. someproduct 100
SELECT DISTINCTCompany.cname
FROM Company
WHERECompany.cname IN(SELECTProduct.company
FROMProduct
WHEREProduc.price >= 100
SELECT DISTINCTCompany.cname
FROM Company
WHERECompany.cname NOTIN(SELECTProduct.company
FROMProduct
WHEREProduc.price >= 100

3. Group-by v.s. Nested Query
•Find authors who wrote 10 documents:
•Attempt 1: with nested queries
SELECTDISTINCTAuthor.name
FROM Author
WHERE count(SELECTWrote.url
FROMWrote
WHEREAuthor.login=Wrote.login)
> 10
This is
SQL by
a novice
Author(login,name)
Wrote(login,url)

3. Group-by v.s. Nested Query
•Find all authors who wrote at least 10
documents:
•Attempt 2: SQL style (with GROUP BY)
SELECT Author.name
FROM Author, Wrote
WHERE Author.login=Wrote.login
GROUP BYAuthor.name
HAVING count(wrote.url) > 10
This is
SQL by
an expert
No need for DISTINCT: automatically from GROUP BY

3. Group-by v.s. Nested Query
Find authors with vocabulary 10000 words:
SELECT Author.name
FROM Author, Wrote, Mentions
WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url
GROUP BYAuthor.name
HAVING count(distinct Mentions.word) > 10000
Author(login,name)
Wrote(login,url)
Mentions(url,word)

Two Examples
Store(sid, sname)
Product(pid, pname, price, sid)
Find all stores that sell only products with price > 100
same as:
Find all stores s.t. all their products have price > 100)

SELECTStore.name
FROMStore, Product
WHEREStore.sid = Product.sid
GROUP BYStore.sid, Store.name
HAVING 100 < min(Product.price)
SELECTStore.name
FROMStore
WHEREStore.sid NOTIN
(SELECTProduct.sid
FROM Product
WHEREProduct.price <= 100)
SELECTStore.name
FROMStore
WHERE
100 < ALL(SELECTProduct.price
FROMproduct
WHEREStore.sid = Product.sid)
Almost equivalent…
Why both ?

Two Examples
Store(sid, sname)
Product(pid, pname, price, sid)
For each store,
find its most expensive product

Two Examples
SELECTStore.sname, max(Product.price)
FROMStore, Product
WHEREStore.sid = Product.sid
GROUP BYStore.sid, Store.sname
SELECTStore.sname, x.pname
FROMStore, Product x
WHEREStore.sid = x.sid and
x.price >=
ALL(SELECTy.price
FROMProduct y
WHEREStore.sid = y.sid)
This is easy but doesn’t do what we want:
Better:
But may
return
multiple
product names
per store

Two Examples
SELECTStore.sname, max(x.pname)
FROMStore, Product x
WHEREStore.sid = x.sid and
x.price >=
ALL(SELECTy.price
FROMProduct y
WHEREStore.sid = y.sid)
GROUP BYStore.sname
Finally, choose some pid arbitrarily, if there are many
with highest price:

NULLS in SQL
•Whenever we don’t have a value, we can put a NULL
•Can mean many things:
–Value does not exists
–Value exists but is unknown
–Value not applicable
–Etc.
•The schema specifies for each attribute if can be null
(nullable attribute) or not
•How does SQL cope with tables that have NULLs ?

Null Values
•If x= NULL then 4*(3-x)/7 is still NULL
•If x= NULL then x=“Joe” is UNKNOWN
•In SQL there are three boolean values:
FALSE = 0
UNKNOWN = 0.5
TRUE = 1

Null Values
•C1 AND C2 = min(C1, C2)
•C1 OR C2 = max(C1, C2)
•NOT C1 = 1 –C1
Rule in SQL: include only tuples that yield TRUE
SELECT*
FROMPerson
WHERE(age < 25) AND
(height > 6 OR weight > 190)
E.g.
age=20
heigth=NULL
weight=200

Null Values
Unexpected behavior:
Some Persons are not included !
SELECT*
FROM Person
WHEREage < 25 OR age >= 25

Null Values
Can test for NULL explicitly:
–x IS NULL
–x IS NOT NULL
Now it includes all Persons
SELECT*
FROM Person
WHEREage < 25 OR age >= 25 OR age IS NULL

Outerjoins
Explicit joins in SQL = “inner joins”:
Product(name, category)
Purchase(prodName, store)
SELECTProduct.name, Purchase.store
FROM Product JOINPurchase ON
Product.name = Purchase.prodName
SELECTProduct.name, Purchase.store
FROM Product, Purchase
WHEREProduct.name = Purchase.prodName
Same as:
But Products that never sold will be lost !

Outerjoins
Left outer joins in SQL:
Product(name, category)
Purchase(prodName, store)
SELECTProduct.name, Purchase.store
FROM Product LEFT OUTER JOINPurchase ON
Product.name = Purchase.prodName

Name Category
Gizmo gadget
Camera Photo
OneClick Photo
ProdName Store
Gizmo Wiz
Camera Ritz
Camera Wiz
Name Store
Gizmo Wiz
Camera Ritz
Camera Wiz
OneClick NULL
Product Purchase

Application
Compute, for each product, the total number of sales in ‘September’
Product(name, category)
Purchase(prodName, month, store)
SELECTProduct.name, count(*)
FROM Product, Purchase
WHEREProduct.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
What’s wrong ?

Application
Compute, for each product, the total number of sales in ‘September’
Product(name, category)
Purchase(prodName, month, store)
SELECTProduct.name, count(*)
FROM Product LEFT OUTER JOINPurchase ON
Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
Now we also get the products who sold in 0 quantity

Outer Joins
•Left outer join:
–Include the left tuple even if there’s no match
•Right outer join:
–Include the right tuple even if there’s no match
•Full outer join:
–Include the both left and right tuples even if there’s no
match

Modifying the Database
Three kinds of modifications
•Insertions
•Deletions
•Updates
Sometimes they are all called “updates”

Insertions
General form:
Missing attribute NULL.
May drop attribute names if give them in order.
INSERT INTOR(A1,…., An) VALUES(v1,…., vn)
INSERT INTOPurchase(buyer, seller, product, store)
VALUES(‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’,
‘The Sharper Image’)
Example: Insert a new purchase to the database:

Insertions
INSERT INTOPRODUCT(name)
SELECT DISTINCTPurchase.product
FROM Purchase
WHEREPurchase.date > “10/26/01”
The query replaces the VALUES keyword.
Here we insert manytuples into PRODUCT

Insertion: an Example
prodNameis foreign key in Product.name
Suppose database got corrupted and we need to fix it:
name listPricecategory
gizmo 100 gadgets
prodNamebuyerName price
camera John 200
gizmo Smith 80
camera Smith 225
Task: insert in Productall prodNamesfrom Purchase
Product
Product(name, listPrice, category)
Purchase(prodName, buyerName, price)
Purchase

Insertion: an Example
INSERT INTOProduct(name)
SELECT DISTINCTprodName
FROM Purchase
WHEREprodName NOT IN(SELECTname FROMProduct)
name listPricecategory
gizmo 100 Gadgets
camera - -

Insertion: an Example
INSERT INTOProduct(name, listPrice)
SELECT DISTINCTprodName, price
FROM Purchase
WHEREprodName NOT IN(SELECTname FROMProduct)
name listPricecategory
gizmo 100 Gadgets
camera 200 -
camera ?? 225 ?? - Depends on the implementation

Deletions
DELETE FROMPURCHASE
WHERE seller = ‘Joe’ AND
product = ‘Brooklyn Bridge’
Factoid about SQL: there is no way to delete only a single
occurrence of a tuple that appears twice
in a relation.
Example:

Updates
UPDATEPRODUCT
SETprice = price/2
WHEREProduct.name IN
(SELECTproduct
FROM Purchase
WHEREDate =‘Oct, 25, 1999’);
Example: