SlideShare a Scribd company logo
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 !
 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
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Attribute namesTable name
Tuples or rows
 The schema of a table is the table name and its
attributes:
Product(PName, Price, Category, Manfacturer)
 A key is an attribute whose values are unique;
we underline a key
Product(PName, Price, Category, Manfacturer)
 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 ?
 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().
Basic form: (plus many many more bells and whistles)
SELECT <attributes>
FROM <one or more relations>
WHERE <conditions>
SELECT <attributes>
FROM <one or more relations>
WHERE <conditions>
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECT *
FROM Product
WHERE category=‘Gadgets’
SELECT *
FROM Product
WHERE category=‘Gadgets’
Product
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
“selection”
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
Product
PName Price Manufacturer
SingleTouch $149.99 Canon
MultiTouch $203.99 Hitachi
“selection” and
“projection”
Product(PName, Price, Category, Manfacturer)
Answer(PName, Price, Manfacturer)
Input Schema
Output Schema
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
 Case insensitive:
◦ Same: SELECT Select select
◦ Same: Product product
◦ Different: ‘Seattle’ ‘seattle’
 Constants:
◦ ‘abc’ - yes
◦ “abc” - no
 s LIKE p: pattern matching on strings
 p may contain two special symbols:
◦ % = any sequence of characters
◦ _ = any single character
SELECT *
FROM Products
WHERE PName LIKE ‘%gizmo%’
SELECT *
FROM Products
WHERE PName LIKE ‘%gizmo%’
SELECT DISTINCT category
FROM Product
SELECT DISTINCT category
FROM Product
Compare to:
SELECT category
FROM Product
SELECT category
FROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household
SELECT pname, price, manufacturer
FROM Product
WHERE category=‘gizmo’ AND price > 50
ORDER BY price, pname
SELECT pname, price, manufacturer
FROM Product
WHERE category=‘gizmo’ AND price > 50
ORDER BY price, pname
Ties are broken by the second attribute on the ORDER BY list, etc.
Ordering is ascending, unless you specify the DESC keyword.
SELECT Category
FROM Product
ORDER BY PName
SELECT Category
FROM Product
ORDER BY PName
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
?
SELECT DISTINCT category
FROM Product
ORDER BY category
SELECT DISTINCT category
FROM Product
ORDER BY category
SELECT DISTINCT category
FROM Product
ORDER BY PName
SELECT DISTINCT category
FROM Product
ORDER BY PName
?
?
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
CName StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
Key
Foreign
key
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all products under $200 manufactured in Japan;
return their names and prices.
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
Join
between Product
and Company
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography 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
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all Chinese companies that manufacture products
both in the ‘electronic’ and ‘toy’ categories
SELECT cname
FROM
WHERE
SELECT cname
FROM
WHERE
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all countries that manufacture some product in the
‘Gadgets’ category.
SELECT Country
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’
SELECT Country
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’
Unexpected duplicates
Name Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography 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 ?
SELECT Country
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’
SELECT Country
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’
SELECT DISTINCT pname, address
FROM Person, Company
WHERE worksfor = cname
SELECT DISTINCT pname, address
FROM Person, Company
WHERE worksfor = cname
Which
address ?
Person(pname, address, worksfor)
Company(cname, address)
SELECT DISTINCT Person.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname
SELECT DISTINCT Person.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname
SELECT DISTINCT x.pname, y.address
FROM Person AS x, Company AS y
WHERE x.worksfor = y.cname
SELECT DISTINCT x.pname, y.address
FROM Person AS x, Company AS y
WHERE x.worksfor = y.cname
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions
Answer = {}
for x1 in R1 do
for x2 in R2 do
…..
for xn in Rn do
if Conditions
then Answer = Answer ∪ {(a1,…,ak)}
return Answer
Answer = {}
for x1 in R1 do
for x2 in R2 do
…..
for xn in Rn do
if Conditions
then Answer = Answer ∪ {(a1,…,ak)}
return Answer
SELECT DISTINCT R.A
FROM R, S, T
WHERE R.A=S.A OR R.A=T.A
SELECT DISTINCT R.A
FROM R, S, T
WHERE R.A=S.A OR R.A=T.A
Computes R ∩ (S ∪ T) But what if S = φ ?
What does it compute ?
SELECT Company.city
FROM Company
WHERE Company.name IN
(SELECT Product.maker
FROM Purchase , Product
WHERE Product.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
SELECT Company.city
FROM Company
WHERE Company.name IN
(SELECT Product.maker
FROM Purchase , Product
WHERE Product.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)
SELECT Company.city
FROM Company, Product, Purchase
WHERE Company.name= Product.maker
AND Product.pname = Purchase.product
AND Purchase.buyer = ‘Joe Blow’
SELECT Company.city
FROM Company, Product, Purchase
WHERE Company.name= Product.maker
AND Product.pname = Purchase.product
AND Purchase.buyer = ‘Joe Blow’
Is it equivalent to this ?
Beware of duplicates !
Now
they are
equivalent
SELECT DISTINCT Company.city
FROM Company
WHERE Company.name IN
(SELECT Product.maker
FROM Purchase , Product
WHERE Product.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
SELECT DISTINCT Company.city
FROM Company
WHERE Company.name IN
(SELECT Product.maker
FROM Purchase , Product
WHERE Product.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
SELECT DISTINCT Company.city
FROM Company, Product, Purchase
WHERE Company.name= Product.maker
AND Product.pname = Purchase.product
AND Purchase.buyer = ‘Joe Blow’
SELECT DISTINCT Company.city
FROM Company, Product, Purchase
WHERE Company.name= Product.maker
AND Product.pname = Purchase.product
AND Purchase.buyer = ‘Joe Blow’
SELECT name
FROM Product
WHERE price > ALL (SELECT price
FROM Purchase
WHERE maker=‘Gizmo-Works’)
SELECT name
FROM Product
WHERE price > ALL (SELECT price
FROM Purchase
WHERE maker=‘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
 Can we express this query as a single
SELECT-FROM-WHERE query, without
subqueries ?
 Answer: all SFW queries are
monotone (figure out what this
means). A query with ALL is not
monotone
SELECT DISTINCT title
FROM Movie AS x
WHERE year <> ANY
(SELECT year
FROM Movie
WHERE title = x.title);
SELECT DISTINCT title
FROM Movie AS x
WHERE year <> ANY
(SELECT year
FROM Movie
WHERE title = 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
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 DISTINCT pname, maker
FROM Product AS x
WHERE price > ALL (SELECT price
FROM Product AS y
WHERE x.maker = y.maker AND y.year < 1972);
SELECT DISTINCT pname, maker
FROM Product AS x
WHERE price > ALL (SELECT price
FROM Product AS y
WHERE x.maker = y.maker AND y.year < 1972);
SELECT count(*)
FROM Product
WHERE year > 1995
SELECT count(*)
FROM Product
WHERE year > 1995
Except count, all aggregations apply to a single attribute
SELECT avg(price)
FROM Product
WHERE maker=“Toyota”
SELECT avg(price)
FROM Product
WHERE maker=“Toyota”
SQL supports several aggregation operations:
sum, count, min, max, avg
COUNT applies to duplicates, unless otherwise stated:
SELECT Count(category)
FROM Product
WHERE year > 1995
SELECT Count(category)
FROM Product
WHERE year > 1995
same as Count(*)
We probably want:
SELECT Count(DISTINCT category)
FROM Product
WHERE year > 1995
SELECT Count(DISTINCT category)
FROM Product
WHERE year > 1995
Purchase(product, date, price, quantity)
SELECT Sum(price * quantity)
FROM Purchase
SELECT Sum(price * quantity)
FROM Purchase
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
What do
they mean ?
Purchase
Product Date Price Quantity
Bagel 10/21 1 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Bagel 10/25 1.50 20
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
50 (= 20+30)
Purchase(product, date, price, quantity)
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
Let’s see what this means…
Find total sales after 10/1/2005 per product.
1. Compute the FROM and WHERE clauses.
2. Group by the attributes in the GROUPBY
3. Compute the SELECT clause: grouped attributes and aggregates.
Product Date Price Quantity
Bagel 10/21 1 20
Bagel 10/25 1.50 20
Banana 10/3 0.5 10
Banana 10/10 1 10
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
Product Date Price Quantity
Bagel 10/21 1 20
Bagel 10/25 1.50 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Product TotalSales
Bagel 50
Banana 15
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity)
FROM Purchase y
WHERE x.product = y.product
AND y.date > ‘10/1/2005’)
AS TotalSales
FROM Purchase x
WHERE x.date > ‘10/1/2005’
SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity)
FROM Purchase y
WHERE x.product = y.product
AND y.date > ‘10/1/2005’)
AS TotalSales
FROM Purchase x
WHERE x.date > ‘10/1/2005’
SELECT product,
sum(price * quantity) AS SumSales
max(quantity) AS MaxQuantity
FROM Purchase
GROUP BY product
SELECT product,
sum(price * quantity) AS SumSales
max(quantity) AS MaxQuantity
FROM Purchase
GROUP BY product
What does
it mean ?
SELECT product, Sum(price * quantity)
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
HAVING Sum(quantity) > 30
SELECT product, Sum(price * quantity)
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
HAVING Sum(quantity) > 30
Same query, except that we consider only products that had
at least 100 buyers.
HAVING clause contains conditions on aggregates.
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2
S = may contain attributes a1,…,ak and/or any aggregates but NO
OTHER ATTRIBUTES
C1 = is any condition on the attributes in R1,…,Rn
C2 = is any condition on aggregate expressions
Why ?
Evaluation steps:
1. Evaluate FROM-WHERE, apply condition C1
2. Group by the attributes a1,…,ak
3. Apply condition C2 to each group (may have
aggregates)
4. Compute aggregates in S and return the result
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2
1. Getting around INTERSECT and EXCEPT
2. Quantifiers
3. Aggregation v.s. subqueries
(SELECT R.A, R.B
FROM R)
INTERSECT
(SELECT S.A, S.B
FROM S)
(SELECT R.A, R.B
FROM R)
INTERSECT
(SELECT S.A, S.B
FROM S)
SELECT R.A, R.B
FROM R
WHERE
EXISTS(SELECT *
FROM S
WHERE R.A=S.A and R.B=S.B)
SELECT R.A, R.B
FROM R
WHERE
EXISTS(SELECT *
FROM S
WHERE R.A=S.A and R.B=S.B)
(SELECT R.A, R.B
FROM R)
EXCEPT
(SELECT S.A, S.B
FROM S)
(SELECT R.A, R.B
FROM R)
EXCEPT
(SELECT S.A, S.B
FROM S)
SELECT R.A, R.B
FROM R
WHERE
NOT EXISTS(SELECT *
FROM S
WHERE R.A=S.A and R.B=S.B)
SELECT R.A, R.B
FROM R
WHERE
NOT EXISTS(SELECT *
FROM S
WHERE R.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
Product ( pname, price, company)
Company( cname, city)
Find all companies that make some products with price < 100
SELECT DISTINCT Company.cname
FROM Company, Product
WHERE Company.cname = Product.company and Product.price < 100
SELECT DISTINCT Company.cname
FROM Company, Product
WHERE Company.cname = Product.company and Product.price < 100
Existential: easy ! 
Product ( pname, price, company)
Company( cname, city)
Find all companies s.t. all of their products have price < 100
Universal: hard ! 
Find all companies that make only products with price < 100
same as:
2. Find all companies s.t. all their products have price < 100
1. Find the other companies: i.e. s.t. some product ≥ 100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname IN (SELECT Product.company
FROM Product
WHERE Produc.price >= 100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname IN (SELECT Product.company
FROM Product
WHERE Produc.price >= 100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname NOT IN (SELECT Product.company
FROM Product
WHERE Produc.price >= 100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname NOT IN (SELECT Product.company
FROM Product
WHERE Produc.price >= 100
 Find authors who wrote ≥ 10 documents:
 Attempt 1: with nested queries
SELECT DISTINCT Author.name
FROM Author
WHERE count(SELECT Wrote.url
FROM Wrote
WHERE Author.login=Wrote.login)
> 10
SELECT DISTINCT Author.name
FROM Author
WHERE count(SELECT Wrote.url
FROM Wrote
WHERE Author.login=Wrote.login)
> 10
This is
SQL by
a novice
Author(login,name)
Wrote(login,url)
 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 BY Author.name
HAVING count(wrote.url) > 10
SELECT Author.name
FROM Author, Wrote
WHERE Author.login=Wrote.login
GROUP BY Author.name
HAVING count(wrote.url) > 10
This is
SQL by
an expert
No need for DISTINCT: automatically from GROUP BY
Find authors with vocabulary ≥ 10000 words:
SELECT Author.name
FROM Author, Wrote, Mentions
WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url
GROUP BY Author.name
HAVING count(distinct Mentions.word) > 10000
SELECT Author.name
FROM Author, Wrote, Mentions
WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url
GROUP BY Author.name
HAVING count(distinct Mentions.word) > 10000
Author(login,name)
Wrote(login,url)
Mentions(url,word)
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)
SELECT Store.name
FROM Store, Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.name
HAVING 100 < min(Product.price)
SELECT Store.name
FROM Store, Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.name
HAVING 100 < min(Product.price)
SELECT Store.name
FROM Store
WHERE Store.sid NOT IN
(SELECT Product.sid
FROM Product
WHERE Product.price <= 100)
SELECT Store.name
FROM Store
WHERE Store.sid NOT IN
(SELECT Product.sid
FROM Product
WHERE Product.price <= 100)
SELECT Store.name
FROM Store
WHERE
100 < ALL (SELECT Product.price
FROM product
WHERE Store.sid = Product.sid)
SELECT Store.name
FROM Store
WHERE
100 < ALL (SELECT Product.price
FROM product
WHERE Store.sid = Product.sid)
Almost equivalent…
Why both ?
Store(sid, sname)
Product(pid, pname, price, sid)
For each store,
find its most expensive product
SELECT Store.sname, max(Product.price)
FROM Store, Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.sname
SELECT Store.sname, max(Product.price)
FROM Store, Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.sname
SELECT Store.sname, x.pname
FROM Store, Product x
WHERE Store.sid = x.sid and
x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid)
SELECT Store.sname, x.pname
FROM Store, Product x
WHERE Store.sid = x.sid and
x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid)
This is easy but doesn’t do what we want:
Better:
But may
return
multiple
product names
per store
SELECT Store.sname, max(x.pname)
FROM Store, Product x
WHERE Store.sid = x.sid and
x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid)
GROUP BY Store.sname
SELECT Store.sname, max(x.pname)
FROM Store, Product x
WHERE Store.sid = x.sid and
x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid)
GROUP BY Store.sname
Finally, choose some pid arbitrarily, if there are many
with highest price:
 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 ?
 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
 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 *
FROM Person
WHERE (age < 25) AND
(height > 6 OR weight > 190)
SELECT *
FROM Person
WHERE (age < 25) AND
(height > 6 OR weight > 190)
E.g.
age=20
heigth=NULL
weight=200
Unexpected behavior:
Some Persons are not included !
SELECT *
FROM Person
WHERE age < 25 OR age >= 25
SELECT *
FROM Person
WHERE age < 25 OR age >= 25
Can test for NULL explicitly:
◦ x IS NULL
◦ x IS NOT NULL
Now it includes all Persons
SELECT *
FROM Person
WHERE age < 25 OR age >= 25 OR age IS NULL
SELECT *
FROM Person
WHERE age < 25 OR age >= 25 OR age IS NULL
Explicit joins in SQL = “inner joins”:
Product(name, category)
Purchase(prodName, store)
SELECT Product.name, Purchase.store
FROM Product JOIN Purchase ON
Product.name = Purchase.prodName
SELECT Product.name, Purchase.store
FROM Product JOIN Purchase ON
Product.name = Purchase.prodName
SELECT Product.name, Purchase.store
FROM Product, Purchase
WHERE Product.name = Purchase.prodName
SELECT Product.name, Purchase.store
FROM Product, Purchase
WHERE Product.name = Purchase.prodName
Same as:
But Products that never sold will be lost !
Left outer joins in SQL:
Product(name, category)
Purchase(prodName, store)
SELECT Product.name, Purchase.store
FROM Product LEFT OUTER JOIN Purchase ON
Product.name = Purchase.prodName
SELECT Product.name, Purchase.store
FROM Product LEFT OUTER JOIN Purchase 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
Compute, for each product, the total number of sales in
‘September’
Product(name, category)
Purchase(prodName, month, store)
SELECT Product.name, count(*)
FROM Product, Purchase
WHERE Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
SELECT Product.name, count(*)
FROM Product, Purchase
WHERE Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
What’s wrong ?
Compute, for each product, the total number of sales in
‘September’
Product(name, category)
Purchase(prodName, month, store)
SELECT Product.name, count(*)
FROM Product LEFT OUTER JOIN Purchase ON
Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
SELECT Product.name, count(*)
FROM Product LEFT OUTER JOIN Purchase ON
Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
Now we also get the products who sold in 0 quantity
 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
Three kinds of modifications
 Insertions
 Deletions
 Updates
Sometimes they are all called “updates”
General form:
Missing attribute → NULL.
May drop attribute names if give them in order.
INSERT INTO R(A1,…., An) VALUES (v1,…., vn)INSERT INTO R(A1,…., An) VALUES (v1,…., vn)
INSERT INTO Purchase(buyer, seller, product, store)
VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’,
‘The Sharper Image’)
INSERT INTO Purchase(buyer, seller, product, store)
VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’,
‘The Sharper Image’)
Example: Insert a new purchase to the database:
INSERT INTO PRODUCT(name)
SELECT DISTINCT Purchase.product
FROM Purchase
WHERE Purchase.date > “10/26/01”
INSERT INTO PRODUCT(name)
SELECT DISTINCT Purchase.product
FROM Purchase
WHERE Purchase.date > “10/26/01”
The query replaces the VALUES keyword.
Here we insert many tuples into PRODUCT
prodName is foreign key in Product.name
Suppose database got corrupted and we need to fix it:
name listPrice category
gizmo 100 gadgets
prodName buyerName price
camera John 200
gizmo Smith 80
camera Smith 225
Task: insert in Product all prodNames from Purchase
Product
Product(name, listPrice, category)
Purchase(prodName, buyerName, price)
Product(name, listPrice, category)
Purchase(prodName, buyerName, price)
Purchase
INSERT INTO Product(name)
SELECT DISTINCT prodName
FROM Purchase
WHERE prodName NOT IN (SELECT name FROM Product)
INSERT INTO Product(name)
SELECT DISTINCT prodName
FROM Purchase
WHERE prodName NOT IN (SELECT name FROM Product)
name listPrice category
gizmo 100 Gadgets
camera - -
INSERT INTO Product(name, listPrice)
SELECT DISTINCT prodName, price
FROM Purchase
WHERE prodName NOT IN (SELECT name FROM Product)
INSERT INTO Product(name, listPrice)
SELECT DISTINCT prodName, price
FROM Purchase
WHERE prodName NOT IN (SELECT name FROM Product)
name listPrice category
gizmo 100 Gadgets
camera 200 -
camera ?? 225 ?? - Depends on the implementation
DELETE FROM PURCHASE
WHERE seller = ‘Joe’ AND
product = ‘Brooklyn Bridge’
DELETE FROM PURCHASE
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:
UPDATE PRODUCT
SET price = price/2
WHERE Product.name IN
(SELECT product
FROM Purchase
WHERE Date =‘Oct, 25, 1999’);
UPDATE PRODUCT
SET price = price/2
WHERE Product.name IN
(SELECT product
FROM Purchase
WHERE Date =‘Oct, 25, 1999’);
Example:

