![Page 1: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/1.jpg)
CSE544: SQL
Monday 3/27 and Wednesday 3/29, 2006
![Page 2: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/2.jpg)
SQL IntroductionStandard 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 !
![Page 3: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/3.jpg)
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
![Page 4: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/4.jpg)
Tables in SQL
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
![Page 5: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/5.jpg)
Tables Explained
• 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)
![Page 6: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/6.jpg)
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 ?
![Page 7: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/7.jpg)
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().
![Page 8: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/8.jpg)
SQL Query
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>
![Page 9: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/9.jpg)
Simple SQL Query
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 ProductWHERE category=‘Gadgets’
SELECT *FROM ProductWHERE category=‘Gadgets’
Product
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks“selection”
![Page 10: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/10.jpg)
Simple SQL Query
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, ManufacturerFROM ProductWHERE Price > 100
SELECT PName, Price, ManufacturerFROM ProductWHERE Price > 100
Product
PName Price Manufacturer
SingleTouch $149.99 Canon
MultiTouch $203.99 Hitachi
“selection” and“projection”
![Page 11: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/11.jpg)
Notation
Product(PName, Price, Category, Manfacturer)
Answer(PName, Price, Manfacturer)
Input Schema
Output Schema
SELECT PName, Price, ManufacturerFROM ProductWHERE Price > 100
SELECT PName, Price, ManufacturerFROM ProductWHERE Price > 100
![Page 12: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/12.jpg)
Details
• Case insensitive:– Same: SELECT Select select– Same: Product product– Different: ‘Seattle’ ‘seattle’
• Constants:– ‘abc’ - yes– “abc” - no
![Page 13: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/13.jpg)
The LIKE operator
• s LIKE p: pattern matching on strings• p may contain two special symbols:
– % = any sequence of characters
– _ = any single character
SELECT *FROM ProductsWHERE PName LIKE ‘%gizmo%’
SELECT *FROM ProductsWHERE PName LIKE ‘%gizmo%’
![Page 14: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/14.jpg)
Eliminating Duplicates
SELECT DISTINCT categoryFROM Product
SELECT DISTINCT categoryFROM Product
Compare to:
SELECT categoryFROM Product
SELECT categoryFROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household
![Page 15: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/15.jpg)
Ordering the Results
SELECT pname, price, manufacturerFROM ProductWHERE category=‘gizmo’ AND price > 50ORDER BY price, pname
SELECT pname, price, manufacturerFROM ProductWHERE category=‘gizmo’ AND price > 50ORDER 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.
![Page 16: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/16.jpg)
SELECT CategoryFROM ProductORDER BY PName
SELECT CategoryFROM ProductORDER 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 categoryFROM ProductORDER BY category
SELECT DISTINCT categoryFROM ProductORDER BY category
SELECT DISTINCT categoryFROM ProductORDER BY PName
SELECT DISTINCT categoryFROM ProductORDER BY PName
?
?
![Page 17: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/17.jpg)
Keys and Foreign Keys
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
Foreignkey
![Page 18: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/18.jpg)
Joins
Product (pname, price, category, manufacturer)Company (cname, stockPrice, country)
Find all products under $200 manufactured in Japan;return their names and prices.
SELECT PName, PriceFROM Product, CompanyWHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
SELECT PName, PriceFROM Product, CompanyWHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
Joinbetween Product
and Company
![Page 19: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/19.jpg)
Joins
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, PriceFROM Product, CompanyWHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
SELECT PName, PriceFROM Product, CompanyWHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
![Page 20: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/20.jpg)
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
SELECT cname
FROM
WHERE
SELECT cname
FROM
WHERE
![Page 21: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/21.jpg)
A Subtlety about Joins
Product (pname, price, category, manufacturer)Company (cname, stockPrice, country)
Find all countries that manufacture some product in the ‘Gadgets’ category.
SELECT CountryFROM Product, CompanyWHERE Manufacturer=CName AND Category=‘Gadgets’
SELECT CountryFROM Product, CompanyWHERE Manufacturer=CName AND Category=‘Gadgets’
Unexpected duplicates
![Page 22: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/22.jpg)
A Subtlety about Joins
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 isthe problem ?
What’s thesolution ?
SELECT CountryFROM Product, CompanyWHERE Manufacturer=CName AND Category=‘Gadgets’
SELECT CountryFROM Product, CompanyWHERE Manufacturer=CName AND Category=‘Gadgets’
![Page 23: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/23.jpg)
Tuple Variables
SELECT DISTINCT pname, addressFROM Person, CompanyWHERE worksfor = cname
SELECT DISTINCT pname, addressFROM Person, CompanyWHERE worksfor = cname
Whichaddress ?
Person(pname, address, worksfor)Company(cname, address)
SELECT DISTINCT Person.pname, Company.addressFROM Person, CompanyWHERE Person.worksfor = Company.cname
SELECT DISTINCT Person.pname, Company.addressFROM Person, CompanyWHERE Person.worksfor = Company.cname
SELECT DISTINCT x.pname, y.addressFROM Person AS x, Company AS yWHERE x.worksfor = y.cname
SELECT DISTINCT x.pname, y.addressFROM Person AS x, Company AS yWHERE x.worksfor = y.cname
![Page 24: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/24.jpg)
Meaning (Semantics) of SQL Queries
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
![Page 25: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/25.jpg)
SELECT DISTINCT R.AFROM R, S, TWHERE R.A=S.A OR R.A=T.A
SELECT DISTINCT R.AFROM R, S, TWHERE R.A=S.A OR R.A=T.A
An Unintuitive Query
Computes R (S T) But what if S = ?
What does it compute ?
![Page 26: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/26.jpg)
Subqueries Returning Relations
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)
![Page 27: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/27.jpg)
Subqueries Returning Relations
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 !
![Page 28: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/28.jpg)
Removing Duplicates
Nowthey 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’
![Page 29: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/29.jpg)
Subqueries Returning Relations
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 producedBy “Gizmo-Works”
You can also use: s > ALL R s > ANY R EXISTS R
![Page 30: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/30.jpg)
Question for Database Fansand their Friends
• Can we express this query as a single SELECT-FROM-WHERE query, without subqueries ?
![Page 31: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/31.jpg)
Question for Database Fansand their Friends
• Answer: all SFW queries are monotone (figure out what this means). A query with ALL is not monotone
![Page 32: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/32.jpg)
Correlated Queries
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
![Page 33: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/33.jpg)
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 DISTINCT pname, makerFROM Product AS xWHERE price > ALL (SELECT price FROM Product AS y WHERE x.maker = y.maker AND y.year < 1972);
SELECT DISTINCT pname, makerFROM Product AS xWHERE price > ALL (SELECT price FROM Product AS y WHERE x.maker = y.maker AND y.year < 1972);
![Page 34: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/34.jpg)
Aggregation
SELECT count(*)FROM ProductWHERE year > 1995
SELECT count(*)FROM ProductWHERE year > 1995
Except count, all aggregations apply to a single attribute
SELECT avg(price)FROM ProductWHERE maker=“Toyota”
SELECT avg(price)FROM ProductWHERE maker=“Toyota”
SQL supports several aggregation operations:
sum, count, min, max, avg
![Page 35: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/35.jpg)
COUNT applies to duplicates, unless otherwise stated:
SELECT Count(category) FROM ProductWHERE year > 1995
SELECT Count(category) FROM ProductWHERE year > 1995
same as Count(*)
We probably want:
SELECT Count(DISTINCT category)FROM ProductWHERE year > 1995
SELECT Count(DISTINCT category)FROM ProductWHERE year > 1995
Aggregation: Count
![Page 36: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/36.jpg)
Purchase(product, date, price, quantity)
More Examples
SELECT Sum(price * quantity)FROM Purchase
SELECT Sum(price * quantity)FROM Purchase
SELECT Sum(price * quantity)FROM PurchaseWHERE product = ‘bagel’
SELECT Sum(price * quantity)FROM PurchaseWHERE product = ‘bagel’
What dothey mean ?
![Page 37: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/37.jpg)
Simple AggregationsPurchase
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 PurchaseWHERE product = ‘bagel’
SELECT Sum(price * quantity)FROM PurchaseWHERE product = ‘bagel’
50 (= 20+30)
![Page 38: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/38.jpg)
Grouping and AggregationPurchase(product, date, price, quantity)
SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > ‘10/1/2005’GROUP BY product
SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > ‘10/1/2005’GROUP BY product
Let’s see what this means…
Find total sales after 10/1/2005 per product.
![Page 39: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/39.jpg)
Grouping and Aggregation
1. Compute the FROM and WHERE clauses.
2. Group by the attributes in the GROUPBY
3. Compute the SELECT clause: grouped attributes and aggregates.
![Page 40: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/40.jpg)
1&2. FROM-WHERE-GROUPBY
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
![Page 41: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/41.jpg)
3. SELECT
SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > ‘10/1/2005’GROUP BY product
SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE 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
![Page 42: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/42.jpg)
GROUP BY v.s. Nested Quereis
SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > ‘10/1/2005’GROUP BY product
SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE 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 TotalSalesFROM Purchase xWHERE 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 TotalSalesFROM Purchase xWHERE x.date > ‘10/1/2005’
![Page 43: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/43.jpg)
Another Example
SELECT product, sum(price * quantity) AS SumSales max(quantity) AS MaxQuantityFROM PurchaseGROUP BY product
SELECT product, sum(price * quantity) AS SumSales max(quantity) AS MaxQuantityFROM PurchaseGROUP BY product
What doesit mean ?
![Page 44: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/44.jpg)
HAVING Clause
SELECT product, Sum(price * quantity)FROM PurchaseWHERE date > ‘10/1/2005’GROUP BY productHAVING Sum(quantity) > 30
SELECT product, Sum(price * quantity)FROM PurchaseWHERE date > ‘10/1/2005’GROUP BY productHAVING Sum(quantity) > 30
Same query, except that we consider only products that hadat least 100 buyers.
HAVING clause contains conditions on aggregates.
![Page 45: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/45.jpg)
General form of Grouping and Aggregation
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 ?
![Page 46: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/46.jpg)
General form of Grouping and Aggregation
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
![Page 47: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/47.jpg)
Advanced SQLizing
1. Getting around INTERSECT and EXCEPT
2. Quantifiers
3. Aggregation v.s. subqueries
![Page 48: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/48.jpg)
1. INTERSECT and EXCEPT:
(SELECT R.A, R.BFROM R) INTERSECT(SELECT S.A, S.BFROM S)
(SELECT R.A, R.BFROM R) INTERSECT(SELECT S.A, S.BFROM S)
SELECT R.A, R.BFROM RWHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)
SELECT R.A, R.BFROM RWHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)
(SELECT R.A, R.BFROM R) EXCEPT(SELECT S.A, S.BFROM S)
(SELECT R.A, R.BFROM R) EXCEPT(SELECT S.A, S.BFROM S)
SELECT R.A, R.BFROM RWHERE NOT EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)
SELECT R.A, R.BFROM RWHERE NOT EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)
If R, S have noduplicates, then can
write withoutsubqueries(HOW ?)
INTERSECT and EXCEPT: not in SQL Server
![Page 49: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/49.jpg)
2. Quantifiers
Product ( pname, price, company)Company( cname, city)
Find all companies that make some products with price < 100
SELECT DISTINCT Company.cnameFROM Company, ProductWHERE Company.cname = Product.company and Product.price < 100
SELECT DISTINCT Company.cnameFROM Company, ProductWHERE Company.cname = Product.company and Product.price < 100
Existential: easy !
![Page 50: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/50.jpg)
2. Quantifiers
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:
![Page 51: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/51.jpg)
2. Quantifiers
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.cnameFROM CompanyWHERE Company.cname IN (SELECT Product.company FROM Product WHERE Produc.price >= 100
SELECT DISTINCT Company.cnameFROM CompanyWHERE Company.cname IN (SELECT Product.company FROM Product WHERE Produc.price >= 100
SELECT DISTINCT Company.cnameFROM CompanyWHERE Company.cname NOT IN (SELECT Product.company FROM Product WHERE Produc.price >= 100
SELECT DISTINCT Company.cnameFROM CompanyWHERE Company.cname NOT IN (SELECT Product.company FROM Product WHERE Produc.price >= 100
![Page 52: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/52.jpg)
3. Group-by v.s. Nested Query
• Find authors who wrote 10 documents:
• Attempt 1: with nested queries
SELECT DISTINCT Author.nameFROM AuthorWHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10
SELECT DISTINCT Author.nameFROM AuthorWHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10
This isSQL bya novice
Author(login,name)
Wrote(login,url)
![Page 53: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/53.jpg)
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.nameFROM Author, WroteWHERE Author.login=Wrote.loginGROUP BY Author.nameHAVING count(wrote.url) > 10
SELECT Author.nameFROM Author, WroteWHERE Author.login=Wrote.loginGROUP BY Author.nameHAVING count(wrote.url) > 10
This isSQL byan expert
No need for DISTINCT: automatically from GROUP BY
![Page 54: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/54.jpg)
3. Group-by v.s. Nested Query
Find authors with vocabulary 10000 words:
SELECT Author.nameFROM Author, Wrote, MentionsWHERE Author.login=Wrote.login AND Wrote.url=Mentions.urlGROUP BY Author.nameHAVING count(distinct Mentions.word) > 10000
SELECT Author.nameFROM Author, Wrote, MentionsWHERE Author.login=Wrote.login AND Wrote.url=Mentions.urlGROUP BY Author.nameHAVING count(distinct Mentions.word) > 10000
Author(login,name)
Wrote(login,url)
Mentions(url,word)
![Page 55: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/55.jpg)
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)
![Page 56: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/56.jpg)
SELECT Store.nameFROM Store, ProductWHERE Store.sid = Product.sidGROUP BY Store.sid, Store.nameHAVING 100 < min(Product.price)
SELECT Store.nameFROM Store, ProductWHERE Store.sid = Product.sidGROUP BY Store.sid, Store.nameHAVING 100 < min(Product.price)
SELECT Store.nameFROM StoreWHERE Store.sid NOT IN (SELECT Product.sid FROM Product WHERE Product.price <= 100)
SELECT Store.nameFROM StoreWHERE Store.sid NOT IN (SELECT Product.sid FROM Product WHERE Product.price <= 100)
SELECT Store.nameFROM StoreWHERE 100 < ALL (SELECT Product.price FROM product WHERE Store.sid = Product.sid)
SELECT Store.nameFROM StoreWHERE 100 < ALL (SELECT Product.price FROM product WHERE Store.sid = Product.sid)
Almost equivalent…
Why both ?
![Page 57: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/57.jpg)
Two Examples
Store(sid, sname)Product(pid, pname, price, sid)
For each store, find its most expensive product
![Page 58: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/58.jpg)
Two Examples
SELECT Store.sname, max(Product.price)FROM Store, ProductWHERE Store.sid = Product.sidGROUP BY Store.sid, Store.sname
SELECT Store.sname, max(Product.price)FROM Store, ProductWHERE Store.sid = Product.sidGROUP BY Store.sid, Store.sname
SELECT Store.sname, x.pnameFROM Store, Product xWHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid)
SELECT Store.sname, x.pnameFROM Store, Product xWHERE 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 mayreturnmultiple product namesper store
![Page 59: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/59.jpg)
Two Examples
SELECT Store.sname, max(x.pname)FROM Store, Product xWHERE 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 xWHERE 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 manywith highest price:
![Page 60: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/60.jpg)
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 ?
![Page 61: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/61.jpg)
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
![Page 62: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/62.jpg)
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 *FROM PersonWHERE (age < 25) AND (height > 6 OR weight > 190)
SELECT *FROM PersonWHERE (age < 25) AND (height > 6 OR weight > 190)
E.g.age=20heigth=NULLweight=200
![Page 63: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/63.jpg)
Null Values
Unexpected behavior:
Some Persons are not included !
SELECT *FROM PersonWHERE age < 25 OR age >= 25
SELECT *FROM PersonWHERE age < 25 OR age >= 25
![Page 64: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/64.jpg)
Null Values
Can test for NULL explicitly:– x IS NULL– x IS NOT NULL
Now it includes all Persons
SELECT *FROM PersonWHERE age < 25 OR age >= 25 OR age IS NULL
SELECT *FROM PersonWHERE age < 25 OR age >= 25 OR age IS NULL
![Page 65: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/65.jpg)
OuterjoinsExplicit joins in SQL = “inner joins”:
Product(name, category) Purchase(prodName, store)
SELECT Product.name, Purchase.storeFROM Product JOIN Purchase ON Product.name = Purchase.prodName
SELECT Product.name, Purchase.storeFROM Product JOIN Purchase ON Product.name = Purchase.prodName
SELECT Product.name, Purchase.storeFROM Product, PurchaseWHERE Product.name = Purchase.prodName
SELECT Product.name, Purchase.storeFROM Product, PurchaseWHERE Product.name = Purchase.prodName
Same as:
But Products that never sold will be lost !
![Page 66: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/66.jpg)
Outerjoins
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
![Page 67: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/67.jpg)
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
![Page 68: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/68.jpg)
Application
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 ?
![Page 69: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/69.jpg)
Application
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
![Page 70: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/70.jpg)
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
![Page 71: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/71.jpg)
Modifying the Database
Three kinds of modifications
• Insertions
• Deletions
• Updates
Sometimes they are all called “updates”
![Page 72: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/72.jpg)
InsertionsGeneral 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:
![Page 73: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/73.jpg)
Insertions
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
![Page 74: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/74.jpg)
Insertion: an Example
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
![Page 75: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/75.jpg)
Insertion: an Example
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 - -
![Page 76: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/76.jpg)
Insertion: an Example
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
![Page 77: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/77.jpg)
Deletions
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:
![Page 78: CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006](https://reader035.vdocuments.net/reader035/viewer/2022062421/56649db35503460f94aa2a81/html5/thumbnails/78.jpg)
Updates
UPDATE PRODUCTSET price = price/2WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’);
UPDATE PRODUCTSET price = price/2WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’);
Example: