0% found this document useful (0 votes)
5 views122 pages

Understanding Relational Database Models

The document provides an overview of the relational model in database systems, detailing key concepts such as relations, tuples, attributes, and domains. It explains formal definitions, integrity constraints, and various types of keys including primary, foreign, candidate, and composite keys. Additionally, it discusses the importance of ensuring data integrity through constraints and the structure of relational schemas.

Uploaded by

Surya Anand
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)
5 views122 pages

Understanding Relational Database Models

The document provides an overview of the relational model in database systems, detailing key concepts such as relations, tuples, attributes, and domains. It explains formal definitions, integrity constraints, and various types of keys including primary, foreign, candidate, and composite keys. Additionally, it discusses the importance of ensuring data integrity through constraints and the structure of relational schemas.

Uploaded by

Surya Anand
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

School of Computing and Information Technology

Course Delivery

[Link] – IV Semester (B20CI0403 )

Unit-2
Relational Model
• Represents database as a collection of relations
• Flat file of records
• Tuple -- row
• Attribute -- column header
• Table – relation
Domains,Attributes , Tuples and Relations
• Domain D is a set of atomic values
• examples
• Usa_phone_numbers: The set of ten digit phone numbers
valid in united states
• Local_phone_numbers: The set of seven digit phone numbers
valid within a particular area code in united states
• Social_security_numbers: the set of valid nine digit socail
security numbers
• Names: The set of character strings that represents names of a
person
• Employee_ages: possible ages of emp in a company
• Data type can be specified for each domain
• Usa_phone_numbers – character string of form (ddd)ddd-dddd
• D – numeric digit
• First 3 digits– valid telephone area code
• Employee_ages: integer number between 15 and 80
Formal Definitions - Schema

• The Schema (or description) of a Relation:


• Denoted by R(A1, A2, .....An)
• R is the name of the relation
• The attributes of the relation are A1, A2, ..., An
• Example:
CUSTOMER (Cust-id, Cust-name, Address, Phone#)
• CUSTOMER is the relation name
• Defined over the four attributes: Cust-id, Cust-name, Address,
Phone#
• Each attribute has a domain or a set of valid values.
• For example, the domain of Cust-id is 6 digit numbers.

Slide 5- 4
Formal Definitions - Tuple

• A tuple is an ordered set of values (enclosed in angled


brackets ‘< … >’)
• Each value is derived from an appropriate domain.
• A row in the CUSTOMER relation is a 4-tuple and would
consist of four values, for example:
• <632895, "John Smith", "101 Main St. Atlanta, GA 30332",
"(404) 894-2000">
• This is called a 4-tuple as it has 4 values
• A tuple (row) in the CUSTOMER relation.
• A relation is a set of such tuples (rows)

Slide 5- 5
• STUDENT(Name, Ssn, Home_phone, Address, Office_phone,
Age, Gpa)
• STUDENT(Name : string , Ssn: string , Home_phone:string,
Address:string, Office_phone:string, Age:integer, Gpa:real)
• dom(Name) = Names
• r(R): relation state – this is a set of tuples (rows)
• r(R) = {t1, t2, …, tn} where each ti is an ordered list of n values
• ti = <v1, v2, …, vn> where each vj is an element-of dom(Aj)
• Relation intension -- schema R
• Relation extension -- Relation state
Formal Definitions - Example

• Let R(A1, A2) be a relation schema:


• Let dom(A1) = {0,1}
• Let dom(A2) = {a,b,c}
• Then: dom(A1) X dom(A2) is all possible combinations:
{<0,a> , <0,b> , <0,c>, <1,a>, <1,b>, <1,c> }

• The relation state r(R)  dom(A1) X dom(A2)


• For example: r(R) could be {<0,a> , <0,b> , <1,c> }
• this is one possible state (or “population” or “extension”) r of
the relation R, defined over A1 and A2.
• It has three 2-tuples: <0,a> , <0,b> , <1,c>

Slide 5- 7
Definition Summary

Informal Terms Formal Terms


Table Relation
Column Header Attribute
All possible Column Domain
Values
Row Tuple
Table Definition Schema of a Relation
Populated Table State of the Relation

Slide 5- 8
Example of a Relation

Slide 5- 9
• r(R)  dom (A1) X dom (A2) X ....X dom(An)
• Total number of tuples
|dom (A1)| X |dom (A2)| X ....X |dom(An)|
• Several attributes can have same domain, attribute names
indicate different roles
• Same domain USA_phone_numbers
• Home_phone
• Office_phone
Formal Definitions - Domain

• A domain has a logical definition:


• Example: “USA_phone_numbers” are the set of 10 digit phone numbers
valid in the U.S.
• A domain also has a data-type or a format defined for it.
• The USA_phone_numbers may have a format: (ddd)ddd-dddd where
each d is a decimal digit.
• Dates have various formats such as year, month, date formatted as
yyyy-mm-dd, or as dd mm,yyyy etc.

Slide 5- 11
Characteristics of Relations

1) Ordering of tuples in a relation