More Related Content

Similar to Sql introduction

Oracle SQL ppt.ppt
Oracle SQL ppt.pptOracle SQL ppt.ppt
Oracle SQL ppt.ppt
MushDev
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
rahulnadola3
 
The Complete Presentation on SQL Server
The  Complete Presentation on SQL ServerThe  Complete Presentation on SQL Server
The Complete Presentation on SQL Server
krishna43511
 
Week 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.pptWeek 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.ppt
SajjadAbdullah4
 
lecture-sql(database query language).ppt
lecture-sql(database query language).pptlecture-sql(database query language).ppt
lecture-sql(database query language).ppt
pogerek867
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
PradeepaKannan6
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
JackpeterNdati
 
SQL Basics - Lecture.ppt
SQL Basics - Lecture.pptSQL Basics - Lecture.ppt
SQL Basics - Lecture.ppt
Erick Araújo
 
SQL BASICS.pptx
SQL BASICS.pptxSQL BASICS.pptx
SQL BASICS.pptx
JEEVA R
 
lecture sql server database basic for beginners
lecture sql server database basic for beginnerslecture sql server database basic for beginners
lecture sql server database basic for beginners
21awais
 
Data
DataData
lecture-SQL_Working.ppt
lecture-SQL_Working.pptlecture-SQL_Working.ppt
lecture-SQL_Working.ppt
LaviKushwaha
 
sql-basic.ppt
sql-basic.pptsql-basic.ppt
sql-basic.ppt
wondmhunegn
 
Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sql
Anuja Lad
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced Training
Moutasm Tamimi
 
Xamppinstallation edited
Xamppinstallation editedXamppinstallation edited
Xamppinstallation edited
Osama Ghandour Geris
 
SQL structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentation
JKarthickMyilvahanan
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
ImXaib
 

Similar to Sql introduction (20)

Oracle SQL ppt.ppt
Oracle SQL ppt.pptOracle SQL ppt.ppt
Oracle SQL ppt.ppt
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
The Complete Presentation on SQL Server
The  Complete Presentation on SQL ServerThe  Complete Presentation on SQL Server
The Complete Presentation on SQL Server
 
Week 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.pptWeek 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.ppt
 
lecture-sql(database query language).ppt
lecture-sql(database query language).pptlecture-sql(database query language).ppt
lecture-sql(database query language).ppt
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
SQL Basics - Lecture.ppt
SQL Basics - Lecture.pptSQL Basics - Lecture.ppt
SQL Basics - Lecture.ppt
 
SQL BASICS.pptx
SQL BASICS.pptxSQL BASICS.pptx
SQL BASICS.pptx
 
lecture sql server database basic for beginners
lecture sql server database basic for beginnerslecture sql server database basic for beginners
lecture sql server database basic for beginners
 
