0% found this document useful (0 votes)
17 views99 pages

DBMS Unit - 2

Uploaded by

aa9128707607
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views99 pages

DBMS Unit - 2

Uploaded by

aa9128707607
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

MODULE – 2

RELATIONAL MODEL

RELATIONAL ALGEBRA

MAPPING CONCEPTUAL DESIGN INTO A LOGICAL DESIGN

PREPARED BY MUSHTAQ AHMED D.M ASSISTANT


PROFESSOR,
DEPT. OF ISE
Relational Model Concepts
• The relational Model of Data is based on the concept of a Relation.
• A Relation is a mathematical concept based on the ideas of sets.
• The strength of the relational approach to data management comes from the formal foundation
provided by the theory of relations.
•When a relation is thought of as a table of values, each row(tuple) in the table represents a
collection of related data values.
•A row(tuple) represents a fact that typically corresponds to a real-world entity or relationship.
•The table name and column names are used to help to interpret the meaning of the values in
each row.
• In the formal relational model terminology
(i) a row is called a tuple
(ii) a column header is called an attribute
(iii) the table is called a relation.
Informal Definitions
RELATION: A table of values
◦ A relation may be thought of as a set of rows.
◦ A relation may alternately be though of as a set of columns.
◦ Each row represents a fact that corresponds to a real-world entity or
relationship.
◦ Each row has a value of an item or set of items that uniquely
identifies that row in the table.
◦ Sometimes row-ids or sequential numbers are assigned to identify
the rows in the table.
◦ Each column typically is called by its column name or column header
or attribute name.
Domains, Attributes, Tuples and Relations
Domain
• A domain D is a set of atomic values.

• Atomic means that each value in the domain is indivisible as far as the relational model is
concerned.
• Usa_phone_numbers. The set of ten-digit phone numbers valid in the United States.
• Social_security_numbers. The set of valid nine-digit Social Security numbers. (This is a
unique identifier assigned to each person in the United States for employment, tax, and
benefits purposes.)
• Employee_ages. Possible ages of employees in a company; each must be an integer value
between 15 and 80.
• A data type or format is also specified for each domain.
* For example, the data type for the domain Usa_phone_numbers can be declared as a
character string of the form (ddd)ddd-dddd, where each d is a numeric (decimal) digit and

the first three digits form a valid telephone area code

* The data type for Employee_ages is an integer number between 15 and 80.
Domains, Attributes, Tuples and Relations
• Relation Schema
• Relation schema R, denoted by R (A1, A2, .....An) is made up of a relation name R and a list of
attributes A1, A2, …, An
• Each attribute Ai is a name of a role played by some domain D in the relation schema R.
• D is called the domain of Ai and is denoted by dom(Ai).
• A relation schema is used to describe a relation; R is called the name of this relation

• Degree of the relation


The degree or arity of a relation is the number of attributes n of its relation schema.
• A relation of degree seven, which stores information about university students, would contain seven
attributes describing each student as follows:
STUDENT(Name, Ssn, Home_phone, Address, Office_phone, Age, Gpa)
• Using the data type of each attribute, the definition is sometimes written as:
STUDENT(Name: string, Ssn: string, Home_phone: string, Address: string, Office_phone: string,
Age: integer, Gpa: real)
• For this relation schema, STUDENT is the name of the relation, which has seven attributes.
dom(Name) = Names; dom(Ssn) = Social_security_numbers;
Contd…
Relation
◦ A relation or relation state r of the relation schema R (A1, A2, .....An), also
denoted by r(R), is a set of n – tuples r = {t1, t2, …, tm}.
◦ Each n – tuple t is an ordered list of n values t = <v1, v2, …,vn> , where each vi,
1≤ i ≤ n, is an element of dom(Ai) or is a special NULL value.

The terms relation intension for the relation schema R and relation
extension for a relation state r(R) are commonly used.
Mathematical Definition
A relation schema or relation state r(R) is a mathematical relation of degree n on
the domains dom(A1), dom(A2),…, dom(An) which is a subset of the Cartesian
product of the domains that defines R:
r(R) ⊆ (dom(A1) X dom(A2) X … X dom(An))

The Cartesian product specifies all possible combinations of values from the
underlying domains.

The total number of values, or cardinality in a domain D by |D|, the total


number of tuples in the Cartesian product is
|dom(A1)| X |dom(A2)| X … X |dom(An)|
Current relation state
◦ A relation state at a given time is called the current relation state.
Example…
Characteristics of Relations
Ordering of tuples in a relation

Ordering of values within a tuple and an Alternative definition of a


relation

Values and NULLs in tuples

Interpretation (Meaning) of a relation


Ordering of Tuples in a
Relation
A relation is a set of tuples.

 The tuples are not considered to be ordered,