2) Ordering of values within a tuple and alternative
definition of a relation
N- tuple is an ordered list of n values
Definition : Relation schema is a set of attributes
Relation state r(R) is a finite set of mappings
r={ t1,t2…..tm} where each tuple is a mapping from R
TO D
D is union of attribute domains
D= dom(A1) dom(A2)………dom(An)
Tuple as mapping
(<attribute>, <value>) pairs
• each pairs give the value of mapping from an attribute Ai to Vi from dom(Ai)
• Attribute name + value = self-describing data
t = <(Name,Dick Davidson),(Sssn, 422-11-2320),(Home_phone,
NULL), (Address,3452 Elgin Road), (Office_phone,(817)749-
1253),(Age,25), (Gpa,3.53)>

t = < (Address,3452 Elgin Road), (Name,Dick Davidson),(Ssn,


422-11-2320), (Age,25), (Office_phone,(817)749-1253),
(Gpa,3.53),(Home_phone, NULL) >
Values and NULLs in tuple
Atomic values
Composite and multivalued attributes are not allowed
Multivalued – separate relation
Composite – simple component attributes
• Office_phone – null
• Home_phone – null
• Value unknown, not available, attribute does not
apply(undefined)
• Visa_status attribute to student
Applies only to foreign student
Interpretation of a relation
• Interpreted as a declaration or type of assertion
• STUDENT relation in fig asserts that in general a student entity has
name,ssn,Home_phone………………..
• Tuple in relation interpreted as a fact or particular instance of
assertion
• First tuple in figure asserts the fact that there is a STUDENT whose
Name is Benjamin Bayer, Ssn is 305-61-2435……
• Relation schema as predicate
• Eg
Predicate STUDENT(Name,Ssn…) is true for all five tuples
Relational Model Notation

• Relation schema – R(A1,A2...An)


• Q,R,S – relation names
• q,r,s – relation states
• t,u,v – tuples
Relational model constraints
• Inherent model based constraint(implicit )
• That are inherent in the data model
• Relation cannot have duplicate tuples
• Schema based constraint(explicit)
• Represented by schemas(in DDL)
• Key constraint, null, referential
• Application based(semantic constraint or
business rules)
• Not schema but enforced in application program
• Data dependencies
• Functional and multivalued dependencies
Relational Integrity Constraints

• Constraints are conditions that must hold on all valid


relation states.
• There are three main types of constraints in the relational
model:
• Key constraints
• Entity integrity constraints
• Referential integrity constraints
• Another implicit constraint is the domain constraint
• Every value in a tuple must be from the domain of its attribute
(or it could be null, if allowed for that attribute)

Slide 5- 19
Domain constraint
• Within each tuple , value of each attribute A must be atomic
value from domain dom(Ai)
• No two tuple in a relation can have same values
• SK – Subset of attribute(SUPER KEY)
• T1[SK] T2[SK]
• Key K of relation schems R is superkey of R with property that
removing any attribute A from K leaves set of attributes K’ that
is not a superkey of R anymore
Summary Chart:

Key Type Purpose Example


Primary Key Uniquely identifies records Employee_ID in Employees table

Foreign Key Creates relationship between Department_ID in Employees


tables (refers to Departments)

Candidate Key Can uniquely identify records (any Student_ID or Email in Students
of them could be the primary key)
Unique Key Ensures uniqueness, can have null Username or Email in Users

Composite Key Combination of columns to Student_ID + Course_ID in


uniquely identify records Course_Enrollments
Set of columns that uniquely Employee_ID + Email + Name in
Super Key identify records (even Employees
unnecessary ones)

Alternate Key A candidate key not chosen as Student_ID in Students (if Email is
primary key primary key)

Natural Key Based on real-world data, Social_Security_Number in


inherently unique Employees

Surrogate Key System-generated, meaningless Employee_Surrogate_ID in


