Upload
evangeline-payne
View
223
Download
2
Embed Size (px)
Citation preview
1
Relational Algebra & SQL
2
Why SQL & Relational Algebra?
SQL is a very-high-level language. Say “what to do” rather than “how to do it.” Avoid a lot of data-manipulation details needed
in procedural languages like C++ or Java. Database management system figures out
“best” way to execute query. Called “query optimization.”
Relational Algebra used in the Query Engine
3
Select-From-Where Statements
SELECT desired attributesFROM one or more tablesWHERE condition about tuples of
the tables
4
Our Running Example
All our SQL queries will be based on the following database schema. Underline indicates key attributes.
Beers(name, manf)Bars(name, addr, license)Drinkers(name, addr, phone)Likes(drinker, beer)Sells(bar, beer, price)Frequents(drinker, bar)
5
Example: Selection R1 := σC (R2)
Relation Sells:bar beer priceJoe’s Bud 2.50Joe’s Miller 2.75Sue’s Bud 2.50Sue’s Miller 3.00
JoeMenu := σbar=“Joe’s”(Sells):bar beer priceJoe’s Bud 2.50Joe’s Miller 2.75
SELECT *FROM SellsWHERE bar = ‘Joe’’s’
SELECT *FROM SellsWHERE bar = ‘Joe’’s’
6
Example: ProjectionR1 := πA (R2)
Relation Sells:bar beer priceJoe’s Bud 2.50Joe’s Miller 2.75Sue’s Bud 2.50Sue’s Miller 3.00
Prices := πbeer,price(Sells):beer priceBud 2.50Miller 2.75Miller 3.00
SELECT beer, priceFROM SellsSELECT beer, priceFROM Sells
7
Example: R3 := R1 Χ R2R1( A, B )
1 23 4
R2( B, C )5 67 89 10
R3( A, R1.B, R2.B, C )1 2 5 61 2 7 81 2 9 103 4 5 63 4 7 83 4 9 10
SELECT *FROM R1, R2SELECT *FROM R1, R2
8
Example: Theta JoinR3 := R1 ⋈C R2
Sells( bar, beer, price ) Bars(name, addr)Joe’s Bud 2.50 Joe’s Maple St.Joe’s Miller 2.75 Sue’s River Rd.Sue’s Bud 2.50Sue’s Coors3.00
BarInfo := Sells ⋈Sells.bar = Bars.name Bars
BarInfo( bar, beer, price, name, addr )Joe’s Bud 2.50 Joe’s Maple St.Joe’s Miller 2.75 Joe’s Maple St.Sue’s Bud 2.50 Sue’s River Rd.Sue’s Coors3.00 Sue’s River Rd.
SELECT * FROM Sells, BarsWHERE Sells.bar=
Bars.name
SELECT * FROM Sells, BarsWHERE Sells.bar=
Bars.name
9
Example: Natural JoinR3 := R1 ⋈ R2
Sells( bar, beer, price ) Bars( bar, addr )Joe’s Bud 2.50 Joe’s Maple St.Joe’s Miller 2.75 Sue’s River Rd.Sue’s Bud 2.50Sue’s Coors3.00
BarInfo( bar, beer, price, addr )Joe’s Bud 2.50 Maple St.Joe’s Milller 2.75 Maple St.Sue’s Bud 2.50 River Rd.Sue’s Coors3.00 River Rd.
BarInfo := Sells ⋈ Bars
SELECT S.bar, beer, price, addr FROM Sells S, Bars BWHERE S.bar=B.bar
SELECT S.bar, beer, price, addr FROM Sells S, Bars BWHERE S.bar=B.bar
10
Renaming
The ρ operator gives a new schema to a relation.
R1 := ρR1(A1,…,An)(R2) makes R1 be a relation with attributes A1,…,An and the same tuples as R2.
Simplified notation: R1(A1,…,An) := R2.
11
Example: Renaming
Bars( name, addr )Joe’s Maple St.Sue’s River Rd.
R( bar, addr )Joe’s Maple St.Sue’s River Rd.
R(bar, addr) := Bars
CREATE TABLE R AS SELECT name as bar, addr FROM Bars
CREATE TABLE R AS SELECT name as bar, addr FROM Bars
SELECT name as bar, addr FROM BarsSELECT name as bar, addr FROM Bars
OR
12
Union, Intersection, and Difference
In Relational Algebra: R3 = R1 ∪ R2 (tuples in R1 or R2) R3 = R1 ∩ R2 (tuples in both R1 and R2) R3 = R1 — R2 (tuples in R1 and not in R2)
In SQL: (<subquery>) UNION (<subquery>)
• SELECT surname FROM instructors UNION
SELECT surname FROM students (<subquery>) INTERSECT (<subquery>)
• SELECT surname FROM instructors INTERSECT
SELECT surname FROM students (<subquery>) EXCEPT (<subquery>)
• SELECT surname FROM instructors EXCEPT
SELECT surname FROM students
13
Building Complex Expressions Combine operators with parentheses and
precedence rules.
Example: the theta-join R3 := R1 ⋈C R2
can be written: R3 := σC (R1 Χ R2) Precedence of relational operators:
1. [σ, π, ρ] (highest).
2. [Χ, ⋈].
3. ∩.4. [∪, —]
14
Expression Trees
Leaves are operands --- either variables standing for relations or particular, constant relations.
Interior nodes are operators, applied to their child or children.
15
Query Tree: Find the names of all the bars that are either on Maple St. or sell Bud for
less than $3
Bars Sells
σaddr = “Maple St.” σprice<3 AND beer=“Bud”
πname
ρR(name)
πbar
∪
Bars(name, addr) Sells(bar, beer, price)
16
Example: Self-Join
Using Sells(bar, beer, price), find the bars that sell two different beers at the same price.
Strategy: by renaming, define a copy of Sells, called S(bar, beer1, price). The natural join of Sells and S consists of quadruples (bar, beer, beer1, price) such that the bar sells both beers at this price.
17
The Tree
Sells Sells
ρS(bar, beer1, price)
⋈
πbar
σbeer != beer1
18
Schemas for Results
Union, intersection, and difference: the schemas of the two operands must be the same, so use that schema for the result.
Selection: schema of the result is the same as the schema of the operand.
Projection: list of attributes tells us the schema.
19
Schemas for Results --- (2)
Product: schema is the attributes of both relations. Use R.A, etc., to distinguish two
attributes named A. Theta-join: same as product. Natural join: union of the attributes
of the two relations. Renaming: the operator tells the
schema.
20
Relational Algebra on Bags A bag (or multiset ) is like a set, but
an element may appear more than once.
Example: {1,2,1,3} is a bag. Example: {1,2,3} is also a bag that
happens to be a set. SQL is actually a bag language. Some operations, like projection, are
more efficient on bags than sets.
21
Example: SelectionR( A, B )
1 25 61 2
A B1 21 2
SELECT *FROM RWHERE A+B < 5
SELECT *FROM RWHERE A+B < 5
σA+B < 5 (R) = A B1 2
SELECT DISTINCT *FROM RWHERE A+B < 5
SELECT DISTINCT *FROM RWHERE A+B < 5
22
Example: ProjectionR( A, B )
1 25 61 2
A151
SELECT DISTINCT AFROM R
SELECT DISTINCT AFROM R
πA (R) = A15
SELECT AFROM RSELECT AFROM R
23
Example: Theta-JoinR( A, B ) S(B, C ) 1 2 3 4 5 6 7 8 1 2
A R.B S.B C1 2 3 41 2 7 85 6 7 81 2 3 41 2 7 8
A R.B S.B C1 2 3 41 2 7 85 6 7 8
SELECT A, R.B, S.B, CFROM R, S WHERE R.B < S.B
SELECT A, R.B, S.B, CFROM R, S WHERE R.B < S.B
R ⋈ R.B<S.B S
SELECT DISTINCT A, R.B, S.B, CFROM R, S WHERE R.B < S.B
SELECT DISTINCT A, R.B, S.B, CFROM R, S WHERE R.B < S.B
24
Union, Intersection, Difference
In SQL UNION, INTERSECTION, EXCEPT return distinct tuples (no duplicates)
Use UNION ALL, INTERSECTION ALL, EXCEPT ALL to return duplicates (if any)
Bag Union: {1,2,1} ∪ {1,1,2,3,1} = {1,1,1,1,1,2,2,3}
Bag Intersection: {1,2,1,1} ∩ {1,2,1,3} = {1,1,2}
Bag Difference: {1,2,1,1} – {1,2,3} = {1,1}
25
SQL Semantics
Select-From-Where Statements
Multirelation QueriesSubqueries
26
Example
Using Beers(name, manf), what beers are made by Anheuser-Busch?
SELECT name
FROM Beers
WHERE manf = ’Anheuser-Busch’;
27
Result of Query
nameBudBud LiteMichelob . . .
The answer is a relation with a single attribute,name, and tuples with the name of each beerby Anheuser-Busch, such as Bud.
28
Meaning of Single-Relation Query
Begin with the relation in the FROM clause.
Apply the selection indicated by the WHERE clause.
Apply the extended projection indicated by the SELECT clause.
29
Operational Semantics
Check ifAnheuser-Busch
name manf
Bud Anheuser-Busch Include t.name in the result, if so
Tuple-variable tloops over alltuples
30
Operational Semantics --- General
Think of a tuple variable visiting each tuple of the relation mentioned in FROM.
Check if the “current” tuple satisfies the WHERE clause.
If so, compute the attributes or expressions of the SELECT clause using the components of this tuple.
31
* In SELECT clauses When there is one relation in the FROM
clause, * in the SELECT clause stands for “all attributes of this relation.”
Example: Using Beers(name, manf):SELECT *
FROM Beers
WHERE manf = ’Anheuser-Busch’;
32
Result of Query:
name manfBud Anheuser-BuschBud Lite Anheuser-BuschMichelob Anheuser-Busch . . . . . .
Now, the result has each of the attributesof Beers.
33
Renaming Attributes
If you want the result to have different attribute names, use “AS <new name>” to rename an attribute.
Example: Using Beers(name, manf):SELECT name AS beer, manf
FROM Beers
WHERE manf = ’Anheuser-Busch’
34
Result of Query:
beer manfBud Anheuser-BuschBud Lite Anheuser-BuschMichelob Anheuser-Busch . . . . . .
35
Expressions in SELECT Clauses
Any expression that makes sense can appear as an element of a SELECT clause.
Example: Using Sells(bar, beer, price):SELECT bar, beer,
price*114 AS priceInYen
FROM Sells;
36
Result of Query
bar beerpriceInYen
Joe’s Bud 285Sue’s Miller 342 … … …
37
Example: Constants as Expressions
Using Likes(drinker, beer):
SELECT drinker,
’likes Bud’ AS whoLikesBud
FROM Likes
WHERE beer = ’Bud’;
38
Result of Query
drinker whoLikesBudSally likes BudFred likes Bud … …
39
Example: Information Integration
We often build “data warehouses” from the data at many “sources.”
Suppose each bar has its own relation Menu(beer, price) .
To contribute to Sells(bar, beer, price) we need to query each bar and insert the name of the bar.
40
Information Integration --- (2)
For instance, at Joe’s Bar we can issue the query: SELECT ’Joe’’s Bar’as bar, beer, price FROM Menu; bar beer price
Joe’s BarBud 2.50Joe’s BarBud Light 2.75 … …
41
Complex Conditions in WHERE Clause
Boolean operators AND, OR, NOT. Comparisons =, <>, <, >, <=, >=.
And many other operators that produce boolean-valued results.
42
Example: Complex Condition
Using Sells(bar, beer, price), find the price Joe’s Bar charges for Bud:
SELECT price
FROM Sells
WHERE bar = ’Joe’’s Bar’ AND
beer = ’Bud’;
43
Patterns
A condition can compare a string to a pattern by: <Attribute> LIKE <pattern> or
<Attribute> NOT LIKE <pattern> Pattern is a quoted string with %
= “any string”; _ = “any character.”
44
Example: LIKE
Using Drinkers(name, addr, phone) find the drinkers with exchange 555:
SELECT name
FROM Drinkers
WHERE phone LIKE ’%555-_ _ _ _’;
45
NULL Values
Tuples in SQL relations can have NULL as a value for one or more components.
Meaning depends on context. Two common cases: Missing value : e.g., we know Joe’s Bar has
some address, but we don’t know what it is. Inapplicable : e.g., the value of attribute
spouse for an unmarried person.
46
Comparing NULL’s to Values
The logic of conditions in SQL is really 3-valued logic: TRUE, FALSE, UNKNOWN.
Comparing any value (including NULL itself) with NULL yields UNKNOWN.
A tuple is in a query answer iff the WHERE clause is TRUE (not FALSE or UNKNOWN).
47
Three-Valued Logic To understand how AND, OR, and NOT
work in 3-valued logic, think of TRUE = 1, FALSE = 0, and UNKNOWN = ½.
AND = MIN; OR = MAX, NOT(x) = 1-x. Example:TRUE AND (FALSE OR NOT(UNKNOWN))
= MIN(1, MAX(0, (1 - ½ ))) =MIN(1, MAX(0, ½ )) = MIN(1, ½ ) = ½.
Three-valued Logic AND = MIN; OR = MAX, NOT(x) = 1-x
OR TRUE and UNKNOWN = UNKNOWN FALSE and UNKNOWN = FALSE TRUE or UNKNOWN = TRUE FALSE or UNKNOWN = UNKNOWN not UNKNOWN = UNKNOWN Example:TRUE AND (FALSE OR NOT(UNKNOWN)) = TRUE AND (FALSE OR UNKNOWN)= TRUE AND UNKNOWN = UNKNOWN
48
49
Surprising Example
From the following Sells relation:bar beer priceJoe’s BarBud NULL
SELECT barFROM SellsWHERE price < 2.00 OR price >= 2.00; UNKNOWN UNKNOWN
UNKNOWN
50
Reason: 2-Valued Laws != 3-Valued Laws
Some common laws, like commutativity of AND, hold in 3-valued logic.
But not others, e.g., the law of the excluded middle : p OR NOT p = TRUE. When p = UNKNOWN, the left side is
MAX( ½, (1 – ½ )) = ½ != 1. i.e., UNKNOWN or not UNKNOWN =
UNKNOWN
51
Multirelation Queries
Interesting queries often combine data from more than one relation.
We can address several relations in one query by listing them all in the FROM clause.
Distinguish attributes of the same name by “<relation>.<attribute>” .
52
Example: Joining Two Relations
Using relations Likes(drinker, beer) and Frequents(drinker, bar), find the beers liked by at least one person who frequents Joe’s Bar.SELECT beerFROM Likes, FrequentsWHERE bar = ’Joe’’s Bar’ AND
Frequents.drinker = Likes.drinker;
53
Formal Semantics
Almost the same as for single-relation queries:
1. Start with the product of all the relations in the FROM clause.
2. Apply the selection condition from the WHERE clause.
3. Project onto the list of attributes and expressions in the SELECT clause.
54
Operational Semantics
Imagine one tuple-variable for each relation in the FROM clause. These tuple-variables visit each
combination of tuples, one from each relation.
If the tuple-variables are pointing to tuples that satisfy the WHERE clause, send these tuples to the SELECT clause.
55
Example
drinker bar drinker beer
tv1 tv2Sally Bud
Sally Joe’s
Likes Frequents
to outputcheck theseare equal
checkfor Joe
56
Explicit Tuple-Variables
Sometimes, a query needs to use two copies of the same relation.
Distinguish copies by following the relation name by the name of a tuple-variable, in the FROM clause.
It’s always an option to rename relations this way, even when not essential.
57
Example: Self-Join
From Beers(name, manf), find all pairs of beers by the same manufacturer. Do not produce pairs like (Bud, Bud). Produce pairs in alphabetic order, e.g.
(Bud, Miller), not (Miller, Bud).
SELECT b1.name, b2.nameFROM Beers b1, Beers b2WHERE b1.manf = b2.manf AND
b1.name < b2.name;