even though they appear to be in the tabular
form.

Relation is not sensitive to the ordering of tuples.


Ordering of values within a tuple and an
Alternative definition of a relation
From the definition of the relation, an n – tuple is a ordered list of
values, so the ordering of values in a tuple is important.

Alternative Definition
◦ A relation schema R = {A1, A2, …, An} is a set of attributes, and a relation state
r(R) is a finite set of mappings r = {t1, t2, …, tm}, where each tuple ti is a
mapping from R to D, and D is the union of the attribute domains; that is, D =
dom(A1) U dom(A2) U … U dom(An).
Values and NULLs in the
Tuples
All values are considered atomic (indivisible).

This model sometimes called as the flat relational model.

A special NULL value is used to represent values that are unknown or


inapplicable to certain tuples.
Interpretation (Meaning) of a
Relation
The relation schema can be interpreted as a declaration or a type of
assertion.

For example, the schema of the student entity has a Name, SSN,
HomePhone, Address, Officephone, Age and GPA. Each tuple in the
relation can then be interpreted as a fact or a particular instance of the
relation.
Example…
Relational Model Notations
Following notations are used in the Relational Model:
◦ A relation schema R of degree n is denoted by R(A1, A2, …, An).
◦ The letters Q, R, S denote relation names.
◦ The letters q, r, s denote relation states.
◦ The letters t, u, v denote tuples.
Relational Model Constraints and
Relational Database Schemas
Constraints on databases can generally be divided into three main categories:

◦ Inherent model based or Implicit constraint


Constraints that are inherent to the data model-the constraint that a
relation cannot have duplicate tuples is an inherent constraint.

◦ Schema based or Explicit constraint


◦ Constraints that are directly expressed in schemas of the data model

◦ Application based or Semantic constraint or Business rules


◦ Constraints that can not be directly expressed in schemas of the data model and
hence must be expressed and enforced by the application programs-Ex: Writing
assertions in application side
Constraints in the Relational Model

Domain Constraints

Key Constraints and Constraint on NULL values

Entity integrity constraints

Referential integrity constraints


Domain Constraints
These constraints specify that within each tuple, the value of each
attribute A must be an atomic value from the domain dom(A).

The data types associated with domains typically include standard


numeric data types for integers and real numbers.
Key Constraints and
Constraints on NULL values
Super Key
◦ It is a subset of attributes SK where any two distinct tuples t1 and t2 in a relation state r of R,
we have the constraint that t1[SK] ≠ t2[SK]

Key
◦ A key K of a relation schema R is a super key of R with the additional property that removing
any attribute A from K leaves set of attributes K’ that is not a super key of R any more.

Candidate Key
◦ A relation schema may have more than one key. In this case, each of the keys is called a
candidate key.

Primary Key
◦ This is the candidate key whose values are used to identify tuples in the relation.
◦ The primary key of the relation schema are underlined.
Relational Databases and Relational Database
Schemas
Relational Database Schema
◦ A relational database schema S is a set of relation schemas S = {R1, R2, …, Rm}
and a set of integrity constraints IC.

Relational Database State


◦ A relational database state DB of S is a set of relation states DB = {r1, r2, …, rm}
such that each ri is a state of Ri and such that the ri relation states satisfy the
integrity constraints specified in IC.

A database state that does not obey all the integrity constraints is called
an invalid state, and a state that satisfies all the constraints in IC is called
a valid state.
Entity Integrity Constraints
The entity integrity constraint states that no primary key can be NULL.

This is because the primary key value is used to identify individual


tuples in a relation.

Having NULL values for the primary key implies that we can not identify
some tuples.

For example, if two or more tuples had NULL for their primary keys, we
might not be able to distinguish them if we tried to reference them
from other relations.
Schema Diagram
Example Database State
Referential Integrity
Constraints
The referential integrity constraint is specified between two
relations and is used to maintain the consistency among
tuples in the two relations.

Informally, the referential integrity constraint states that a


tuple in one relation that refers to another relation must
refer to an existing tuple in that relation.

For example, the DNO of EMPLOYEE gives the department


number for which each employee works; hence, its value in
every EMPLOYEE tuple must match the DNUMBER value of
some tuple in the DEPARTMENT relation.
Foreign Key
The condition for a foreign key specify a referential integrity constraint between the two
relation schemas R1 and R2.

A set of attributes FK in the relation schema R 1 is a foreign key of R1 that references


relation R2 if it satisfies the following rules:

◦ The attributes in FK have the same domain(s) as the primary key attributes PK of R 2; the
attributes FK are said to reference or refer to the relation R 2.

◦ The value of FK in a tuple t1 of the current state r1(R1) either occurs as a value of PK for some
tuple t2 in the current state r2(R2) or is NULL. In the former case, we have t 1[FK] = t2[PK], and we
say that the tuple t1 references or refers to the tuple t2.

In this definition, R1 is called the referencing relation and R2 is the referenced relation.`
Update Operations and Dealing with
Constraint Violations
The operations of the relational model can be categorized into retrievals
and update.

There are three basic update operations:


◦ Insert
◦ Delete
◦ Modify
The Insert Operation-All
The insert operation provides a list of attribute values for a new tuple
t that is to be inserted into a relation R.
Insert can violate any of the four types of constraints.
1. Insert <‘Cecilia’, ‘F’, ‘Kolonsky’, null, ‘1960-04-05’, ‘6357 Windy
Lane, Katy, TX’, F, 28000, null, 4> into EMPLOYEE.

2. Insert <‘Alicia’, ‘J’, ‘Zelaya’, ‘999887777’, ‘1960-04-05’, ‘6357


Windy Lane, Katy, TX’, F, 28000, ‘987654321’, 4> into EMPLOYEE.

3. Insert <‘Cecilia’, ‘F’, ‘Kolonsky’, ‘677678989’, ‘1960-04-05’, ‘6357


Windswept, Katy, TX’, F, 28000, ‘987654321’, 7> into EMPLOYEE.

4. Insert <‘Cecilia’, ‘F’, ‘Kolonsky’, ‘677678989’, ‘1960-04-05’, ‘6357


Windy Lane, Katy, TX’, F, 28000, null, 4> into EMPLOYEE.
The Delete Operation-RI
The delete operation is used to delete the tuples from the relation.

Eg:

Delete the WORKS_ON tuple with ESSN = ‘999887777’ and PNO = 10.

Delete the EMPLOYEE tuple with SSN = ‘999887777’.

Delete the EMPLOYEE tuple with SSN = ‘333445555’.


The Update Operation
The update(or Modify) operation is used to change the values of one or more attributes in
a tuple(or tuples) of some relation R.

Eg:

Update the SALARY of the EMPLOYEE tuple with SSN = ‘999887777’ to 28000.

Update the DNO of the EMPLOYEE tuple with SSN = ‘999887777’ to 1.

Update the DNO of the EMPLOYEE tuple with SSN = ‘999887777’ to 7.

Update the SSN of the EMPLOYEE tuple with SSN = ‘999887777’ to ‘987654321’.
The Transaction Concept
A database application program running against a relational database typically runs a
series of transactions.

A transaction involves reading from the database as well as doing insertions, deletions
and updates to existing values in the database.

These transactions must leave the database in a consistent state.

A single transaction may involve any number of retrieval operations that reads from the
database and any number of update operations.

A large number of commercial applications running against relational databases in the


Online Transaction Processing(OLTP) systems are executing transactions at rates several
hundreds per second.
Relational Algebra Overview

• Relational algebra is the basic set of operations for the relational model

•These operations enable a user to specify basic retrieval


requests (or queries)
•The result of an operation is a new relation, which may have been formed from
one or more input relations
• This property makes the algebra “closed” (all objects in relational algebra are relations)

The algebra operations thus produce new relations


◦ These can be further manipulated using operations of the same algebra

A sequence of relational algebra operations forms a relational algebra expression


◦ The result of a relational algebra expression is also a relation
that represents the result of a database query (or retrieval
request)
Relational Algebra Overview

Relational Algebra consists of several groups of operations


◦ Unary Relational Operations
◦ SELECT (symbol:  (sigma))
◦ PROJECT (symbol:  (pi))
◦ RENAME (symbol:  (rho))
◦ Relational Algebra Operations From Set Theory
◦ UNION (  ), INTERSECTION (  ), DIFFERENCE (or MINUS, – )
◦ CARTESIAN PRODUCT ( x )
◦ Binary Relational Operations
◦ JOIN (several variations of JOIN exist)
◦ DIVISION
◦ Additional Relational Operations
◦ OUTER JOINS, OUTER UNION
◦ AGGREGATE FUNCTIONS (These compute summary of information: for example,
SUM, COUNT, AVG, MIN, MAX)
Database State for COMPANY
All examples discussed below refer to the COMPANY database shown
here.
Unary Relational Operations: SELECT
The SELECT operation (denoted by  (sigma)) is used to select a subset of the
tuples from a relation based on a selection condition.
◦ The selection condition acts as a filter
◦ Keeps only those tuples that satisfy the qualifying condition
◦ Tuples satisfying the condition are selected whereas the other tuples
are discarded (filtered out)
Examples:
◦ Select the EMPLOYEE tuples whose department number is 4:

s PNAME = ‘ABC’ (PROJECT)

◦ Select the employee tuples whose salary is greater than $30,000:

 SALARY > 30,000 (EMPLOYEE)


Unary Relational Operations: SELECT
◦ In general, the select operation is denoted by 
<selection condition> (R) where

the symbol  (sigma) is used to denote the select operator
◦ the selection condition is a Boolean (conditional) expression specified on the attributes of
relation R
◦ tuples that make the condition true are selected
◦ appear in the result of the operation
◦ tuples that make the condition false are filtered out
◦ discarded from the result of the operation
Unary Relational Operations: SELECT
(contd.)
SELECT Operation Properties
◦ The SELECT operation  <selection condition>(R) produces a relation S that has the same schema
(same attributes) as R

◦ SELECT  is commutative:
◦  <condition1>( < condition2> (R)) =  <condition2> ( < condition1> (R))

◦ Because of commutativity property, a cascade (sequence) of SELECT operations may be


applied in any order:
◦ <cond1>(<cond2> (<cond3> (R)) = <cond2> (<cond3> (<cond1> ( R)))

◦ A cascade of SELECT operations may be replaced by a single selection with a conjunction


of all the conditions:
◦ <cond1>(< cond2> (<cond3>(R)) =  <cond1> AND < cond2> AND < cond3>(R)))

◦ The number of tuples in the result of a SELECT is less than (or equal to) the number of
tuples in the input relation R
The following query results refer to this
database state
Unary Relational Operations: PROJECT
PROJECT Operation is denoted by  (pi)
This operation keeps certain columns (attributes) from a relation and
discards the other columns.
◦ PROJECT creates a vertical partitioning
◦ The list of specified columns (attributes) is kept in each tuple
◦ The other attributes in each tuple are discarded

Example: To list each employee’s first and last name and salary, the
following is used:
LNAME, FNAME,SALARY(EMPLOYEE)
Unary Relational Operations: PROJECT
(cont.)

The general form of the project operation is:


<attribute list>(R)
◦  (pi) is the symbol used to represent the project operation
◦ <attribute list> is the desired list of attributes from relation R.

The project operation removes any duplicate tuples


◦ This is because the result of the project operation must be a set of tuples
◦ Mathematical sets do not allow duplicate elements.
Unary Relational Operations: PROJECT
(contd.)
PROJECT Operation Properties
◦ The number of tuples in the result of projection <list>(R) is always less or
equal to the number of tuples in R
◦ If the list of attributes includes a key of R, then the number of tuples in the result of PROJECT is
equal to the number of tuples in R
◦ PROJECT is not commutative
◦  <list1> ( <list2> (R) ) =  <list1> (R) as long as <list2> contains the attributes in <list1>
Examples of applying SELECT and
PROJECT operations
Relational Algebra
Expressions
We may want to apply several relational algebra operations one after
the other
◦ Either we can write the operations as a single relational algebra expression
by nesting the operations, or
◦ We can apply one operation at a time and create intermediate result
relations.

In the latter case, we must give names to the


relations that hold the intermediate results.
Single expression versus sequence of
relational operations (Example)
To retrieve the first name, last name, and salary of all
employees who work in department number 5, we must
apply a select and a project operation
We can write a single relational algebra expression as
follows:
◦ FNAME, LNAME, SALARY( DNO=5(EMPLOYEE))
OR We can explicitly show the sequence of operations,
giving a name to each intermediate relation:
◦ DEP5_EMPS   DNO=5(EMPLOYEE)
◦ RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)
Unary Relational Operations: RENAME
The RENAME operator is denoted by  (rho)
In some cases, we may want to rename the attributes of a relation or
the relation name or both
◦ Useful when a query requires multiple operations
◦ Necessary in some cases (see JOIN operation
later)
Unary Relational Operations: RENAME
(contd.)
The general RENAME operation  can be expressed by any of the
following forms:
◦ S (B1, B2, …, Bn )(R) changes both:
◦ the relation name to S, and
◦ the column (attribute) names to B1, B1, …..Bn
◦ S(R) changes:
◦ the relation name only to S
◦ (B1, B2, …, Bn )(R) changes:
◦ the column (attribute) names only to B1, B1, …..Bn
Unary Relational Operations: RENAME
(contd.)
For convenience, we also use a shorthand for renaming attributes in an
intermediate relation:
◦ If we write:
• RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)
• RESULT will have the same attribute names as
DEP5_EMPS (same attributes as EMPLOYEE)
•If we write:
• RESULT (F, M, L, S, B, A, SX, SAL, SU, DNO) 
FNAME, LNAME, SALARY (DEP5_EMPS)
• The 10 attributes of DEP5_EMPS are renamed to F, M,
L, S, B, A, SX, SAL, SU, DNO, respectively
Example of applying multiple operations and
RENAME
Relational Algebra Operations from
Set Theory: UNION
UNION Operation
◦ Binary operation, denoted by 
◦ The result of R  S, is a relation that includes all tuples that are either in R or
in S or in both R and S
◦ Duplicate tuples are eliminated
◦ The two operand relations R and S must be “type
compatible” (or UNION compatible)
◦ R and S must have same number of attributes
◦ Each pair of corresponding attributes must be type
compatible (have same or compatible domains)
Relational Algebra Operations from
Set Theory: UNION
Example:
◦ To retrieve the social security numbers of all employees who
either work in department 5 (RESULT1 below) or directly supervise
an employee who works in department 5 (RESULT2 below)
◦ We can use the UNION operation as follows:

DEP5_EMPS  DNO=5 (EMPLOYEE)


RESULT1   SSN(DEP5_EMPS)
RESULT2(SSN)  SUPERSSN(DEP5_EMPS)
RESULT  RESULT1  RESULT2
◦ The union operation produces the tuples that are in either
RESULT1 or RESULT2 or both
Example of the result of a UNION operation
UNION Example
Relational Algebra Operations from
Set Theory
Type Compatibility of operands is required for the binary set
operation UNION , (also for INTERSECTION , and SET
DIFFERENCE –, see next slides)
R1(A1, A2, ..., An) and R2(B1, B2, ..., Bn) are type compatible
if:
◦ they have the same number of attributes, and
◦ the domains of corresponding attributes are type compatible
(i.e. dom(Ai)=dom(Bi) for i=1, 2, ..., n).
The resulting relation for R1R2 (also for R1R2, or R1–R2,
see next slides) has the same attribute names as the first
operand relation R1 (by convention)
Relational Algebra Operations from Set
Theory: INTERSECTION
INTERSECTION is denoted by 
The result of the operation R  S, is a relation
that includes all tuples that are in both R and S
◦ The attribute names in the result will be the same
as the attribute names in R
The two operand relations R and S must be “type
compatible”
Relational Algebra Operations from Set
Theory: SET DIFFERENCE (cont.)
SET DIFFERENCE (also called MINUS or EXCEPT) is denoted by –
The result of R – S, is a relation that includes all tuples that are in R but not in S
◦ The attribute names in the result will be the same
as the attribute names in R
The two operand relations R and S must be “type
compatible”
Example to illustrate the result of UNION,
INTERSECT, and DIFFERENCE
Some properties of UNION, INTERSECT,
and DIFFERENCE
Notice that both union and intersection are commutative
operations; that is
◦ R  S = S  R, and R  S = S  R

Both union and intersection can be treated as n-ary


operations applicable to any number of relations as both
are associative operations; that is
◦ R  (S  T) = (R  S)  T
◦ (R  S)  T = R  (S  T)

The minus operation is not commutative; that is, in general


◦ R–S≠S–R
Relational Algebra Operations from Set
Theory: CARTESIAN PRODUCT
CARTESIAN (or CROSS) PRODUCT Operation
◦ This operation is used to combine tuples from two relations in
a combinatorial fashion.
◦ Denoted by R(A1, A2, . . ., An) x S(B1, B2, . . ., Bm)
◦ Result is a relation Q with degree n + m attributes:
◦ Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
◦ The resulting relation state has one tuple for each combination
of tuples—one from R and one from S.
◦ Hence, if R has nR tuples (denoted as |R| = nR ), and S has nS
tuples, then R x S will have nR * nS tuples.
◦ The two operands do NOT have to be "type compatible”
Relational Algebra Operations from Set
Theory: CARTESIAN PRODUCT (cont.)
Generally, CROSS PRODUCT is not a meaningful operation
◦ Can become meaningful when followed by other operations

Example (not meaningful):


◦ FEMALE_EMPS   SEX=’F’(EMPLOYEE)
◦ EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS)
◦ EMP_DEPENDENTS  EMPNAMES x DEPENDENT

EMP_DEPENDENTS will contain every combination of


EMPNAMES and DEPENDENT
◦ whether or not they are actually related
Relational Algebra Operations from Set
Theory: CARTESIAN PRODUCT (cont.)
To keep only combinations where the DEPENDENT is related to the
EMPLOYEE, we add a SELECT operation as follows
Example (meaningful):
◦ FEMALE_EMPS   SEX=’F’(EMPLOYEE)
◦ EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS)
◦ EMP_DEPENDENTS  EMPNAMES x DEPENDENT
◦ ACTUAL_DEPS   SSN=ESSN(EMP_DEPENDENTS)
◦ RESULT   FNAME, LNAME, DEPENDENT_NAME (ACTUAL_DEPS)
RESULT will now contain the name of female employees and
their dependents
Example of applying CARTESIAN
PRODUCT
Binary Relational Operations: JOIN
JOIN Operation (denoted by )

◦ The sequence of CARTESIAN PRODECT followed by SELECT is used quite


commonly to identify and select related tuples from two relations
◦ A special operation, called JOIN combines this sequence into a single
operation
◦ This operation is very important for any relational database with more
than a single relation, because it allows us combine related tuples from
various relations
◦ The general form of a join operation on two relations R(A1, A2, . . ., An)
and S(B1, B2, . . ., Bm) is:
R <join condition>S
◦ where R and S can be any relations that result from general relational
algebra expressions.
Binary Relational Operations: JOIN (cont.)

Example: Suppose that we want to retrieve the name of the manager of each
department.
◦ To get the manager’s name, we need to combine each DEPARTMENT tuple with the

EMPLOYEE tuple whose SSN value matches the MGRSSN value in the department tuple.

◦ We do this by using the join operation.

◦ DEPT_MGR  DEPARTMENT MGRSSN=SSN EMPLOYEE

MGRSSN=SSN is the join condition


◦ Combines each department record with the employee who manages the department

◦ The join condition can also be specified as DEPARTMENT.MGRSSN= EMPLOYEE.SSN


Example of applying the JOIN operation
Some properties of JOIN
Consider the following JOIN operation:

◦ R(A1, A2, . . ., An) S(B1, B2, . . ., Bm)


R.Ai=S.Bj
◦ Result is a relation Q with degree n + m attributes:
◦ Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
◦ The resulting relation state has one tuple for each combination of tuples—r from R and s
from S, but only if they satisfy the join condition r[Ai]=s[Bj]
◦ Hence, if R has nR tuples, and S has nS tuples, then the join result will generally have less
than nR * nS tuples.
◦ Only related tuples (based on the join condition) will appear in the result
Some properties of JOIN
The general case of JOIN operation is called a Theta-join: R S
theta

The join condition is called theta


Theta can be any general boolean expression on the attributes of R and
S; for example:
◦ R.Ai<S.Bj AND (R.Ak=S.Bl OR R.Ap<S.Bq)

Most join conditions involve one or more equality conditions “AND”ed


together; for example:
◦ R.Ai=S.Bj AND R.Ak=S.Bl AND R.Ap=S.Bq
Binary Relational Operations: EQUIJOIN
EQUIJOIN Operation
The most common use of join involves join conditions with equality
comparisons only
Such a join, where the only comparison operator used is =, is called an
EQUIJOIN.
◦ In the result of an EQUIJOIN we always have one or more pairs of attributes
(whose names need not be identical) that have identical values in every
tuple.
◦ The JOIN seen in the previous example was an EQUIJOIN.
Binary Relational Operations:
NATURAL JOIN Operation
NATURAL JOIN Operation
◦ Another variation of JOIN called NATURAL JOIN — denoted by
* — was created to get rid of the second (superfluous)
attribute in an EQUIJOIN condition.
◦ because one of each pair of attributes with identical values is
superfluous
◦ The standard definition of natural join requires that the two
join attributes, or each pair of corresponding join attributes,
have the same name in both relations
◦ If this is not the case, a renaming operation is applied first.
Binary Relational Operations
NATURAL JOIN (contd.)

Example: To apply a natural join on the DNUMBER attributes of DEPARTMENT and


DEPT_LOCATIONS, it is sufficient to write:
◦ DEPT_LOCS  DEPARTMENT * DEPT_LOCATIONS

Only attribute with the same name is DNUMBER


An implicit join condition is created based on this attribute:
DEPARTMENT.DNUMBER=DEPT_LOCATIONS.DNUMBER

Another example: Q  R(A,B,C,D) * S(C,D,E)


◦ The implicit join condition includes each pair of attributes with the same name,
“AND”ed together:
◦ R.C=S.C AND R.D.S.D
◦ Result keeps only one attribute of each such pair:
◦ Q(A,B,C,D,E)
Binary Relational Operations
NATURAL JOIN (contd.)

The NATURAL JOIN or EQUIJOIN operation can also be specified among multiple tables,
leading to an n-way join
• Project-department-manager combined information
• This combines each project tuple with its controlling department tuple into a single Tuple
• Then combines that tuple with an employee tuple that is the department manager.
• Project_Dept
Example of NATURAL JOIN operation
Complete Set of Relational Operations
The set of operations including SELECT , PROJECT  , UNION ,
DIFFERENCE - , RENAME , and CARTESIAN PRODUCT X is called a
complete set because any other relational algebra expression can be
expressed by a combination of these five operations.
For example:
◦ R  S = (R  S ) – ((R - S)  (S - R))
◦ R <join condition>S =  <join condition> (R X S)
Binary Relational Operations: DIVISION
DIVISION Operation
◦ The division operation is applied to two relations
◦ R(Z)  S(X), where X subset Z. Let Y = Z - X (and hence Z = X 
Y); that is, let Y be the set of attributes of R that are not attributes of S.

◦ The result of DIVISION is a relation T(Y) that includes a tuple t if tuples


tR appear in R with tR [Y] = t, and with
◦ tR [X] = ts for every tuple ts in S.

◦ For a tuple t to appear in the result T of the DIVISION, the values in t


must appear in R in combination with every tuple in S.
Example of DIVISION
Recap of Relational Algebra Operations
Additional Relational Operations: Aggregate
Functions and Grouping
A type of request that cannot be expressed in the basic
relational algebra is to specify mathematical aggregate
functions on collections of values from the database.
Examples of such functions include retrieving the average or
total salary of all employees or the total number of employee
tuples.
◦ These functions are used in simple statistical queries that
summarize information from the database tuples.
Common functions applied to collections of numeric values
include
◦ SUM, AVERAGE, MAXIMUM, and MINIMUM.
The COUNT function is used for counting tuples or values.
Aggregate Function Operation
Use of the Aggregate Functional operation ℱ
◦ ℱMAX Salary (EMPLOYEE) retrieves the maximum salary value from
the EMPLOYEE relation
◦ ℱMIN Salary (EMPLOYEE) retrieves the minimum Salary value from
the EMPLOYEE relation
◦ ℱSUM Salary (EMPLOYEE) retrieves the sum of the Salary from the
EMPLOYEE relation
◦ ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE) computes the count (number)
of employees and their average salary
◦ Note: count just counts the number of rows, without removing
duplicates
Using Grouping with
Aggregation
The previous examples all summarized one or more attributes for a set
of tuples
◦ Maximum Salary or Count (number of) Ssn
Grouping can be combined with Aggregate Functions
Example: For each department, retrieve the DNO, COUNT SSN, and
AVERAGE SALARY
A variation of aggregate operation ℱ allows this:
◦ Grouping attribute placed to left of symbol
◦ Aggregate functions to right of symbol
◦ DNO ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE)

Above operation groups employees by DNO (department number) and


computes the count of employees and average salary per department
Examples of applying aggregate functions and
grouping
Illustrating aggregate functions and grouping
Additional Relational Operations (cont.)
Recursive Closure Operations
◦ Another type of operation that, in general, cannot be
specified in the basic original relational algebra is
recursive closure.
◦ This operation is applied to a recursive relationship.
◦ An example of a recursive operation is to retrieve all
SUPERVISEES of an EMPLOYEE e at all levels — that is,
all EMPLOYEE e’ directly supervised by e; all
employees e’’ directly supervised by each employee
e’; all employees e’’’ directly supervised by each
employee e’’; and so on.
Additional Relational Operations (cont.)
Although it is possible to retrieve employees at each level and then take
their union, we cannot, in general, specify a query such as “retrieve the
supervisees of ‘James Borg’ at all levels” without utilizing a looping
mechanism.
◦ The SQL3 standard includes syntax for recursive closure.
Additional Relational Operations (cont.)
Additional Relational Operations (cont.) : OUTER JOIN

•The JOIN operations described earlier match tuples that satisfy the join condition.
For example, for a NATURAL JOIN operation R * S, only tuples from R that have
matching tuples in S—and vice versa—appear in the result
• Hence
(i)Tuples without a matching (or related) tuple are eliminated from the JOIN
result.
(ii)Tuples with NULL values in the join attributes are also eliminated.
•This type of join, where tuples with no match are eliminated, is known as an inner
join.
•This amounts to the loss of information if the user wants the result of the JOIN to
include all the tuples in one or more of the component relations.
Additional Relational Operations (cont.)
The left outer join operation keeps every tuple in the first or left
relation R in ; if no matching tuple is found in S, then the
attributes of S in the join result are filled or “padded” with null values.
A similar operation, right outer join, keeps every tuple in the second or
right relation S in the result of
A third operation, full outer join, denoted by keeps all tuples in
both the left and the right relations when no matching tuples are found,
padding them with null values as needed.
Additional Relational Operations (cont.)

• The LEFT OUTER JOIN operation keeps every tuple in the first, or left, relation R in R
S;

• if no matching tuple is found in S, then the attributes of S in the join result are filled or
padded with NULL values. The result of these operations is shown
Example Database State
Additional Relational Operations (cont.)
OUTER UNION Operations
◦ The outer union operation was developed to take the union of tuples from
two relations if the relations are not type compatible.
◦ This operation will take the union of tuples in two relations R(X, Y) and S(X, Z)
that are partially compatible, meaning that only some of their attributes, say
X, are type compatible.
◦ The attributes that are type compatible are represented only once in the
result, and those attributes that are not type compatible from either relation
are also kept in the result relation T(X, Y, Z).
Additional Relational Operations (cont.)
Example: An outer union can be applied to two relations
whose schemas are STUDENT(Name, SSN, Department,
Advisor) and INSTRUCTOR(Name, SSN, Department, Rank).
◦ Tuples from the two relations are matched based on having the
same combination of values of the shared attributes— Name,
SSN, Department.
◦ If a student is also an instructor, both Advisor and Rank will have a
value; otherwise, one of these two attributes will be null.
◦ The result relation STUDENT_OR_INSTRUCTOR will have the
following attributes:
STUDENT_OR_INSTRUCTOR (Name, SSN, Department,
Advisor, Rank)
Query 1. Retrieve the name and address of all employees who work for
the ‘Research’ department.

Query 2. For every project located in ‘Stafford’, list the project number,
the controlling department number, and the department manager’s last
name, address, and birth date.
Examples of Queries in Relational Algebra
 Q1: Retrieve the name and address of all employees who work for the
‘Research’ department.
RESEARCH_DEPT   DNAME=’Research’ (DEPARTMENT)
RESEARCH_EMPS  (RESEARCH_DEPT DNUMBER= DNOEMPLOYEE EMPLOYEE)
RESULT   FNAME, LNAME, ADDRESS (RESEARCH_EMPS)

 Q6: Retrieve the names of employees who have no dependents.


ALL_EMPS   SSN(EMPLOYEE)
EMPS_WITH_DEPS(SSN)   ESSN(DEPENDENT)
EMPS_WITHOUT_DEPS  (ALL_EMPS - EMPS_WITH_DEPS)
RESULT   LNAME, FNAME (EMPS_WITHOUT_DEPS * EMPLOYEE)
Example Database State
Relational Database Design Using
ER – to – Relational Mapping
1. Mapping of Regular Entity Types
2. Mapping of Weak Entity Types
3. Mapping of Binary 1:1 Relationship Types
4. Mapping of Binary 1:N Relationship Types
5. Mapping of Binary M:N Relationship Types
6. Mapping of Multivalued Attributes
7. Mapping of N – ary Relationship Types
Mapping of Regular Entity
Types
For each regular(strong) entity type E in the ER schema, create a relation R that includes
all simple attributes of E.

Include only the simple component attributes of a composite attribute.

Choose one of the key attributes of E as the primary key of R.

If the chosen key of E is a composite, then the set of simple attributes that form it will
together form the primary key of R.

If multiple keys were identified for E during the conceptual design, the information
describing the attributes that form each additional key is kept in order to specify
secondary keys of relation R.
Mapping of Weak Entity
Types
For each weak entity type W in the ER schema with owner entity type E,
create a relation R and include all simple attributes of W as attributes of R.

In addition, include as foreign key attributes of R, the primary key


attribute(s) of the relation(s) that correspond to the owner entity type(s).

The primary key of R is the combination of the primary key(s) of the


owner(s) and the partial key of the weak entity type W, if any.

If there is a weak entity type E2 whose owner is also a weak entity type E 1,
then E1 should be mapped before E2 to determine its primary key first.
Mapping of Binary 1:1 Relationship Types
For each binary 1:1 relationship type R in ER schema, identify the
relations S and T that correspond to the entity types participating in R.

There are three possible approaches:


◦ The foreign key approach
◦ The merged relationship approach
◦ The cross reference or relationship relation approach
Mapping of Binary 1:N Relationship Types
For each regular binary 1:N relationship type R, identify the relation S
that represents the participating entity type at the N – side of the
relationship type.

Include as foreign key in S the primary key of relation T that represents


the other entity type participating in R.

Include any simple attributes of the 1:N relationship type as attributes


of S.
Mapping of Binary M:N Relationship Types
For each binary M:N relationship type R, create a new relation S to
represent R.

Include as foreign key attributes in S the primary keys of the relations


that represent the participating entity types.

Their combination will form the primary key of S.

Also include any simple attributes of the M:N relationship type as


attributes of S.
Mapping of Multivalued
Attributes
For each Multivalued attribute A, create a new relation R.

This relation R will include an attribute corresponding to A, plus the


primary key attribute K – as foreign key in R – of the relation that
represents the entity type or the relationship type that has A as an
attribute.

The primary key of R is the combination of A and K.


Mapping of N – ary Relationship Types
For each N – ary relationship type R, where n>2, create a new relation S to
represent R.

Include as foreign key attributes in S the primary keys of the relations that
represent the participating entity types.

Also include any simple attributes of the n – ary relationship type as attributes
of S.

The primary key of S is usually a combination of all the foreign keys that
reference the relations representing the participating entity types.
Data Definition, Constraints,
and Schema Changes
Used to CREATE, DROP, and ALTER the descriptions of the tables
(relations) of a database

You might also like