Final Revision 2
This presentation is the property of its rightful owner.
Sponsored Links
1 / 100

Prof. Sin-Min Lee PowerPoint PPT Presentation


  • 41 Views
  • Uploaded on
  • Presentation posted in: General

Final Revision 2. CS 157A Lecture 26. Prof. Sin-Min Lee. 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC). A) Which quizzes did a “CE” major score 100% on? { a[Q_num]: a  Quiz , s STUDENT ; t  Q_score, s[ufid]=t[ufid]  s[ufid]=“CE”

Download Presentation

Prof. Sin-Min Lee

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Prof sin min lee

Final Revision 2

CS 157A Lecture 26

Prof. Sin-Min Lee


3 student ufid major quiz q num point pos q score q num ufid points scored in trc

3) Student (ufid, major)Quiz(Q_num, point_pos)Q_score(q_num,ufid,points_scored) (in TRC)

A) Which quizzes did a “CE” major score 100% on?

{ a[Q_num]: a  Quiz ,s STUDENT ; t  Q_score, s[ufid]=t[ufid]  s[ufid]=“CE”

 a[Q_num]=t[q_num]

t[points_scored]=100% }

Relational Algebra:

q_num [ Quiz |x| (major=“CE” Student) |x| (points_scored=“100” Q_score))


Prof sin min lee

  • Consider the following relational database schema:

  • Pizza(pid, pname, size)

  • Store(sname, phone, quality)

  • Soldby(pid, sname, price)

  • Express each of the following queries in the relational algebra.

  • Find the name of all stores that sell both veggie and cheese pizza.

  • Answer:

  • sname(pname = ‘veggie’ Pizza |X| Soldby)

  • sname(pname = ‘cheese’ Pizza |X| Soldby)


Prof sin min lee

Consider the following relational database schema:

Pizza(pid, pname, size)

Store(sname, phone, quality)

Soldby(pid, sname, price)

Express each of the following queries in the relational algebra.

b) Find the names and phone numbers of all stores that sell good or excellent veggie pizza under $10.

Answer:

sname, phone((pname = ‘veggie’ Pizza) |X| (quality = ‘good’ Store) |X| (price < 10 Soldby))

sname, phone((pname = ‘veggie’ Pizza) |X| (quality = ‘excellent’ Store) |X| (price < 10 Soldby))


Prof sin min lee

Student (ufid, major)Quiz(Q_num, point_pos)Q_score(q_num,ufid,points_scoredb) Who are the “CE” major who missed Quiz 3?

{ s [ufid]:s  STUDENT. t Q_SCORE

 s[ufid]=“CE”

t[q_num ]=“3”  t[points_scored] =“null”

 s[ufid]=t[ufid] }


Prof sin min lee

Student (ufid, major)Quiz(Q_num, point_pos)Q_score(q_num,ufid,points_scoredc) Which students have a 0 score for 2 different quizzes?

{ s[ufid]: s  STUDENT t1, t2 Q_SCORE

s[ufid]=t1[ufid]= t2[ufid]

 t1[q_num] t2 [q_num]

 t1 [point_score]=t2 [point_score]=“0” }


Prof sin min lee

7) Author (aid, name, phone) with key =(aid)wrote(aid, isbn, order) with key =(aid, Isbn)book(isbn, title, publisher,dte) with key=(isbn)

a) Find the names of authors who wrote or co wrote books published in 1995

{a [name]: a Author w  WROTE b  Book

 a.aid=w.aid  w.isbn=b.isbn  b.date=1995}


Prof sin min lee

Author (aid, name, phone) with key =(aid)wrote(aid, isbn, order) with key =(aid, Isbn)book(isbn, title, publisher,dte) with key=(isbn)b) Find the names of authors who were always the first author of books they wrote

{ a[name]: a  Author,  w  Wrote, b  Book

 a.aid=w.aid  w.isbn = b.isbn  w.order=1 }


Prof sin min lee