Data
DataData
Data
 
lecture-SQL_Working.ppt
lecture-SQL_Working.pptlecture-SQL_Working.ppt
lecture-SQL_Working.ppt
 
sql-basic.ppt
sql-basic.pptsql-basic.ppt
sql-basic.ppt
 
Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sql
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced Training
 
Xamppinstallation edited
Xamppinstallation editedXamppinstallation edited
Xamppinstallation edited
 
SQL structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentation
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
 

More from husnara mohammad

Jsp intro
Jsp introJsp intro
Jsp intro
husnara mohammad
 
Hibernate
HibernateHibernate
Hibernate
husnara mohammad
 
Spring frame work
Spring frame workSpring frame work
Spring frame work
husnara mohammad
 
Java intro
Java introJava intro
Java intro
husnara mohammad
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
husnara mohammad
 
Asp dot net
Asp dot netAsp dot net
Asp dot net
husnara mohammad
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
husnara mohammad
 
Selenium
SeleniumSelenium
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
husnara mohammad
 
C++ basics
C++ basicsC++ basics
C++ basics
husnara mohammad
 
Ajax basic intro
Ajax basic introAjax basic intro
Ajax basic intro
husnara mohammad
 
Backbone js
Backbone jsBackbone js
Backbone js
husnara mohammad
 
Web attacks
Web attacksWeb attacks
Web attacks
husnara mohammad
 

More from husnara mohammad (16)

Ajax
AjaxAjax
Ajax
 
Log4e
Log4eLog4e
Log4e
 
Jsp intro
Jsp introJsp intro
Jsp intro
 
Hibernate
HibernateHibernate
Hibernate
 
J2EE
J2EEJ2EE
J2EE
 
Spring frame work
Spring frame workSpring frame work
Spring frame work
 
Java intro
Java introJava intro
Java intro
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Asp dot net
Asp dot netAsp dot net
Asp dot net
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
Selenium
SeleniumSelenium
Selenium
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
C++ basics
C++ basicsC++ basics
C++ basics
 
Ajax basic intro
Ajax basic introAjax basic intro
Ajax basic intro
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Web attacks
Web attacksWeb attacks
Web attacks
 

Recently uploaded

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 

Sql introduction

  • 1. 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 !
  • 2.  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
  • 3. PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Attribute namesTable name Tuples or rows
  • 4.  The schema of a table is the table name and its attributes: Product(PName, Price, Category, Manfacturer)  A key is an attribute whose values are unique; we underline a key Product(PName, Price, Category, Manfacturer)
  • 5.  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 ?
  • 6.  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().
  • 7. Basic form: (plus many many more bells and whistles) SELECT <attributes> FROM <one or more relations> WHERE <conditions> SELECT <attributes> FROM <one or more relations> WHERE <conditions>
  • 8. PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT * FROM Product WHERE category=‘Gadgets’ SELECT * FROM Product WHERE category=‘Gadgets’ Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks “selection”
  • 9. PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 Product PName Price Manufacturer SingleTouch $149.99 Canon MultiTouch $203.99 Hitachi “selection” and “projection”
  • 10. Product(PName, Price, Category, Manfacturer) Answer(PName, Price, Manfacturer) Input Schema Output Schema SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100
  • 11.  Case insensitive: ◦ Same: SELECT Select select ◦ Same: Product product ◦ Different: ‘Seattle’ ‘seattle’  Constants: ◦ ‘abc’ - yes ◦ “abc” - no
  • 12.  s LIKE p: pattern matching on strings  p may contain two special symbols: ◦ % = any sequence of characters ◦ _ = any single character SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’ SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’
  • 13. SELECT DISTINCT category FROM Product SELECT DISTINCT category FROM Product Compare to: SELECT category FROM Product SELECT category FROM Product Category Gadgets Gadgets Photography Household Category Gadgets Photography Household
  • 14. SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname Ties are broken by the second attribute on the ORDER BY list, etc. Ordering is ascending, unless you specify the DESC keyword.
  • 15. SELECT Category FROM Product ORDER BY PName SELECT Category FROM Product ORDER BY PName PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi ? SELECT DISTINCT category FROM Product ORDER BY category SELECT DISTINCT category FROM Product ORDER BY category SELECT DISTINCT category FROM Product ORDER BY PName SELECT DISTINCT category FROM Product ORDER BY PName ? ?
  • 16. PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company CName StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan Key Foreign key
  • 17. Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 Join between Product and Company
  • 18. PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography 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 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
  • 19. Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all Chinese companies that manufacture products both in the ‘electronic’ and ‘toy’ categories SELECT cname FROM WHERE SELECT cname FROM WHERE
  • 20. Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all countries that manufacture some product in the ‘Gadgets’ category. SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’ SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’ Unexpected duplicates
  • 21. Name Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography 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 ? SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’ SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’
  • 22. SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname Which address ? Person(pname, address, worksfor) Company(cname, address) SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname SELECT DISTINCT x.pname, y.address FROM Person AS x, Company AS y WHERE x.worksfor = y.cname SELECT DISTINCT x.pname, y.address FROM Person AS x, Company AS y WHERE x.worksfor = y.cname
  • 23. SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions Answer = {} for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer ∪ {(a1,…,ak)} return Answer Answer = {} for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer ∪ {(a1,…,ak)} return Answer
  • 24. SELECT DISTINCT R.A FROM R, S, T WHERE R.A=S.A OR R.A=T.A SELECT DISTINCT R.A FROM R, S, T WHERE R.A=S.A OR R.A=T.A Computes R ∩ (S ∪ T) But what if S = φ ? What does it compute ?
  • 25. SELECT Company.city FROM Company WHERE Company.name IN (SELECT Product.maker FROM Purchase , Product WHERE Product.pname=Purchase.product AND Purchase .buyer = ‘Joe Blow‘); SELECT Company.city FROM Company WHERE Company.name IN (SELECT Product.maker FROM Purchase , Product WHERE Product.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)
  • 26. SELECT Company.city FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.pname = Purchase.product AND Purchase.buyer = ‘Joe Blow’ SELECT Company.city FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.pname = Purchase.product AND Purchase.buyer = ‘Joe Blow’ Is it equivalent to this ? Beware of duplicates !
  • 27. Now they are equivalent SELECT DISTINCT Company.city FROM Company WHERE Company.name IN (SELECT Product.maker FROM Purchase , Product WHERE Product.pname=Purchase.product AND Purchase .buyer = ‘Joe Blow‘); SELECT DISTINCT Company.city FROM Company WHERE Company.name IN (SELECT Product.maker FROM Purchase , Product WHERE Product.pname=Purchase.product AND Purchase .buyer = ‘Joe Blow‘); SELECT DISTINCT Company.city FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.pname = Purchase.product AND Purchase.buyer = ‘Joe Blow’ SELECT DISTINCT Company.city FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.pname = Purchase.product AND Purchase.buyer = ‘Joe Blow’
  • 28. SELECT name FROM Product WHERE price > ALL (SELECT price FROM Purchase WHERE maker=‘Gizmo-Works’) SELECT name FROM Product WHERE price > ALL (SELECT price FROM Purchase WHERE maker=‘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
  • 29.  Can we express this query as a single SELECT-FROM-WHERE query, without subqueries ?
  • 30.  Answer: all SFW queries are monotone (figure out what this means). A query with ALL is not monotone
  • 31. SELECT DISTINCT title FROM Movie AS x WHERE year <> ANY (SELECT year FROM Movie WHERE title = x.title); SELECT DISTINCT title FROM Movie AS x WHERE year <> ANY (SELECT year FROM Movie WHERE title = 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
  • 32. 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 DISTINCT pname, maker FROM Product AS x WHERE price > ALL (SELECT price FROM Product AS y WHERE x.maker = y.maker AND y.year < 1972); SELECT DISTINCT pname, maker FROM Product AS x WHERE price > ALL (SELECT price FROM Product AS y WHERE x.maker = y.maker AND y.year < 1972);
  • 33. SELECT count(*) FROM Product WHERE year > 1995 SELECT count(*) FROM Product WHERE year > 1995 Except count, all aggregations apply to a single attribute SELECT avg(price) FROM Product WHERE maker=“Toyota” SELECT avg(price) FROM Product WHERE maker=“Toyota” SQL supports several aggregation operations: sum, count, min, max, avg
  • 34. COUNT applies to duplicates, unless otherwise stated: SELECT Count(category) FROM Product WHERE year > 1995 SELECT Count(category) FROM Product WHERE year > 1995 same as Count(*) We probably want: SELECT Count(DISTINCT category) FROM Product WHERE year > 1995 SELECT Count(DISTINCT category) FROM Product WHERE year > 1995
  • 35. Purchase(product, date, price, quantity) SELECT Sum(price * quantity) FROM Purchase SELECT Sum(price * quantity) FROM Purchase SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ What do they mean ?
  • 36. Purchase Product Date Price Quantity Bagel 10/21 1 20 Banana 10/3 0.5 10 Banana 10/10 1 10 Bagel 10/25 1.50 20 SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ 50 (= 20+30)
  • 37. Purchase(product, date, price, quantity) SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product Let’s see what this means… Find total sales after 10/1/2005 per product.
  • 38. 1. Compute the FROM and WHERE clauses. 2. Group by the attributes in the GROUPBY 3. Compute the SELECT clause: grouped attributes and aggregates.
  • 39. Product Date Price Quantity Bagel 10/21 1 20 Bagel 10/25 1.50 20 Banana 10/3 0.5 10 Banana 10/10 1 10
  • 40. SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product Product Date Price Quantity Bagel 10/21 1 20 Bagel 10/25 1.50 20 Banana 10/3 0.5 10 Banana 10/10 1 10 Product TotalSales Bagel 50 Banana 15
  • 41. SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity) FROM Purchase y WHERE x.product = y.product AND y.date > ‘10/1/2005’) AS TotalSales FROM Purchase x WHERE x.date > ‘10/1/2005’ SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity) FROM Purchase y WHERE x.product = y.product AND y.date > ‘10/1/2005’) AS TotalSales FROM Purchase x WHERE x.date > ‘10/1/2005’
  • 42. SELECT product, sum(price * quantity) AS SumSales max(quantity) AS MaxQuantity FROM Purchase GROUP BY product SELECT product, sum(price * quantity) AS SumSales max(quantity) AS MaxQuantity FROM Purchase GROUP BY product What does it mean ?
  • 43. SELECT product, Sum(price * quantity) FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product HAVING Sum(quantity) > 30 SELECT product, Sum(price * quantity) FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product HAVING Sum(quantity) > 30 Same query, except that we consider only products that had at least 100 buyers. HAVING clause contains conditions on aggregates.
  • 44. SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2 S = may contain attributes a1,…,ak and/or any aggregates but NO OTHER ATTRIBUTES C1 = is any condition on the attributes in R1,…,Rn C2 = is any condition on aggregate expressions Why ?
  • 45. Evaluation steps: 1. Evaluate FROM-WHERE, apply condition C1 2. Group by the attributes a1,…,ak 3. Apply condition C2 to each group (may have aggregates) 4. Compute aggregates in S and return the result SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2 SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2
  • 46. 1. Getting around INTERSECT and EXCEPT 2. Quantifiers 3. Aggregation v.s. subqueries
  • 47. (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) SELECT R.A, R.B FROM R WHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B) SELECT R.A, R.B FROM R WHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B) (SELECT R.A, R.B FROM R) EXCEPT (SELECT S.A, S.B FROM S) (SELECT R.A, R.B FROM R) EXCEPT (SELECT S.A, S.B FROM S) SELECT R.A, R.B FROM R WHERE NOT EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B) SELECT R.A, R.B FROM R WHERE NOT EXISTS(SELECT * FROM S WHERE R.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
  • 48. Product ( pname, price, company) Company( cname, city) Find all companies that make some products with price < 100 SELECT DISTINCT Company.cname FROM Company, Product WHERE Company.cname = Product.company and Product.price < 100 SELECT DISTINCT Company.cname FROM Company, Product WHERE Company.cname = Product.company and Product.price < 100 Existential: easy ! 
  • 49. Product ( pname, price, company) Company( cname, city) Find all companies s.t. all of their products have price < 100 Universal: hard !  Find all companies that make only products with price < 100 same as:
  • 50. 2. Find all companies s.t. all their products have price < 100 1. Find the other companies: i.e. s.t. some product ≥ 100 SELECT DISTINCT Company.cname FROM Company WHERE Company.cname IN (SELECT Product.company FROM Product WHERE Produc.price >= 100 SELECT DISTINCT Company.cname FROM Company WHERE Company.cname IN (SELECT Product.company FROM Product WHERE Produc.price >= 100 SELECT DISTINCT Company.cname FROM Company WHERE Company.cname NOT IN (SELECT Product.company FROM Product WHERE Produc.price >= 100 SELECT DISTINCT Company.cname FROM Company WHERE Company.cname NOT IN (SELECT Product.company FROM Product WHERE Produc.price >= 100
  • 51.  Find authors who wrote ≥ 10 documents:  Attempt 1: with nested queries SELECT DISTINCT Author.name FROM Author WHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10 SELECT DISTINCT Author.name FROM Author WHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10 This is SQL by a novice Author(login,name) Wrote(login,url)
  • 52.  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 BY Author.name HAVING count(wrote.url) > 10 SELECT Author.name FROM Author, Wrote WHERE Author.login=Wrote.login GROUP BY Author.name HAVING count(wrote.url) > 10 This is SQL by an expert No need for DISTINCT: automatically from GROUP BY
  • 53. Find authors with vocabulary ≥ 10000 words: SELECT Author.name FROM Author, Wrote, Mentions WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url GROUP BY Author.name HAVING count(distinct Mentions.word) > 10000 SELECT Author.name FROM Author, Wrote, Mentions WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url GROUP BY Author.name HAVING count(distinct Mentions.word) > 10000 Author(login,name) Wrote(login,url) Mentions(url,word)
  • 54. 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)
  • 55. SELECT Store.name FROM Store, Product WHERE Store.sid = Product.sid GROUP BY Store.sid, Store.name HAVING 100 < min(Product.price) SELECT Store.name FROM Store, Product WHERE Store.sid = Product.sid GROUP BY Store.sid, Store.name HAVING 100 < min(Product.price) SELECT Store.name FROM Store WHERE Store.sid NOT IN (SELECT Product.sid FROM Product WHERE Product.price <= 100) SELECT Store.name FROM Store WHERE Store.sid NOT IN (SELECT Product.sid FROM Product WHERE Product.price <= 100) SELECT Store.name FROM Store WHERE 100 < ALL (SELECT Product.price FROM product WHERE Store.sid = Product.sid) SELECT Store.name FROM Store WHERE 100 < ALL (SELECT Product.price FROM product WHERE Store.sid = Product.sid) Almost equivalent… Why both ?
  • 56. Store(sid, sname) Product(pid, pname, price, sid) For each store, find its most expensive product
  • 57. SELECT Store.sname, max(Product.price) FROM Store, Product WHERE Store.sid = Product.sid GROUP BY Store.sid, Store.sname SELECT Store.sname, max(Product.price) FROM Store, Product WHERE Store.sid = Product.sid GROUP BY Store.sid, Store.sname SELECT Store.sname, x.pname FROM Store, Product x WHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid) SELECT Store.sname, x.pname FROM Store, Product x WHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid) This is easy but doesn’t do what we want: Better: But may return multiple product names per store
  • 58. SELECT Store.sname, max(x.pname) FROM Store, Product x WHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid) GROUP BY Store.sname SELECT Store.sname, max(x.pname) FROM Store, Product x WHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid) GROUP BY Store.sname Finally, choose some pid arbitrarily, if there are many with highest price:
  • 59.  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 ?
  • 60.  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
  • 61.  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 * FROM Person WHERE (age < 25) AND (height > 6 OR weight > 190) SELECT * FROM Person WHERE (age < 25) AND (height > 6 OR weight > 190) E.g. age=20 heigth=NULL weight=200
  • 62. Unexpected behavior: Some Persons are not included ! SELECT * FROM Person WHERE age < 25 OR age >= 25 SELECT * FROM Person WHERE age < 25 OR age >= 25
  • 63. Can test for NULL explicitly: ◦ x IS NULL ◦ x IS NOT NULL Now it includes all Persons SELECT * FROM Person WHERE age < 25 OR age >= 25 OR age IS NULL SELECT * FROM Person WHERE age < 25 OR age >= 25 OR age IS NULL
  • 64. Explicit joins in SQL = “inner joins”: Product(name, category) Purchase(prodName, store) SELECT Product.name, Purchase.store FROM Product JOIN Purchase ON Product.name = Purchase.prodName SELECT Product.name, Purchase.store FROM Product JOIN Purchase ON Product.name = Purchase.prodName SELECT Product.name, Purchase.store FROM Product, Purchase WHERE Product.name = Purchase.prodName SELECT Product.name, Purchase.store FROM Product, Purchase WHERE Product.name = Purchase.prodName Same as: But Products that never sold will be lost !
  • 65. Left outer joins in SQL: Product(name, category) Purchase(prodName, store) SELECT Product.name, Purchase.store FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName SELECT Product.name, Purchase.store FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName
  • 66. 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
  • 67. Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) SELECT Product.name, count(*) FROM Product, Purchase WHERE Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name SELECT Product.name, count(*) FROM Product, Purchase WHERE Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name What’s wrong ?
  • 68. Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) SELECT Product.name, count(*) FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name SELECT Product.name, count(*) FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name Now we also get the products who sold in 0 quantity
  • 69.  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
  • 70. Three kinds of modifications  Insertions  Deletions  Updates Sometimes they are all called “updates”
  • 71. General form: Missing attribute → NULL. May drop attribute names if give them in order. INSERT INTO R(A1,…., An) VALUES (v1,…., vn)INSERT INTO R(A1,…., An) VALUES (v1,…., vn) INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’) INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’) Example: Insert a new purchase to the database:
  • 72. INSERT INTO PRODUCT(name) SELECT DISTINCT Purchase.product FROM Purchase WHERE Purchase.date > “10/26/01” INSERT INTO PRODUCT(name) SELECT DISTINCT Purchase.product FROM Purchase WHERE Purchase.date > “10/26/01” The query replaces the VALUES keyword. Here we insert many tuples into PRODUCT
  • 73. prodName is foreign key in Product.name Suppose database got corrupted and we need to fix it: name listPrice category gizmo 100 gadgets prodName buyerName price camera John 200 gizmo Smith 80 camera Smith 225 Task: insert in Product all prodNames from Purchase Product Product(name, listPrice, category) Purchase(prodName, buyerName, price) Product(name, listPrice, category) Purchase(prodName, buyerName, price) Purchase
  • 74. INSERT INTO Product(name) SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) INSERT INTO Product(name) SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera - -
  • 75. INSERT INTO Product(name, listPrice) SELECT DISTINCT prodName, price FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) INSERT INTO Product(name, listPrice) SELECT DISTINCT prodName, price FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera 200 - camera ?? 225 ?? - Depends on the implementation
  • 76. DELETE FROM PURCHASE WHERE seller = ‘Joe’ AND product = ‘Brooklyn Bridge’ DELETE FROM PURCHASE 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:
  • 77. UPDATE PRODUCT SET price = price/2 WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’); UPDATE PRODUCT SET price = price/2 WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’); Example: