Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CH 4

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 64

Database Operation

Chapter 4

ENG ELHAM MOH'D


Query language

Procedural :relational Algebra


Non procedural: Tuple algebra

ENG ELHAM MOH'D


The Tuple Relation
calculus

A query in the tuple relational calculus is


expressed as

t p(t)

the set of tuples t for which predicate p is true

ENG ELHAM MOH'D


The Tuple Relation
calculus

f1 ∧ f2 " is true if and only if " f1 " is true and " f2 "
is true,
" f1 ∨ f2 " is true if and only if " f1 " is true or " f2 "
is true or both are true,
" ¬ f " is true if and only if " f " is not true,

ENG ELHAM MOH'D


t.name = "C. J. Date" ∨ t.name = "H. Darwen"
Book(t) ∨ Magazine(t)
∀ t : {author, title, subject} ( ¬ ( Book(t) ∧ t.author = "C. J.
Date" ∧ ¬ ( t.subject = "relational model")))
Note that the last formula states that all books that are written
by C. J. Date have as their subject the relational model. As usual
we omit brackets if this causes no ambiguity about the semantics
of the formula

Tuple calculus
ENG ELHAM MOH'D
Algebra -> operators and atomic operands
Expressions -> applying operators to atomic operands and/or
other expressions

Algebra of arithmetic: operands are variables and


constants, and operators are the usual arithmetic operators
E.g., (x+y)*2 or ((x+7)/(y-3)) + x

Relational algebra: operands are variables that stand for


relations and relations (sets of tuples), and operations
include union, intersection, selection, projection, Cartesian
product, etc
– E.g., (π c-ownerChecking-account) ∩ (π s-ownerSavings-
account)

Is this the Algebra you know?


• The Relational Algebra consists of a set of
fundamental operators that take relations as
their operands and return a relation as their
result. This means that operators can be
composed, ie the output of one operation
may be used as input to another operation.
• The relational algebra is a language of
expressions that can be evaluated to yield
relations. In a similar way, normal algebraic
expressions, for example x+5*y, are
evaluated to yield numbers. In normal
algebra, one expression can be equivalent to
another expression, for example, x+5*y =
y*5+x.

Relational Algebra
ENG ELHAM MOH'D
• There are two groups of operations:
• Mathematical set theory based relations:
UNION, INTERSECTION, DIFFERENCE, and
CARTESIAN PRODUCT.
• Special database operations:
SELECT (not the same as SQL SELECT),
PROJECT, and JOIN.

Relational Algebra
ENG ELHAM MOH'D
Relational Algebra
Five operators:
◦ Union: 
◦ Difference: -
◦ Selection:
◦ Projection: 
◦ Cartesian Product: 
Derived or auxiliary operators:
◦ Intersection, complement
◦ Joins (natural,equi-join, theta join, semi-join)
◦ Renaming:
•Operations that remove parts of relations:
selection, projection
•Operations that combine tuples from two relations:
Cartesian product, join
•Since each operation returns a relation,
operations can be composed!

Relational Algebra Operations


Removing Parts of Relations
Selection – rows

Projection - columns
• Relational SELECT
• SELECTION, σ - Selects the rows, or
tuples, from a relation, which satisfy the
specified constraints or restrictions

• For example, find all employees born after


1st Jan 1950:
• dob '01/JAN/1950'(employee)

ENG ELHAM MOH'D


Selection
Returns all tuples which satisfy a
condition
Notation: c(R)
Examples
◦ Salary > 40000 (Employee)
◦ name = “Smith” (Employee)
The condition c can be =, <, , >, ,
<>
SSN Name Salary
1234545 John 200000
5423341 Smith 600000
4352342 Fred 500000

 Name=“Fred” (Employee)

SSN Name Salary


5423341 Smith 600000
4352342 Fred 500000
• Relational PROJECT
• The PROJECT operation is used to select a
subset of the attributes of a relation by
specifying the names of the required
attributes.
• For example, to get a list of all employees
surnames and employee numbers:
•   π surname,empno(employee)

Relational Algebra
ENG ELHAM MOH'D
Projection
Eliminates columns, then removes
duplicates
Notation: A1,…,An (R)
Example: project social-security
number and names:
◦  SSN, Name (Employee)
◦ Output schema: Answer(SSN, Name)
SSN Name Salary
1234545 John 200000
5423341 John 600000
4352342 John 200000

 Name,Salary (Employee)

Name Salary
John 20000
John 60000
Relational Algebra
SELECT and PROJECT
SELECT and PROJECT can be combined
together. For example, to get a list of
employee numbers for employees in
department number 1:
Π empno , σ dpno=1 (employee)

ENG ELHAM MOH'D


Selection: Example
Another selection
Example of Projection
Projection removes duplicates
CROSS PRODUCT, X - Combines the
tuples from two relations to create new
tuples containing attributes from both
original relations. Every tuple from one
relation is combined with every tuple from
the other relation.

Cross product
ENG ELHAM MOH'D
Cross Product Example
Each tuple in R1 with each tuple in R2
Notation: R1  R2
Example:
◦ Employee  Dependents
Very rare in practice; mainly used to
express joins

Cartesian Product
Cartesian Product Example

Employee
Name SSN
John 999999999
Tony 777777777

Dependents
EmployeeSSN Dname
999999999 Emily
777777777 Joe

Employee x Dependents
Name SSN EmployeeSSN Dname
John 999999999 999999999 Emily
John 999999999 777777777 Joe
Tony 777777777 999999999 Emily
Tony 777777777 777777777 Joe
Set operation-semantic
• Consider two relations R and S.
• UNION of R and S
the union of two relations is a relation that
includes all the tuples that are either in R
or in S or in both R and S. Duplicate tuples
are eliminated.
• INTERSECTION of R and S
the intersection of R and S is a relation that
includes all tuples that are both in R and S.
• DIFFERENCE of R and S
the difference of R and S is the relation that
contains all
ENG ELHAM MOH'D
Relations r, s:

A B A B

 1  2
 2  3
 1 s
r

A B

 r  s:  1
 2
 1
 3
Union Operation – Example
Union Example
Union Compatibility
Intersection
Set Difference Operation –
Example
Relations r, s:
A B A B

 1  2
 2  3
 1 s
r

 r – s:
A B

 1
 1
Example to illustrate the result of
UNION, INTERSECT, and DIFFERENCE
Slide 6- 33
Some additional operations are:
• Intersection “∩ “
• Join “ “
• Renaming “ρ “

Operations rake relations as input, and


output relations
~ operations can be
composed!
Operations
ENG ELHAM MOH'D
Example SELECT
 If the original relation, Customer, contained the
following data:
customer_no name address tel_no
Anne
1 15 Broomilea Drive Denpasar EX1 2XS 01789277883
Wetherby
22 Clarence Drive Wolverhampton WH3
2 Peter Smith 01788 266777
2DX
3 Ben Hinckley 2 Hexam Drive Hexam HQ12 4TG 01276 355228
4 Robert Harthill 3 Coleshill Birmingham BH1 6GT 02776 338112
5 Peter Michaels 26 Market Square Leicester LE19 3RT 01286 337373

6 Dudley Smith 44 Tamworth Crescent Walsall WA19 6HJ 02899 366227

7 Peter Michaels 10 PinkLady Drive Kuala Lumpur EX1 2XS 01789277883

ENG ELHAM MOH'D


EXAMPLE SELECT
Then the result of the SELECT is as below
customer_no name address tel_no

22 Clarence Drive Wolverhampton WH3


2 Peter Smith 01788 266777
2DX
3 Ben Hinckley 2 Hexam Drive Hexam HQ12 4TG 01276 355228
Robert
4 3 Coleshill Birmingham BH1 6GT 02776 338112
Harthill
Peter
5 26 Market Square Leicester LE19 3RT 01286 337373
Michaels

Four rows have been selected from the relation, Customer.


The equivalent relational algebra expression follows:
σc.customer_no>=2 and c.customer_no<6Customer

ENG ELHAM MOH'D


Deletes attributes not in the projection list
Schema of result contains the attributes in
the projection list
Project is used to select specific attributes,
fields, or columns, from a single relation.
We use the Greek symbol for p, pi or Π to
represent the PROJECT operator.

Example Projection
ENG ELHAM MOH'D
Example PROJECTION
name tel_no
• πc.name, c.tel_noCustomer
Anne 01789277883
Wetherby
Peter Smith 01788 266777

Ben Hinckley 01276 355228

Robert Harthill 02776 338112

Peter 01286 337373


Michaels
Dudley Smith 02899 366227

Peter 01789277883
Michaels

ENG ELHAM MOH'D


Rename operation

The rename operation is used to store


the result of relational-algebra
expression under a different name. It is
denoted by lowercase Greek letter rho
( р ).
Given a relational-algebra expression E,
the expression
 рx(A1,…An) ( E )
returns the result of expression E under
the name x.

ENG ELHAM MOH'D


Changes the schema, not the instance
Notation:  B1,…,Bn (R)
Example:
◦ LastName, SocSocNo (Employee)
◦ Output schema:
Answer(LastName, SocSocNo)

Renaming
Renaming Example

Employee
Name SSN
John 999999999
Tony 777777777

LastName, SocSocNo (Employee)


LastName SocSocNo
John 999999999
Tony 777777777
Supplier × Purchase_Order
• This shows the name of the first relation, followed
by the CROSS PRODUCT operator, followed by the
name of the second relation, to which the cross
product will be applied.

EXAMPLE CROSS PRODUCT


ENG ELHAM MOH'D
EXAMPLE JOIN
ENG ELHAM MOH'D
Join: Example
EXAMPLE JOIN
•Forexample, if the original relations, Supplier and
Purchase_Order, contained the following data:

Supplier
supplier
name address contact_name tel_no
_no
Phones 4 Everyone 01637
1 Unit 10 Count Drive Northampton NH10 4EX Mr Smith
Ltd 890226
Mrs. 01456
2 MP Tradesales 3 Clarence Drive Wolverhampton WX10 2GT
Applegate 789267
Peter 01287
3 Buzz Mobiles Ltd 10 Green Gate Norwich NA2 6DT
Taverham 383991
Phone Accessories 01275
4 Warwick Crescent Leicester LE10 3AT Mr Studley
Direct 339482
2 Lindridge Industrial Estate Lindridge LD12 01534
5 Orion Express Mr Wheathill
4TD 729467
Unit 8 Knowle Industrial Estate Knowle KN22 01237
6 Activity Phones Ltd. Mr Solihull
3AX 228999

ENG ELHAM MOH'D


EXAMPLE JOIN

And Purchase

purchase_order_no supplier_no date


1 1 2005-06-25
2 2 2005-06-26
19 2 2005-10-16
24 6 2005-09-12

ENG ELHAM MOH'D


JOIN
Then the result of the join would be a new relation with
the structure shown below and containing the tuples
listed below:
Purchase
Supplier Supplier
name address contact_name tel_no _order_ date
_no _no
no

Phones 4 Unit 10 Count Drive Northampton 01637


1 Mr Smith 1 1 2005-06-25
Everyone Ltd NH10 4EX 890226

3 Clarence Drive Wolverhampton 01456


2 MP Tradesales Mrs. Applegate 2 2 2005-06-26
WX10 2GT 789267

3 Clarence Drive Wolverhampton 01456


2 MP Tradesales Mrs. Applegate 19 2 2005-10-16
WX10 2GT 789267

Activity
Unit 8 Knowle Industrial Estate 01237
6 Phones Mr Solihull 24 6 2005-09-12
Knowle KN22 3AX 228999
Ltd.

ENG ELHAM MOH'D


This is an example of an equijoin, where
the condition for matching tuples from both
relations depends on the values of the
matching field, or fields, in both relations
being equal.
A natural join is a special case of an
equijoin, where all attributes that have the
same name in the relations to be joined
form the basis of the join.

JOIN-natural join
ENG ELHAM MOH'D
 Invariably the JOIN involves an equality test,
and thus is often described as an equi-join.
Such joins result in two attributes in the
resulting relation having exactly the same
value. A `natural join' will remove the duplicate
attribute(s).
 In most systems a natural join will require that
the attributes have the same name to identify
the attribute(s) to be used in the join. This may
require a renaming mechanism.
 If you do use natural joins make sure that the
relations do not have two attributes with the
same name by accident

JOIN
ENG ELHAM MOH'D
S
R
A 1 A 1 R JOIN S
B 2 R.COLA=S.COLA
C 2
C 3 D 3
D 4
F 4
E 5

A 1 A 1
C 3 C 2

D 4 D 3

EXAMPLE JOIN
ENG ELHAM MOH'D
 The equivalent relational algebra expression
follows:
 Supplier
S.supplier_no=PO.supplier_no Purchase_Order

 This shows the name of the first relation,


Supplier, followed by JOIN operator, followed by
the condition controlling the join, which specifies
which attributes, fields, or columns are to be
matched, followed by the name of the second
relation, Purchase_Order, to which the join will be
applied.

EXAMPLE JOIN
ENG ELHAM MOH'D
Contains those tuples of the cross product
that satisfy some condition
The result schema is the same as that of
the cross product
However there are fewer tuples than cross
product ~ might be computationally more
efficient
E.g. S S1.supplier_no < P.supplier_no P

CONDITION JOIN
ENG ELHAM MOH'D
A special case of condition join where the
condition cond contains only equalities

E.g. S S1.supplier_no = P.supplier_no P

Result schema similar to cross product, but


only one copy of fields for which equality is
specified

EQUI-JOIN
ENG ELHAM MOH'D
 Taking into account the sailors
 Sailors(sid, sname, rating, age)

 Boats(bid, bname, color)

 Reserves(sid, bid, day)


algebra statements for:
1. Show the name of all sailor
2. Show details of all sailors.
3. Show all sailor name that their rating is 20.
4. Show the name of all red boat.
5. Show the name of red boat whcih starts with ‘ sea’.
6. Show the red boat was reserved more then 5 days
7. Find the names of the sailors who’ve reserved boat #103
8. Find the names of the sailors who’ve reserved a red boat
9. Find all sailors who have reserved a red or green boat

ENG ELHAM MOH'D


Find names of sailors who’ve
reserved boat #103

Solution 1:  sname (( bid 103 Re serves)  Sailors)

 Solution 2:  (Temp1,  Re serves)


bid  103

 ( Temp2, Temp1  Sailors)


 sname (Temp2)

 Solution 3:  sname ( (Re serves  Sailors))


bid 103
ENG ELHAM MOH'D
Find
 namesabout
Information of sailors who
boat color ’ve
only
reserved
available inaBoats;
red boat
so need an extra join:

 sname (( Boats)  Re serves  Sailors)


color ' red '

 A more efficient solution:


 sname ( ((  Boats)  Re s)  Sailors)
sid bid color ' red '

 A query optimizer can find this given the first solution!


ENG ELHAM MOH'D
Find sailors who’ve reserved a red
or a green boat
Can identify all red or green boats, then
find sailors who’ve reserved one of
these boats:, (
 (Tempboats Boats))
color ' red '  color ' green '
 sname(Tempboats  Re serves  Sailors)

 Can also define Tempboats using union! (How?)



What happens if  is replaced by  in this query?
ENG ELHAM MOH'D
Find sailors who’ve reserved a red
and a green boat
Previous approach won’t work! Must
identify sailors who’ve reserved red boats,
sailors who’ve reserved green boats, then
find the intersection (note that sid is a
key for
 (Tempred ,  Sailors):
(( Boats)  Re serves))
sid color ' red '
 (Tempgreen,  (( Boats)  Re serves))
sid color ' green'

 sname((Tempred  Tempgreen)  Sailors)


ENG ELHAM MOH'D
The content of the database may
be modified using the following
operations:
Deletion
Insertion
Updating
All these operations are expressed
using the assignment operator.
DATA BASE OPERATION
ENG ELHAM MOH'D
A delete request is expressed similarly to a
query, except instead of displaying tuples to
the user, the selected tuples are removed
from the database.

• Can delete only whole tuples; cannot delete


values on only particular attributes

A deletion is expressed in relational algebra


by:
rr–E
DATA BASE OPERATION
ENG ELHAM MOH'D
Delete all account records in the Perryridge
branch.
 
account  account –  branch-name =
“Perryridge” (account)
 
Delete all loan records with amount in the
range of 0 to 50
loan  loan –  amount  0and amount  50
(loan)

DELETE EXAMPLE
ENG ELHAM MOH'D
To insert data into a relation, we either:
specify a tuple to be inserted
write a query whose result is a set of
tuples to be inserted
in relational algebra, an insertion is
expressed by:
 r r  E
 where r is a relation and E is a
relational algebra expression.

INSERT
ENG ELHAM MOH'D
Insert information in the database
specifying that Smith has $1200 in
account A-973 at the Perryridge branch.
 
account  account  {(“Perryridge”, A-
973, 1200)}
depositor  depositor  {(“Smith”, A-
973)}

INSERT
ENG ELHAM MOH'D
Make interest payments by increasing all
balances by 5 percent.
account   AN, BN, BAL * 1.05 (account)
where AN, BN and BAL stand for account-
number, branch-name and balance,
respectively.

UPDATE ENG ELHAM MOH'D

You might also like