Author (aid, name, phone) with key =(aid)wrote(aid, isbn, order) with key =(aid, Isbn)book(isbn, title, publisher,dte) with key=(isbn) c) Find the AID of author (if any) who have written or co written books published by every publisher of book?

Let Publisher = {b[publisher]: b  Book }

{ a[aid]: a  Author  p  Publisher  w  Wrote & b*  Book

& a [aid]=w[aid] & w[isbn]= b*[isbn] & b*[publisher]=p }


Prof sin min lee

6 c) Author (aid, name, phone) with key =(aid)wrote(aid, isbn, order) with key =(aid, Isbn)book(isbn, title, publisher,dte) with key=(isbn

Find the aid of authors (if any) who have written or co-written books published by every publisher of books? (Relational Algebra, TRC)

Relational Algebra:

Let T = publisherBook,

aid [ (Author |x| Wrote|x| Book) T ]


Data definition in sql

Data Definition in SQL

  • So far we have see the Data Manipulation Language, DML

  • Next: Data Definition Language (DDL)

  • Data types:

  • Defines the types.

  • Data definition: defining the schema.

  • Create tables

  • Delete tables

  • Modify table schema

  • Indexes: to improve performance


Data types in sql

Data Types in SQL

  • Characters:

    • CHAR(20)-- fixed length

    • VARCHAR(40)-- variable length

  • Numbers:

    • INT, REAL plus variations

  • Times and dates:

    • DATE, TIME (Pointbase)


Creating tables

Creating Tables

Example:

CREATE TABLE Person(

name VARCHAR(30),

social-security-number INT,

age SHORTINT,

city VARCHAR(30),

gender BIT(1),

Birthdate DATE

);


Sql queries

SQL Queries

  • Principal form:

    SELECT desired attributes

    FROM tuple variables –– range over relations

    WHERE condition about tuple variables;

    Running example relation schema:

    Beers(name, manf)

    Bars(name, addr, license)

    Drinkers(name, addr, phone)

    Likes(drinker, beer)

    Sells(bar, beer, price)

    Frequents(drinker, bar)


Example

Example

What beers are made by Anheuser-Busch?

Beers(name, manf)

SELECT name

FROM Beers

WHERE manf = 'Anheuser-Busch';

  • Note: single quotes for strings.

    name

    Bud

    Bud Lite

    Michelob


Union intersection difference

Union, Intersection, Difference

(SELECT name

FROM Person

WHERE City=“Seattle”)

UNION

(SELECT name

FROM Person, Purchase

WHERE buyer=name AND store=“The Bon”)

Similarly, you can use INTERSECT and EXCEPT.

You must have the same attribute names (otherwise: rename).


Formal semantics of single relation sql query

Formal Semanticsof Single-Relation SQL Query

  • Start with the relation in the FROM clause.

  • Apply (bag) , using condition in WHERE clause.

  • Apply (extended, bag)  using attributes in SELECT clause.

    Equivalent Operational Semantics

    Imagine a tuple variable ranging over all tuples of the relation. For each tuple:

  • Check if it satisfies the WHERE clause.

  • Print the values of terms in SELECT, if so.


Star as list of all attributes

Star as List of All Attributes

Beers(name, manf)

SELECT *

FROM Beers

WHERE manf = 'Anheuser-Busch';

namemanf

BudAnheuser-Busch

Bud LiteAnheuser-Busch

MichelobAnheuser-Busch


Renaming columns

Renaming columns

Beers(name, manf)

SELECT name AS beer

FROM Beers

WHERE manf = 'Anheuser-Busch';

beer

Bud

Bud Lite

Michelob


Expressions as values in columns

Expressions as Values in Columns

Sells(bar, beer, price)

SELECT bar, beer,

price*120 AS priceInYen

FROM Sells;

barbeerpriceInYen

Joe’sBud300

Sue’sMiller360

………

  • Note: no WHERE clause is OK.


Prof sin min lee

  • Trick: If you want an answer with a particular string in each row, use that constant as an expression.

    Likes(drinker, beer)

    SELECT drinker,

    'likes Bud' AS whoLikesBud

    FROM Likes

    WHERE beer = 'Bud';

    drinkerwhoLikesBud

    Sallylikes Bud

    Fred likes Bud

    ……


Example1

Example

  • Find the price Joe's Bar charges for Bud.

    Sells(bar, beer, price)

    SELECT price

    FROM Sells

    WHERE bar = 'Joe''s Bar' AND

    beer = 'Bud';

  • Note: two single-quotes in a character string represent one single quote.

  • Conditions in WHERE clause can use logical operators AND, OR, NOT and parentheses in the usual way.

  • Remember: SQL is case insensitive. Keywords like SELECT or AND can be written upper/lower case as you like.

    • Only inside quoted strings does case matter.


Updates

Updates

UPDATE relation SET list of assignments WHERE condition.

Example

Drinker Fred's phone number is 555-1212.

Drinkers(name, addr, phone)

UPDATE Drinkers

SET phone = '555-1212'

WHERE name = 'Fred';

Example

Make $4 the maximum price for beer.

  • Updates many tuples at once.

    Sells(bar, beer, price)

    UPDATE Sells

    SET price = 4.00

    WHERE price > 4.00;


Modifying the database

Modifying the Database

Three kinds of modifications

  • Insertions

  • Deletions

  • Updates

    Sometimes they are all called “updates”


Deleting or modifying a table

Deleting or Modifying a Table

Deleting:

Exercise with care !!

Example:

DROP Person;

Altering: (adding or removing an attribute).

ALTER TABLE Person

ADD phone CHAR(16);

ALTER TABLE Person

DROP age;

Example:

What happens when you make changes to the schema?


Default values

Default Values

Specifying default values:

CREATE TABLE Person(

name VARCHAR(30),

social-security-number INT,

age SHORTINT DEFAULT 100,

city VARCHAR(30) DEFAULT ‘Seattle’,

gender CHAR(1) DEFAULT ‘?’,

Birthdate DATE

The default of defaults: NULL


Conserving duplicates

Conserving Duplicates

(SELECT name

FROM Person

WHERE City=“Seattle”)

UNIONALL

(SELECT name

FROM Person, Purchase

WHERE buyer=name AND store=“The Bon”)


Insertions

Insertions

General form:

INSERT INTO R(A1,…., An) VALUES (v1,…., vn)

Example: Insert a new purchase to the database:

INSERT INTO Purchase(buyer, seller, product, store)

VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’)

Missing attribute  NULL.

May drop attribute names if give them in order.


Insertions1

Insertions

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


Insertion an example

Insertion: an Example

Product(name, listPrice, category)

Purchase(prodName, buyerName, price)

prodName is foreign key in Product.name

Suppose database got corrupted and we need to fix it:

corrupted

Purchase

Product

Task: insert in Product all prodNames from Purchase


Insertion an example1

Insertion: an Example

INSERT INTO Product(name)

SELECT DISTINCT prodName

FROM Purchase

WHERE prodName NOT IN (SELECT name FROM Product)


Insertion an example2

Insertion: an Example

INSERT INTO Product(name, listPrice)

SELECT DISTINCT prodName, price

FROM Purchase

WHERE prodName NOT IN (SELECT name FROM Product)

Depends on the implementation


Deletions

Deletions

Example:

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.


Deletion

Deletion

DELETE FROM relation WHERE condition.

  • Deletes all tuples satisfying the condition from the named relation.

    Example

    Sally no longer likes Bud.

    Likes(drinker, beer)

    DELETE FROM Likes

    WHERE drinker = 'Sally' AND

    beer = 'Bud';

    Example

    Make the Likes relation empty.

    DELETE FROM Likes;


Updates1

Updates

Example:

UPDATE PRODUCT

SET price = price/2

WHERE Product.name IN

(SELECT product

FROM Purchase

WHERE Date =‘Oct, 25, 1999’);


Patterns

Patterns

  • % stands for any string.

  • _ stands for any one character.

  • “Attribute LIKE pattern” is a condition that is true if the string value of the attribute matches the pattern.

    • Also NOT LIKE for negation.

      Example

      Find drinkers whose phone has exchange 555.

      Drinkers(name, addr, phone)

      SELECT name

      FROM Drinkers

      WHERE phone LIKE '%555-_ _ _ _’;

  • Note patterns must be quoted, like strings.


Nulls

Nulls

In place of a value in a tuple's component.

  • Interpretation is not exactly “missing value.”

  • There could be many reasons why no value is present, e.g., “value inappropriate.”

    Comparing Nulls to Values

  • 3rd truth value UNKNOWN.

  • A query only produces tuples if the WHERE-condition evaluates to TRUE(UNKNOWN is not sufficient).


Example2

Example

barbeerprice

Joe's barBudNULL

SELECT bar

FROM Sells

WHERE price < 2.00 OR price >= 2.00;

UNKNOWN UNKNOWN

UNKNOWN

  • Joe's Bar is not produced, even though the WHERE condition is a tautology.


3 valued logic

3-Valued Logic

Think of true = 1; false = 0, and unknown = 1/2. Then:

  • AND = min.

  • OR = max.

  • NOT(x) = 1 – x.

    Some Key Laws Fail to Hold

    Example: Law of the excluded middle, i.e.,

    pOR NOT p = TRUE

  • For 3-valued logic: if p = unknown, then left side = max(1/2,(1–1/2)) = 1/2 ≠ 1.

  • Like bag algebra, there is no way known to make 3-valued logic conform to all the laws we expect for sets/2-valued logic, respectively.


Testing for null

Testing for NULL

  • The condition value = NULL always evaluates to UNKNOWN, even if the value is NULL!

  • Use value IS NULL or value IS NOT NULL instead.


Multi relation queries

Multi-relation Queries

  • List of relations in FROM clause.

  • Relation-dot-attribute disambiguates attributes from several relations.

    Example

    Find the beers that the frequenters of Joe's Bar like.

    Likes(drinker, beer)

    Frequents(drinker, bar)

    SELECT beer

    FROM Frequents, Likes

    WHERE bar = 'Joe''s Bar' AND

    Frequents.drinker = Likes.drinker;


Formal semantics of multi relation queries

Formal Semantics of Multi-relation Queries

Same as for single relation, but start with the product of all the relations mentioned in the FROM clause.

Operational Semantics

Consider a tuple variable for each relation in the FROM.

  • Imagine these tuple variables each pointing to a tuple of their relation, in all combinations (e.g., nested loops).

  • If the current assignment of tuple-variables to tuples makes the WHERE true, then output the attributes of the SELECT.


Explicit tuple variables

Explicit Tuple Variables

Sometimes we need to refer to two or more copies of a relation.

  • Use tuple variables as aliases of the relations.

    Example

    Find pairs of beers by the same manufacturer.

    Beers(name, manf)

    SELECT b1.name, b2.name

    FROM Beers b1, Beers b2

    WHERE b1.manf = b2.manf AND

    b1.name < b2.name;

  • SQL permits AS between relation and its tuple variable;Oracle does not.

  • Note that b1.name < b2.name is needed to avoid producing (Bud, Bud) and to avoid producing a pair in both orders.


Subqueries

Subqueries

Result of a select-from-where query can be used in the where-clause of another query.

Simplest Case: Subquery Returns a Single, Unary Tuple

Find bars that serve Miller at the same price Joe charges for Bud.

Sells(bar, beer, price)

SELECT bar

FROM Sells

WHERE beer = 'Miller' AND price =

(SELECT price

FROM Sells

WHERE bar = 'Joe''s Bar' AND

beer = 'Bud');

  • Notice the scoping rule: an attribute refers to the most closely nested relation with that attribute.

  • Parentheses around subquery are essential.


The in operator

The IN Operator

“Tuple IN relation” is true iff the tuple is in the relation.

Example

Find the name and manufacturer of beers that Fred likes.

Beers(name, manf)

Likes(drinker, beer)

SELECT *

FROM Beers

WHERE name IN

(SELECT beer

FROM Likes

WHERE drinker = 'Fred’);

  • Also: NOT IN.


Exists

EXISTS

“EXISTS(relation)” is true iff the relation is nonempty.

Example

Find the beers that are the unique beer by their manufacturer.

Beers(name, manf)

SELECT name

FROM Beers b1

WHERE NOT EXISTS

(SELECT *

FROM Beers

WHERE manf = b1.manf AND

name <> b1.name);

  • Note scoping rule: to refer to outer Beers in the inner subquery, we need to give the outer a tuple variable, b1 in this example.

  • A subquery that refers to values from a surrounding query is called a correlated subquery.


Quantifiers

Quantifiers

ANY and ALL behave as existential and universal quantifiers, respectively.

  • Beware: in common parlance, “any” and “all” seem to be synonyms, e.g., “I am fatter than any of you” vs. “I am fatter than all of you.” But in SQL:

    Example

    Find the beer(s) sold for the highest price.

    Sells(bar, beer, price)

    SELECT beer

    FROM Sells

    WHERE price >= ALL(

    SELECT price

    FROM Sells);

    Class Problem

    Find the beer(s) not sold for the lowest price.


Union intersection difference1

Union, Intersection, Difference

“(subquery) UNION (subquery)” produces the union of the two relations.

  • Similarly for INTERSECT, EXCEPT = intersection and set difference.

    • But: in Oracle set difference is MINUS, not EXCEPT.

      Example

      Find the drinkers and beers such that the drinker likes the beer and frequents a bar that serves it.

      Likes(drinker, beer)

      Sells(bar, beer, price)

      Frequents(drinker, bar)

      (SELECT * FROM Likes)

      INTERSECT

      (SELECT drinker, beer

      FROM Sells, Frequents

      WHERE Frequents.bar = Sells.bar

      );


Example3

Example

Find the different prices charged for beers.

Sells(bar, beer, price)

SELECT DISTINCT price

FROM Sells;


Join based expressions

Join-Based Expressions

A number of forms are provided.

  • Can be used either stand-alone (in place of a select-from-where) or to define a relation in the FROM-clause.

    R NATURAL JOIN S

    R JOIN S ON condition

    e.g., condition:R.B=S.B

    R CROSS JOIN S

    R OUTER JOIN S

  • Outerjoin can be modified by:

    1. Optional NATURAL in front.

    2. Optional ON condition at end.

    3. Optional LEFT, RIGHT, or FULL (default) before OUTER.

    • LEFT = pad (with NULL) dangling tuples of R only; RIGHT = pad dangling tuples of S only.


Aggregations

Aggregations

Sum, avg, min, max, and count apply to attributes/columns. Also, count(*) applies to tuples.

  • Use these in lists following SELECT.

    Example

    Find the average price of Bud.

    Sells(bar, beer, price)

    SELECT AVG(price)

    FROM Sells

    WHERE beer = 'Bud';

  • Counts each tuple (presumably each bar that sells Bud) once.

    Class Problem

    What would we do if Sells were a bag?


Eliminating duplicates before aggregation

Eliminating DuplicatesBefore Aggregation

Find the number of different prices at which Bud is sold.

Sells(bar, beer, price)

SELECT COUNT(DISTINCT price)

FROM Sells

WHERE beer = 'Bud';

  • DISTINCT may be used in any aggregation, but typically only makes sense with COUNT.


Grouping

Grouping

Follow select-from-where by GROUP BY and a list of attributes.

  • The relation that is the result of the FROM and WHERE clauses is grouped according to the values of these attributes, and aggregations take place only within a group.

    Example

    Find the average sales price for each beer.

    Sells(bar, beer, price)

    SELECT beer, AVG(price)

    FROM Sells

    GROUP BY beer;


Example4

Example

Find, for each drinker, the average price of Bud at the bars they frequent.

Sells(bar, beer, price)

Frequents(drinker, bar)

SELECT drinker, AVG(price)

FROM Frequents, Sells

WHERE beer = 'Bud' AND

Frequents.bar = Sells.bar

GROUP BY drinker;

  • Note: grouping occurs after the  and  operations.


Restriction on select lists with aggregation

Restriction on SELECT Lists With Aggregation

If any aggregation is used, then each element of a SELECT clause must either be aggregated or appear in a group-by clause.

Example

  • The following might seem a tempting way to find the bar that sells Bud the cheapest:

    Sells(bar, beer, price)

    SELECT bar, MIN(price)

    FROM Sells

    WHERE beer = 'Bud';

  • But it is illegal in SQL.

    Problem

    How would we find that bar?


Having clauses

HAVING Clauses

HAVING clauses are selections on groups, just as WHERE clauses are selections on tuples.

  • Condition can use the tuple variables or relations in the FROM and their attributes, just like the WHERE can.

    • But the tuple variables range only over the group.

    • And the attribute better make sense within a group; i.e., be one of the grouping attributes.


Example5

Example

Find the average price of those beers that are either served in at least 3 bars or manufactured by Anheuser-Busch.

Beers(name, manf)

Sells(bar, beer, price)

SELECT beer, AVG(price)

FROM Sells

GROUP BY beer

HAVING COUNT(*) >= 3 OR

beer IN (

SELECT name

FROM Beers

WHERE manf = 'Anheuser-Busch'

);


Db modifications

DB Modifications

  • Modification = insert + delete + update.

    Insertion of a Tuple

    INSERT INTO relation VALUES (list of values).

  • Inserts the tuple = list of values, associating values with attributes in the order the attributes were declared.

    • Forget the order? List the attributes as arguments of the relation.

      Example

      Likes(drinker, beer)

      Insert the fact that Sally likes Bud.

      INSERT INTO Likes(drinker, beer)

      VALUES('Sally', 'Bud');


Insertion of the result of a query

Insertion of the Result of a Query

INSERT INTO relation (subquery).

Example

Create a (unary) table of all Sally's potential buddies, i.e., the people who frequent bars that Sally also frequents.

Frequents(drinker, bar)

CREATE TABLE PotBuddies(

name char(30)

);

INSERT INTO PotBuddies

(SELECT DISTINCT d2.drinker

FROM Frequents d1, Frequents d2

WHERE d1.drinker = 'Sally' AND

d2.drinker <> 'Sally' AND

d1.bar = d2.bar

);


Example6

Example

  • Delete all beers for which there is another beer by the same manufacturer.

    Beers(name, manf)

    DELETE FROM Beers b

    WHERE EXISTS

    (SELECT name

    FROM Beers

    WHERE manf = b.manf AND

    name <> b.name

    );

  • Note alias for relation from which deletion occurs.


Prof sin min lee

  • Semantics is tricky. If A.B. makes Bud and BudLite (only), does deletion of Bud make BudLite not satisfy the condition?

  • SQL semantics: all conditions in modifications must be evaluated by the system before any mods due to that mod command occur.

    • In Bud/Budlite example, we would first identify both beers a targets, and then delete both.


Subqueries1

Subqueries

A subquery producing a single value:

In this case, the subquery returns one value.

If it returns more, it’s a run-time error.

SELECT Purchase.product

FROM Purchase

WHERE buyer =

(SELECT name

FROM Person

WHERE ssn = ‘123456789‘);


Subqueries2

Subqueries

Can say the same thing without a subquery:

This is equivalent to the previous one when the ssn is a keyand ‘123456789’ exists in the database;otherwise they are different.

SELECT Purchase.productFROM Purchase, PersonWHERE buyer = name AND ssn = ‘123456789‘


Subqueries returning relations

Subqueries Returning Relations

Find companies that manufacture products bought by Joe Blow.

SELECT Company.name

FROM Company, Product

WHERE Company.name = Product.maker

AND Product.name IN

(SELECT Purchase.product

FROM Purchase

WHERE Purchase .buyer = ‘Joe Blow‘);

Here the subquery returns a set of values: no moreruntime errors.


Subqueries returning relations1

Subqueries Returning Relations

Equivalent to:

SELECT Company.name

FROM Company, Product, Purchase

WHERE Company.name = Product.maker

AND Product.name = Purchase.product

AND Purchase.buyer = ‘Joe Blow’

Is this query equivalent to the previous one ?

Beware of duplicates !


Removing duplicates

Removing Duplicates

SELECTDISTINCT Company.name

FROM Company, Product

WHERE Company.name= Product.maker

AND Product.name IN

(SELECT Purchase.product

FROM Purchase

WHERE Purchase.buyer = ‘Joe Blow’)

SELECTDISTINCT Company.name

FROM Company, Product, Purchase

WHERE Company.name= Product.maker

AND Product.name = Purchase.product

AND Purchase.buyer = ‘Joe Blow’

Now

they are

equivalent


Subqueries returning relations2

Subqueries Returning Relations

You can also use: s > ALL R

s > ANY R

EXISTS R

Product ( pname, price, category, maker)

Find products that are more expensive than all those produced

By “Gizmo-Works”

SELECT name

FROM Product

WHERE price > ALL (SELECT price

FROM Purchase

WHERE maker=‘Gizmo-Works’)


Correlated queries

Correlated Queries

Movie (title, year, director, length)

Find movies whose title appears more than once.

correlation

SELECTDISTINCT title

FROM Movie AS x

WHERE year < > ANY

(SELECT year

FROM Movie

WHERE title = x.title);

Note (1) scope of variables (2) this can still be expressed as single SFW


Complex correlated query

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

    Powerful, but 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);


Existential universal conditions

Existential/Universal Conditions

Product ( pname, price, company)

Company( cname, city)

Find all companies s.t. some of their products have price < 100

SELECT DISTINCT Company.cname

FROM Company, Product

WHERE Company.cname = Product.company and Product.price < 100

Existential: easy ! 


Existential universal conditions1

Existential/Universal Conditions

Product ( pname, price, company)

Company( cname, city)

Find all companies s.t. all of their products have price < 100

Universal: hard ! 


Existential universal conditions2

Existential/Universal Conditions

1. Find the other companies: i.e. s.t. some product  100

SELECT DISTINCT Company.cname

FROM Company

WHERE Company.cname IN (SELECT Product.companyFROM ProductWHERE Product.price >= 100

2. Find all companies s.t. all their products have price < 100

SELECT DISTINCT Company.cname

FROM Company

WHERE Company.cname NOTIN (SELECT Product.companyFROM ProductWHERE Product.price >= 100


Nulls in sql

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 it can be null (nullable attribute) or not

  • How does SQL cope with tables that have NULLs ?


Null values

Null Values

  • If x= NULL then 4*(3-x)/7 is still NULL

  • If x= NULL then x=“Joe” is UNKNOWN

  • In SQL there are three boolean values:

    FALSE = 0

    UNKNOWN = 0.5

    TRUE = 1


Null values1

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 Person

WHERE (age < 25) AND

(height > 6 OR weight > 190)

E.g.age=20heigth=NULLweight=200


Null values2

Null Values

Unexpected behavior:

Some Persons are not included !

SELECT *

FROM Person

WHERE age < 25 OR age >= 25


Null values3

Null Values

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


Outerjoins

Outerjoins

Explicit joins in SQL:

Product(name, category)

Purchase(prodName, store)

Same as:

But Products that never sold will be lost !

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


Outerjoins1

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


Prof sin min lee

Product

Purchase


Outer joins

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


Aggregation

Aggregation

SELECT Avg(price)

FROM Product

WHERE maker=“Toyota”

SQL supports several aggregation operations:

SUM, MIN, MAX, AVG, COUNT


Aggregation count

Aggregation: Count

SELECT Count(*)

FROM Product

WHERE year > 1995

Except COUNT, all aggregations apply to a single attribute


Aggregation count1

Aggregation: Count

COUNT applies to duplicates, unless otherwise stated:

SELECT Count(category) same as Count(*)

FROM Product

WHERE year > 1995

Better:

SELECT Count(DISTINCT category)

FROM Product

WHERE year > 1995


Simple aggregation

Simple Aggregation

Purchase(product, date, price, quantity)

Example 1: find total sales for the entire database

SELECT Sum(price * quantity)

FROM Purchase

Example 1’: find total sales of bagels

SELECT Sum(price * quantity)

FROM Purchase

WHERE product = ‘bagel’


Simple aggregations

Simple Aggregations

Purchase


Grouping and aggregation

Grouping and Aggregation

Usually, we want aggregations on certain parts of the relation.

Purchase(product, date, price, quantity)

Example 2: find total sales after 9/1 per product.

SELECT product, Sum(price*quantity) AS TotalSales

FROM Purchase

WHERE date > “9/1”

GROUP BY product

Let’s see what this means…


Grouping and aggregation1

Grouping and Aggregation

1. Compute the FROM and WHERE clauses.

2. Group by the attributes in the GROUP BY

3. Produce one tuple for every group by applying aggregation

SELECT can have (1) grouped attributes or (2) aggregates.


First compute the from where clauses date 9 1 then group by product

First compute the FROM-WHERE clauses (date > “9/1”) then GROUP BY product:


Then aggregate

Then, aggregate

SELECT product, Sum(price*quantity) AS TotalSales

FROM Purchase

WHERE date > “9/1”

GROUP BY product


Group by v s nested quereis

GROUP BY v.s. Nested Quereis

SELECT product, Sum(price*quantity) AS TotalSales

FROM Purchase

WHERE date > “9/1”

GROUP BY product

SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity)FROM Purchase yWHERE x.product = y.product AND y.date > ‘9/1’)AS TotalSales

FROM Purchase x

WHERE x.date > “9/1”


Another example

Another Example

For every product, what is the total sales and max quantity sold?

SELECT product, Sum(price * quantity) AS SumSales

Max(quantity) AS MaxQuantity

FROM Purchase

GROUP BY product


Having clause

HAVING Clause

Same query, except that we consider only products that had

at least 30 items sold.

SELECT product, Sum(price * quantity)

FROM Purchase

WHERE date > “9/1”

GROUPBY product

HAVING Sum(quantity) > 30

HAVING clause contains conditions on aggregates.


General form of grouping and aggregation

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 ?


General form of grouping and aggregation1

General form of Grouping and Aggregation

SELECT S

FROM R1,…,Rn

WHERE C1

GROUP BY a1,…,ak

HAVING C2

Evaluation steps:

  • Compute the FROM-WHERE part, obtain a table with all attributes in R1,…,Rn

  • Group by the attributes a1,…,ak

  • Compute the aggregates in C2 and keep only groups satisfying C2

  • Compute aggregates in S and return the result


Aggregation1

Aggregation

Author(login,name)

Document(url, title)

Wrote(login,url)

Mentions(url,word)


Grouping vs nested queries

Grouping vs. Nested Queries

  • Find all authors who wrote at least 10 documents:

  • Attempt 1: with nested queries

This isSQL bya novice

SELECTDISTINCT Author.name

FROM Author

WHERE count(SELECT Wrote.urlFROM WroteWHERE Author.login=Wrote.login) > 10


Grouping vs nested queries1

Grouping vs. Nested Queries

  • Find all authors who wrote at least 10 documents:

  • Attempt 2: SQL style (with GROUP BY)

This isSQL byan expert

SELECT Author.name

FROM Author, Wrote

WHERE Author.login=Wrote.login

GROUP BY Author.name

HAVING count(wrote.url) > 10

No need for DISTINCT: automatically from GROUP BY


Grouping vs nested queries2

Grouping vs. Nested Queries

  • Find all authors who have a vocabulary over 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

Look carefully at the last two queries: you maybe tempted to write them as a nested queries,but in SQL we write them best with GROUP BY


  • Login