key Employees
•A candidate key can be either single or composite, but it must be minimal.
•A composite key specifically refers to a key that requires multiple attributes to
•uniquely identify a record. It is one type of candidate key that involves more
•than one attribute.
Have a look at the following table with
the schema employees(Id, Name,
Gender, City, Email, Dep_Id)
• A Super Key is any combination of attributes that uniquely identifies
records, and adding extra, unnecessary attributes doesn't change the
fact that the combination is still a Super Key.
• The Id attribute (Employee ID) in a table uniquely identifies each
employee. This means Id is a Super Key because it can uniquely
identify all rows (tuples) in the table.
• However, a Super Key can also be formed by combining Id with other
attributes, even if those additional attributes aren't necessary for
uniqueness.
• For example:
• (Id, Name)
• (Id, Email)
• (Id, Name, Email)
• All of these are also Super Keys because the Id alone guarantees
uniqueness. The extra attributes (like Name or Email) aren't needed to
uniquely identify the tuples, but they can still be part of a Super Key.
What Are Candidate Keys in SQL?
A candidate key is a column or a combination of columns
that uniquely identifies each row in a table. It is used to
ensure that there are no duplicate or ambiguous records in
a table

A Candidate key is a subset of Super keys and devoid of


unnecessary attributes that are not important for
uniquely identifying tuples. For this reason, you can also
call the Candidate key a minimal Super key.
On the other hand, we cannot use the attributes
like City or Gender to retrieve tuples from the table, as they have no
unique values.

Whereas querying the table on the Id attribute will help


us to retrieve unique tuples.
What Are Primary Keys in SQL?

Primary key is the Candidate key selected by the database


administrator to uniquely identify tuples in a table.

Out of all the Candidate keys that can be possible for a table,
only one key will be used to retrieve unique tuples from the
table. This Candidate key is called the Primary Key.

There can be only one Primary key for a table. Depending on how
the Candidate Key is constructed, the primary key can be a singl
attribute or a group of attributes. But the important point is that th
Primary key should be a unique and non-null attribute(s)
There can be two ways to create a Primary key for the table.
The first way is to alter an already created to add the Primary
key constraint on an attribute. This is shown below:

Now if I try to add a new row with a duplicate Id value, it gives


me an error message.

The second way of adding a Primary key is during the creation


of the table itself. All you have to do is add the Primary Key
constraint at the end after defining all the attributes in the
table.
To define a Primary Key constraint on multiple attributes, you can list all
the attributes in the parenthesis, as shown below.

But remember that these attributes should be defined as non-null values;


otherwise, the whole purpose of using the Primary key to identify tuples
uniquely gets defeated.
What Are Alternate Keys or
Secondary Keys in SQL?

What Are Composite Keys in SQL?

A Composite key is a Candidate key or Primary key that


consists of more than one attribute.
Here, neither of the attributes contains unique values to
identify the tuples. Therefore, we can combine two or more
attributes to create a key uniquely identifying the tuples. For
example, we can group Transaction_Id and Product_Id to
create a key that can uniquely identify the tuples. These are
called composite keys.
Differences Between Various Keys in
SQL
•SQL keys are used to identify rows in a table uniquely.
•SQL keys can either be a single column or a group of
columns.
•A Super key is a single key or a group of multiple keys that can
uniquely identify tuples in a table.
•Super keys can contain redundant attributes that might not be
important for identifying tuples.
•Super keys are a superset of Candidate keys.
•Candidate keys are a subset of Super keys. They contain only
those attributes which are required to identify tuples uniquely.
•All Candidate keys are Super keys. But the vice-versa is not
true.
•A Primary key is a Candidate key chosen to uniquely identify
tuples in the table.
Key Constraints (continued)

The above table has following super keys. All of the following sets of
super key are able to uniquely identify a row of the employee table.

Slide 5- 34
• Key satisfies two properties
• Two distict tuples in any state of relation cannot have
identical values
• Minimal superkey(candidate key)– superkey from which we
cannot remove any attributes and still have uniqueness
constraint hold
• Key is superkey(not vice versa)
{Ssn} – key
{Ssn,name,age} – superkey
More than one key – candidate key
One among them – Primary
Another constraint
Null allowed or not
Every student name must have valid non null value
Name constrained to NOT NULL
Relational Database Schema
• S is a set of relational schemas S={R1,R2….Rm} and
a set of integrity constraints IC
• Relational database state DB of S is a set of relational
states DB={r1,r2….rm} such that each ri is a state of
Ri and such that ri relation state satisfies the IC
• Schema diagram
• Database state satisfying all IC – Valid state
• Invalid state
• Entity Integrity constraint – no primary key value can be
NULL
Referential integrity
• Tuples in one relation that refers to another relation must refer
to an existing tuple in that relation
• Dno of EMP must match Dnumber value in DEPT
Foreign key
• Two relations R1 and R2
• Set of attributes FK in relation schema R1 is foreign key of R2
that references Relation R2 if it satisfies following rules
• Attributes in FK have same domain as primary key attributes PK of R2
• Value of FK in t1 of current state r1(R1) either occurs as a value of PK for some t2 in state
r2(R2) or is NULL
• R1 – referencing relation
• R2 – referenced relation
• Two conditions satisfied– referential integrity constraint from
R1 to R2 is said to hold
• Dno-- foreign key of EMP referring to DEPT
• Dno should match value of primary key of DEPT
• John smith refers to research dept(diagram)
• Foreign key can refer to its own relation
• Super_ssn in EMP refers to supervisor of an EMP
• Eg
• John smith references tuple for EMP ‘franklin ’
• Franklin wong is supervisor of john smith
Other types of constraints
• Semantic integrity constraint
• Not part of DDL
• Salary of employee should not exceed salary of employee
supervisor
• Maximum num of hours an emp can work on project per
week is 56
• All constraint discussed so far are called state constraints
• Define constraints that a valid state of database must satisfy
• Transition constraint
• Defined to deal with state changes in database
eg : Salary of an employee can only increase
Update Operations on Relations

• In case of integrity violation, several actions can be taken:


• Cancel the operation that causes the violation (RESTRICT or REJECT option)
• Perform the operation but inform the user of the violation
• Trigger additional updates so the violation is corrected (CASCADE option, SET
NULL option)
• Execute a user-specified error-correction routine

Slide 5- 44
Possible violations for each operation

• INSERT may violate any of the constraints:


• Domain constraint:
• if one of the attribute values provided for the new tuple is not of
the specified attribute domain
• Key constraint:
• if the value of a key attribute in the new tuple already exists in
another tuple in the relation
• Referential integrity:
• if a foreign key value in the new tuple references a primary key
value that does not exist in the referenced relation
• Entity integrity:
• if the primary key value is null in the new tuple

Slide 5- 45
Possible violations for each operation

• DELETE may violate only referential integrity:


• If the primary key value of the tuple being deleted is referenced
from other tuples in the database
• Can be remedied by several actions: RESTRICT, CASCADE, SET
NULL
• RESTRICT option: reject the deletion
• CASCADE option: propagate the new primary key value into the
foreign keys of the referencing tuples
• SET NULL option: set the foreign keys of the referencing tuples to
NULL
• One of the above options must be specified during database
design for each foreign key constraint

Slide 5- 46
Possible violations for each operation

• UPDATE may violate domain constraint and NOT NULL


constraint on an attribute being modified
• Any of the other constraints may also be violated, depending
on the attribute being updated:
• Updating the primary key (PK):
• Similar to a DELETE followed by an INSERT
• Need to specify similar options to DELETE
• Updating a foreign key (FK):
• May violate referential integrity
• Updating an ordinary attribute (neither PK nor FK):
• Can only violate domain constraints

Slide 5- 47
Update operations
• Insert
• Delete
• Update
• Modify
• Insert
• Operation:

Insert<‘Cecilia’ , ‘F’ , ‘Kolonsky’ , NULL , ‘1960-04-05’,


‘6357 windy Lane, katy,TX’ , F , 28000, NULL ,4> into
EMPLOYEE
• Key Constraint

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


‘6357 windy Lane, katy,TX’ , F , 28000, ‘987654321’ , 4> into
EMPLOYEE

• Referential integrity

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


‘6357 windswept’, katy,TX’ , F , 28000, ‘987654321’ , 7> into
EMPLOYEE
• Acceptable( satisfies all constraint)

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


‘6357 windy Lane, katy,TX’ , F , 28000, NULL , 4> into
EMPLOYEE
• Delete operation
• Acceptable(deletes only one tuple)

Delete the WORKS_ON tuple with Essn=‘999887777’ and Pno


=10
• Not acceptable

Delete the Employee Tuple with Ssn = ‘999887777’


• Referential integrity violation
• Tuple referenced by tuples from EMP, DEPT,WORKS_ON
and dependent relations

Delete the EMP tuple with Ssn=‘333445555’

• Update operation

Update the salary of EMP tuple with Ssn=‘999887777’ to 28000


• unaccept – referential integrity
Update the Dno of EMP tuple with Ssn=‘999887777’ to 7
• Unaccept
• primary key constraint – repeating value that already exist as
PK in another tuple
• Referential – other relation that refer to existing value of
Ssn

Update the Ssn of EMP tuple with Ssn=‘999887777’ to


‘987654321’
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)

Slide 6- 53
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)
• In general, the select operation is denoted by
 <selection condition>(R)
• 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

Slide 6- 54
Unary Relational Operations: SELECT

• Examples:
• Select the EMPLOYEE tuples whose department number is 4:
 DNO = 4 (EMPLOYEE)
• Select the employee tuples whose salary is greater than $30,000:
 SALARY > 30,000 (EMPLOYEE)

Slide 6- 55
Unary Relational Operations: SELECT
(contd.)

• SELECT Operation Properties

• 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)))

Slide 6- 56
The following query results refer to this
database state

Slide 6- 57
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

Slide 6- 58
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.
• Example: To list each employee’s first and last name and salary, the
following is used:
LNAME, FNAME,SALARY(EMPLOYEE)

Slide 6- 59
Unary Relational Operations:
PROJECT (contd.)

• PROJECT is not commutative


•  <list1> ( <list2> (R) ) =  <list1> (R) as long as <list2> contains the attributes in
<list1>

Slide 6- 60
• Select the tuples for all employees who either work in department no
4 and make over $25000 per year, or work in department 5 and make
over $30000
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)

Slide 6- 63
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

Slide 6- 64
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

Slide 6- 65
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

Slide 6- 66
• TEMP   DNO=5(EMPLOYEE)
• R(First_name, Last_name,Salary)   FNAME, LNAME, SALARY (TEMP)
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)

Slide 6- 69
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

Slide 6- 70
Result of union operation
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)

Slide 6- 72
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”

Slide 6- 73
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”

Slide 6- 74
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

Slide 6- 76
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”

Slide 6- 77
Relational Algebra Operations from Set
Theory: CARTESIAN PRODUCT (cont.)

• To retrieve list of names of each female employees dependents.


• 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

Slide 6- 78
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

Slide 6- 79
Cartesian product
Binary Relational Operations: JOIN

• JOIN Operation (denoted by )

• A special operation, called JOIN combines this sequence into a


single operation

• 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.

Slide 6- 83
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 [Link]=
[Link]

Slide 6- 84
Some properties of JOIN

• 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

Slide 6- 86
Some properties of JOIN

• The general case of JOIN operation is called a Theta-join: R S


theta
• The join condition is called theta
• Most join conditions involve one or more equality conditions
“AND”ed together; for example:
• [Link]=[Link] AND [Link]=[Link] AND [Link]=[Link]

Slide 6- 87
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.

Slide 6- 88
Additional Relational Operations
(cont.)

• The OUTER JOIN Operation


• In NATURAL JOIN and EQUIJOIN, tuples without a matching (or
related) tuple are eliminated from the join result
• Tuples with null in the join attributes are also eliminated
• This amounts to loss of information.
• A set of operations, called OUTER joins, can be used when we
want to keep all the tuples in R, or all those in S, or all those in
both relations in the result of the join, regardless of whether or
not they have matching tuples in the other relation.

Slide 6- 89
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.
• A similar operation, right outer join, keeps every tuple in the second
or right relation S in the result of R S.
• 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.

Slide 6- 90
(INNER JOIN)

LEFT JOIN):
(RIGHT JOIN):

(FULL JOIN):
Additional Relational Operations
(cont.)

Slide 6- 93
LEFT JOIN):

(RIGHT JOIN):
(FULL JOIN):
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.

Slide 6- 98
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:
[Link]=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)

Slide 6- 99
Example of NATURAL JOIN operation

Slide 6- 100
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)

Slide 6- 101
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.
Slide 6- 102
Division operation
Query Tree
Recap of Relational Algebra
Operations

Slide 6- 106
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.

Slide 6- 107
Aggregate Function Operation

• Use of the Aggregate Functional operation ℱ(script F)


• ℱ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

Slide 6- 108
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
Slide 6- 109
Aggregate function operation
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.

Slide 6- 111
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 SSNs of all employees e’ directly supervised at level one by
employee e whose name is ‘James Borg’
• without utilizing a looping mechanism.
• The SQL3 standard includes syntax for recursive closure.

Slide 6- 112
Two level recursive query
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).

Slide 6- 119
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)

Slide 6- 120
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)

Slide 6- 121
Illustrating aggregate functions and
grouping

Slide 6- 122

You might also like