Chapter 3: Relational Model IIIChapter 3: Relational Model III Additional Relational Algebra Additional Relational Algebra
Operations Operations ViewsViews
Additional OperationsAdditional OperationsWe define additional operations that do not We define additional operations that do not
add any power to the relational algebra, add any power to the relational algebra, but that simplify common queries.but that simplify common queries.
Set intersectionSet intersection Natural joinNatural join DivisionDivision AssignmentAssignment
Set-Intersection OperationSet-Intersection Operation Notation: Notation: rr ss Defined as:Defined as: rr ss ={ ={ t t | | tt rr andand tt ss } } Assume: Assume:
rr, , ss have the have the same aritysame arity attributes of r and s are compatibleattributes of r and s are compatible
Note: Note: rr ss = = rr - ( - (rr - - ss))
Set-Intersection Operation - Set-Intersection Operation - ExampleExample
Relation r, s:Relation r, s:
r r s s
A B
121
A B
23
r s
A B
2
Natural-Join OperationNatural-Join Operation Notation: r s Example:Example:
RR = ( = (A, B, C, DA, B, C, D))SS = ( = (E, B, DE, B, D)) Result schema = (Result schema = (A, B, C, D, EA, B, C, D, E)) rr ss is defined as: is defined as:
r.A, r.B, r.C, r.D, s.Er.A, r.B, r.C, r.D, s.E ( (r.B = s.B r.B = s.B r.D = s.D r.D = s.D ( (r r x x ss))))
Natural Join Operation – Natural Join Operation – ExampleExample
Relations r, s:Relations r, s:A B
12412
C D
aabab
B
13123
D
aaabb
E
r
A B
11112
C D
aaaab
E
s
r s
ExampleExample List account number and the branch city List account number and the branch city
that the account belongs tothat the account belongs to account-number, branch-cityaccount-number, branch-city (account branch) (account branch)
Division OperationDivision Operation Suited to queries that include the Suited to queries that include the
phrase “for all”.phrase “for all”. Let Let rr and and ss be relations on schemas R be relations on schemas R
and S respectively whereand S respectively where RR = ( = (AA11, …, , …, AAmm, , BB11, …, , …, BBnn)) SS = ( = (BB11, …, , …, BBnn))The result of r The result of r s is a relation on schema s is a relation on schemaRR – – S S = (= (AA11, …, , …, AAmm))
r r ss = { = { tt | | t t R-SR-S((rr) ) u u s s ( ( tutu r r ) } ) }
Division Operation – Division Operation – ExampleExample
Relations r, s:
r s: A
B
1
2
A B
12311134612
r
s
Another Division ExampleAnother Division ExampleA B
aaaaaaaa
C D
aabababb
E
11113111
Relations r, s:
r s:
D
ab
E
11
A B
aa
C
r
s
Example QueriesExample Queries Find all customers who have an account from at least the Find all customers who have an account from at least the
“Downtown” and the Uptown” branches.“Downtown” and the Uptown” branches.
Query 1
Customer-name(Branch-name=“Downtown” (depositor account))
Customer-name(Branch-name=“Uptown”(depositor account))
Query 2
customer-name, branch-name (depositor account)
temp(branch-name) ({(“Downtown”), (“Uptown”)})
Find all customers who have an account at all Find all customers who have an account at all branches located in Brooklyn city.branches located in Brooklyn city.
Example QueriesExample Queries
customer-name, branch-name (depositor account) branch-name (branch-city = “Brooklyn” (branch))
Assignment OperationAssignment Operation The assignment operation (The assignment operation () provides a ) provides a
convenient way to express complex queries. convenient way to express complex queries. Write query as a sequential program consisting ofWrite query as a sequential program consisting of
a series of assignments a series of assignments followed by an expression whose value is displayed as a followed by an expression whose value is displayed as a
result of the query.result of the query. Example:Example:
Temp1 Temp1 r x s r x s A,B (Temp1 )(Temp1 )
Extended Relational-Extended Relational-Algebra-OperationsAlgebra-Operations
Generalized ProjectionGeneralized Projection Outer JoinOuter Join Aggregate FunctionsAggregate Functions
Generalized ProjectionGeneralized Projection Extends the projection operation by Extends the projection operation by
allowing arithmetic functions to be used in allowing arithmetic functions to be used in the projection list.the projection list.
F1, F2, …, FnF1, F2, …, Fn((EE)) EE is any relational-algebra expression is any relational-algebra expression Each of Each of FF11, , FF22, …, , …, FFnn are are arithmetic are are arithmetic
expressions involving constants and expressions involving constants and attributes in the schema of attributes in the schema of EE..
ExampleExample Given relation Given relation credit-info(customer-name, credit-info(customer-name,
limit, credit-balance),limit, credit-balance), find how much more find how much more each person can spend: each person can spend:
customer-name, limit – credit-balancecustomer-name, limit – credit-balance (credit- (credit-info)info)
Aggregate Functions and Aggregate Functions and OperationsOperations
Aggregation functionAggregation function takes a collection takes a collection of values and returns a single value as a of values and returns a single value as a result.result.
avgavg: average value: average valueminmin: minimum value: minimum valuemaxmax: maximum value: maximum valuesumsum: sum of values: sum of valuescountcount: number of values: number of values
Aggregate OperationAggregate Operation Aggregate operationAggregate operation in relational in relational
algebra algebra G1, G2, …, GnG1, G2, …, Gn gg F1( A1F1( A1)), F2( A2, F2( A2)),…, Fn( An,…, Fn( An)) ((EE))
EE is any relational-algebra expression is any relational-algebra expression GG11, , GG22 …, …, GGnn is a list of attributes on which to is a list of attributes on which to
group (can be empty)group (can be empty) Each Each FFii is an aggregate functionis an aggregate function Each Each AAii is an attribute nameis an attribute name
Aggregate Operation – Aggregate Operation – ExampleExample
Relation Relation rr:: A B
C
77310
g sum(c) (r)sum-C
27
Aggregate Operation – Aggregate Operation – ExampleExample
Relation Relation accountaccount grouped by grouped by branch-namebranch-name::
branch-name g sum(balance) (account)
branch-name account-number balance
PerryridgePerryridgeBrightonBrightonRedwood
A-102A-201A-217A-215A-222
400900750750700
branch-name balancePerryridgeBrightonRedwood
13001500700
Aggregate Functions Aggregate Functions (Cont.)(Cont.)
Result of aggregation does not have a Result of aggregation does not have a namename Can use rename operation to give it a nameCan use rename operation to give it a name For convenience, we permit renaming as part For convenience, we permit renaming as part
of aggregate operationof aggregate operation
branch-name g sum(balance) as sum-balance (account)
Outer JoinOuter Join An extension of the join operation that avoids An extension of the join operation that avoids
loss of information.loss of information. Computes the join and then adds tuples form Computes the join and then adds tuples form
one relation that do not match tuples in the one relation that do not match tuples in the other relation to the result of the join. other relation to the result of the join.
Uses Uses nullnull values: values: null null signifies that the value is unknown or does not signifies that the value is unknown or does not
exist exist All comparisons involving All comparisons involving nullnull are (roughly are (roughly
speaking) speaking) falsefalse by definition. by definition. Will study precise meaning of comparisons with nulls laterWill study precise meaning of comparisons with nulls later
Outer Join – ExampleOuter Join – Example Relation Relation loanloan
Relation borrower
customer-name loan-numberJonesSmithHayes
L-170L-230L-155
300040001700
loan-number amountL-170L-230L-260
branch-nameDowntownRedwoodPerryridge
Outer Join – ExampleOuter Join – Example Inner JoinInner Join loan Borrowerloan Borrower
loan-number amount
L-170L-230
30004000
customer-name
JonesSmith
branch-name
DowntownRedwood
JonesSmithnull
loan-number amountL-170L-230L-260
300040001700
customer-namebranch-nameDowntownRedwoodPerryridge
Left Outer Join loan Borrower
Outer Join – ExampleOuter Join – Example Right Outer JoinRight Outer Join loanloan borrowerborrower
loan borrower Full Outer Join
loan-number amountL-170L-230L-155
30004000null
customer-nameJonesSmithHayes
branch-nameDowntownRedwoodnull
loan-number amount
L-170L-230L-260L-155
300040001700null
customer-name
JonesSmithnullHayes
branch-name
DowntownRedwoodPerryridgenull
Null ValuesNull Values It is possible for tuples to have a null value, It is possible for tuples to have a null value,
denoted by denoted by nullnull, for some of their attributes, for some of their attributes nullnull signifies an unknown value or that a signifies an unknown value or that a
value does not exist.value does not exist. The result of any arithmetic expression The result of any arithmetic expression
involving involving nullnull is is null.null. Aggregate functions simply ignore null valuesAggregate functions simply ignore null values For duplicate elimination and grouping, null is For duplicate elimination and grouping, null is
treated like any other value, and two nulls treated like any other value, and two nulls are assumed to be the sameare assumed to be the same
Null ValuesNull Values Comparisons with null values return the Comparisons with null values return the
special truth value special truth value unknownunknown If If falsefalse was used instead of was used instead of unknownunknown, then , then not (A < 5)not (A < 5) would not be equivalent to would not be equivalent to A >= A >=
55
Three-valued logicThree-valued logic Three-valued logic using the truth value Three-valued logic using the truth value unknownunknown::
OR: (OR: (unknownunknown oror truetrue) = ) = truetrue, , ( (unknownunknown oror falsefalse) = ) = unknownunknown ( (unknown unknown oror unknown) = unknown unknown) = unknown
AND:AND: (true (true and and unknown) = unknown, unknown) = unknown, (false (false and and unknown) = false,unknown) = false, (unknown (unknown andand unknown) = unknown unknown) = unknown
NOTNOT: (: (notnot unknown) = unknown unknown) = unknown In SQL “In SQL “PP is unknown” is unknown” evaluates to true if predicate evaluates to true if predicate PP
evaluates to evaluates to unknownunknown Result of selectResult of select predicate is treated as predicate is treated as false false if it if it
evaluates to evaluates to unknownunknown
ViewsViews In some cases, it is not desirable for all users In some cases, it is not desirable for all users
to see the entire logical model (i.e., all the to see the entire logical model (i.e., all the actual relations stored in the database.)actual relations stored in the database.)
Consider a person who needs to know a Consider a person who needs to know a customer’s loan number and branch-name customer’s loan number and branch-name but has no need to see the loan amount. but has no need to see the loan amount. This person should see a relation described, This person should see a relation described, in the relational algebra, by in the relational algebra, by customer-name, loan-numbercustomer-name, loan-number , , branch_namebranch_name((borrower loanborrower loan))
Any relation that is not of the conceptual Any relation that is not of the conceptual model but is made visible to a user as a model but is made visible to a user as a “virtual relation” is called a “virtual relation” is called a viewview..
View DefinitionView Definition A view is defined using the A view is defined using the create view create view
statement which has the formstatement which has the formcreate view create view v v as as <<query expressionquery expressionwhere <query expression> is any legal where <query expression> is any legal relational algebra query expression. The relational algebra query expression. The view name is represented by view name is represented by v.v.
Once a view is defined, the view name can Once a view is defined, the view name can be used to refer to the virtual relation that be used to refer to the virtual relation that the view generates.the view generates.
View ExamplesView Examples Consider the view (named Consider the view (named all-customerall-customer) consisting of branches ) consisting of branches
and their customers.and their customers.
We can find all customers of the Perryridge branch by writing:
create view all-customer as
branch-name, customer-name (depositor account)
branch-name, customer-name (borrower loan)
customer-name
(branch-name = “Perryridge” (all-customer))