Professional Documents
Culture Documents
o The relational model eliminated all parent child relationshiPt and instead
represented all data in the database as simple row/column tables of data
values.
. A relation is similar to a table with rows/columns of data values.
. Each table is an independent entity and there is no physical relationship
between tables.
o Most data management systems based on the relational model have a built-in
zupport for qrJry languages like ANSI SQL or QBE. These queries- are
S"lirf" English construJs that allow adhoc data manipulation from a table.
. Relational model of data management is based on set theory.
. The user interface used with relational models is non-Procedural because
only what needs to be done is specified and not how it has to be done'
(3-1)
Database Management Systems 3 -2 Relational Model turhase Managemer
@ Lire{h
Database Management System ir@lEr:E 3= I
E.F. Codd's laws for a RDBMs are given below :
aiff|' E EELE
milF fu -:
2) Information representation : All information stored in a relational database b
r! nFE:T-:t l
represented only by data item values, which are stored in the tables that makc
up the database. qrf
3) Logical accessibility : Every data item value stored in a relational database is
accessible by stating the name of the table it is stored in, the name of the Reletion : -\ I
column under which it is stored and the value of the primary key that defines :e'adon consis
the row in which it is stored.
. Rrlttion Scfu
4) Representation of null values : The DBMS has a consistent method for H.i ,or colu
representing null values. For example, null values for numeric data must be tI
distinct from zero or any other numeric value and for character data it must be -terreci tr-
:r=:.lle : Cor
different from a string of blanks or any other character value.
;-;,cyee (Emt
5) Catalog facilities : The logical description of a relational database is jse.
represented in the same manner as ordinary data. This is done so that the the fiel,
facilities of the relational database mzrnagement system itself can be used to =---liated
rrit
maintain database description. . Reletion lnst
-^-iuch each tr
6) Data language : A relational DBMS may support many types of languages for
describing data and accessing the database. -\r. in-stance
7) View updatability : Any view that can be defined using combinations of base
tables, that are theoretically updatable, is capable of being updated by the
relationat DBMS.
8) Insert, update and delete : Any operand that describes the results of a single
retrieval operation is capable of being applied to an insert, update or delete
operation as well.
9) Physical data independence : Changes made to physical storage ,, ./
representations or access methods do not require changes to be made to luples /
rRours. Records)
application programs.
10) Logical data independence : Changes made to tables, that do not modify any
data stored in that table, do not require changes to be made to application
Programs.
L1) Integrity constraints : Constraints that apply to entity integrity and referential
integrity are specifiable by the data language implemented by the DBMS and I
not by the statements coded into the application program. lLe inst;rnce E1 I
'':rr> are identical. It
i- of unique tuplet
Y
rdel
Database Management Systems 3-3 Relational Model
11.1.1 Relations I
Degree
Fig. 3.1 An instance El of Employee relation
fhe instance EL has five tuples, and three columns. As shown in Fig. 3.1 no
two
G are identical. It satisfies the requirement of relational model that
each relation is
*
dr of unique tuples.
(Habase Manage
Database Management Systems 3-4 Relational Model
The degree, also called arity, of a relation is the number of fields in it.
. We cannr
Pounds.
The cardinalitity of a relation is the number of tuples in it in Fig. 3.L, the degree However,
of the relation is three and cardinality is five. (cast t
The relational database is a collection of relations with distinct relation Names. . 6hould a
The relational database schema is the collection of schemas for the relations in
database. An instance of a relational database is a collection of relation instances,
per relation schema in the database schema, each relation instance must satisfy
domain constraints in its schema. &dits irfi
t e hase rela
f priman- ke
In a relational database, all data is stored and accessed via relations. Relations Fima+- k T
store data are called "base relations" and in implementations are called "tables". ; ker- shou
relations do not store data, but are computed by applying relational operations , relatioru u
other relations. These relations are sometimes called "derived relations". d ir fte branc
implementations these are called "views" or "queries". Derived relations are conv
in that though they may grab information from several relations, they act as a f Eremiall Inft
relation. Also, derived relations can be used as an abstraction layer.
value that ;
-1,
1) Domain Constraints
. Domain constraints are the most elementary form of integrity constraint.
o They test values inserted in the database and test queries to ensure that the
comparisons make sense.
. New domains can be created from existing data types.
Integrity
The entity integrity constraint states that,
"In a base relatior; no attribute of a primary key can be null."
I
A primary key is used to identify tuples uniquely. This means that no subset of
I primary k"y is sufficient to provide unique identification of tuples. Therefore,
r key should not be null. For example, as Branch-no is the primary key of the
i
It relation, we should not be able to insert a tuple into the Branch relation with a
D
for the branch-no athibute.
I
E Integrity
F
? A value that in one relation for a given set of attributes also aPPears for
appears a
g in set of attributes in another relation. This is called referential integrity.
3 al integrity in the E-R model
x
integrity constraints arise frequent$. If we derive our relational
scheme by constructing tables from E-R diagrams then every relation arising
a relationship set has referential integrity constraints.
shown in Fig. 3.2, an n-ary relationship set R, relating entity sets E1 ,Ey,.....En-
i denote the primary k"y of Ei. The attributes of the relation scheme for
ip set R include K*) Kzv ...... u Kn. Eadr Ki in the scheme for R is a
key that leads to a referential integnty constraint.
F -* : -i: :.'-:
iw ::r = !::-
P- l€ fj-
create table Account =L-=
!um: - :,:::-:-- ::
ior"ign key(Branch-name) referenc es Branch
on delete cascade a' : htroducti
on uPdate cascade (
:f-,----:+j
) nilfir- -...-:i
-:::::
o Due to the on delete cascade clauses, if a delete of a tuple
in Branch results t:-4--- -:-:
he Alternative to cascading:
" on delete set null
" on delete set default
Null values in foreign key attributes complicate SQL referential integrity semantics,
and are best prevented using not null. If any attribute of a foreign key is null, the
tuple is defined to satisfy the foreign key constraint.
4) Enterprise Constraints
These are additional rules specified by the users or database administrators of a
database.
It is also possible for users to specify additional constraints that the data must
-tisfy- For example, if limit on number of staffs working at a branch is 20, then the
user must be able to specify it and expect DBMS to enforce it. In this case, it should
not be possible to add a new staff at that branch.
h
Ie SQL usage by its very nature is extremly flexible. It uses a free form syntax that
Erves the user the abilig to structure SQL statements in a way best suited to him.
)e
Each SQL request is parsed by the RDBMS before execution, to check for proper
>lrntax and to optimize the request. Unlike certain programming languages, there is no
n.
need to start SQL statements in a particular column or be finished in a single line. The
rg
same SQL request can be written in a variety of wavs.
be
re
The various advantages of SQL are :
ie
' SQL is a high level language that provides a greater degree of abstra
than procedural languages.
Database Management Systems 3-8 Relational
SQL enables the end-users and systems personnel to deal with a number
database management systems where it is available. Increased acceptance
7 availabiliff of SQL are also in its favor.
. Applications written in SQL can be easily ported across systems.
porting could be required when the underlying DBMS needs to be up
or changed.
. SQL specifies what is required and not how it should be done.
o The language while being simple and easy to learn can handle co
situations.
. A11 SQL operations are performed at a set level. One select
statement
retrieve multiple rows, one modify statement can modify multiple rows.
set at a time feature of the SQL makes it increasingly powerful than
record at a time processing techniques employed in language like COBOL.
o Character string
o Bit string
o Exact numeric
o Approximate numeric
1) Gharacter String
Character strings are written as a sequence of characters enclosed in single
The single quote character is represented within a character string by two
quotes. Some example of character strings are :
o 'Computer Engg'
o 'structured Ouery Language'
2) Bit String
A bit string is written either as a sequence of 0 s and 1s enclosed in single q
and preceded by the letter 'B' or as a sequence of hexadecimal digits enclosed
single quotes and preceded by the letter 'X' some examples are given below :
o B'1.01101t'
o B't'
o B'0'
o X'A 5'
o X'1'
t\
E
Database Management SYstems 3-9 Relational Model
3) Exact Numeric
These literals are written as a signed or unsigned decimal number possibly with a
Theprincipaldatadefinitionstatementsare:
o Create table, create view, create index
. Alter table
o Drop table, droP view, droP index
Multiplication
I Division
+ Addition
Subtraction
Example :
update Emp_Salary
set salary - salary " 1.0S ;
These are used to compare one expression with another. The comparlson operators
are given below :
ata
ind Operator Definition
Equality
(), Inequality
-r =
QL Less than
>= Greater than or equal to
<= Less than or equal to
5) Disptay the names of students who hnoe secured second class in exam.
= select student name
ftom student
where percentage BET\AIEEN 50 AITID 55 ;
Operator Definition
Examples :
2) Disptay the names of students who haoe secured higher second class in exam.
= select student name
from student
. r,,..rhere percentage >:55 and percentage < 60 ;
a\
del Database Management Systems 3-13 Relational Model
Operator Definition
UNION Returns all distinct rows from both queries
= select Name
from Permanent_Emp
Union
select Name
from Temporary_Emp ;
the order that the DBMS uses when evaluating the different
Precedence defines
qrators in the same expression. The DBMS evaluates operators with the highest
luedence first before evaluating the operators of lower precedence. Operators of
+at precedence are evaluated from the left to right.
Hg. 3.7 shows the order of precedence.
Operator Definition
Prefix for host variable
Variable separator
o Surrounds subqueries
Surrounds a literal
Surrounds a table or column alias or literal text
ll Character concatenation
NOT Reverses the result of an expression
AND True if both conditions are true
OR True if either conditions are true
UNION Returns all data from both queries
INTERSECT Returns only rows that match both queries
MINUS Returns only row that do not match both queries
2011011980 --rg
Sl[-:''=
3.1.3.1 Greate Table _+
The Tables are created using Create table command' There are
two waYS of
J.
TE TABLE
This command is used to create a new relation and the corre.qtonding sfntar is :
.l
Modern Book House mostly supplies boolcs to institutions which frequentty buy boolcs
them. Various relations used are Customer, Sales, Book Author, and Publisher. Design
schnne for the same.
Country varchar(15));
created.
Database Management SYstems 3-16 Relational Model Database Management S
1) Delete
5) The publisher table definition is as follows
SOL >create table Publisher A delete request is e
(Publisher-name v at char (25 ) primary key' :o delete all or specific
Pub add varchar(30)); attributes.
Table created. Syntax :
delete from r
2) CREATE TABLE ... AS SELECT where p
This type of create command is used to create the structure of a new table from where,
the structure of existing table. r - relation
The generalized syntax of this form is shown in below : p - predicate
Create the structure for specinl customer fro* the structure of Customer table. Delete all books from B
3.1.3.3 Relation Modification using Insert, Update, and Delete Queries where Unit-P
(select avg (U
Different operations that modify the contents of the relation are : ftom Book) ;
o Delete Jl Delete all books fron
e Insert SOL > delete from B<
' UPdaie
3-17 Relational Model
lel fbase Management SYstems
|| Delete I
delete operation is used
A delete request is expressed in same way as a query' The
derete all or specific rows from database. we
cannot delete values of particular
l
rrihutes.
Syntax :
delete ftom r
where P
where,
r - relation
P - Predicate
P(t) is true and then deletes
D delete statement first finds all tuples in r for which
fbr from r. The where crause is omitled if arl tupres tn r
are to be deleted.
want to delete tuples from
A delete corrunand operates only on one reration. If we
each relation.
rsal relations, w€ must use one delete conunand for
2) Insert rrF
To insert data into a relation, we either specify a fuple to be inserted or write a :sng update sta
tIE rt.|a
query whose result is a set of tuples to be inserted. The attribute values for inserted
tuples must be members of the attribute's domain. ,lmn'qi- tollorring re
Trl_r\-.Tlee
Consider following customer relation. - {Emp-
In above example, the values are specified in the order in which the corresponding
attributes are listed in the relation schema. SQL allows the attributes to be specified as
part of the insert statement.
Above query is rewritten as :
SOL > insert into customer (cust_no, cust_name, cust_address, cust;lh)
i i.t:r-arc slary of all
Values (05, 'pragati', 'ABC',98223989L0) ;
Example :
SOL> update Emp
SOL >insert into Customer set SalarY =
values (05, 'Pragati', 'AE|C', null); where Sala:
1 row updated.
The updated salar
del Ilatabase Management Systems 3-19 Relational Model
3) Update
Using update statement, we can change value in a tuple or all the tuples of a
relation.
1 Ram 10000
2 Jim 7000
mg
3 John 9000
AS
4 Sita 1 1000
rows updated.
$rt:
Emp_code Name Salary
1 Ram 1 1500
2 Jm 8050
3 John 1 0350
4 Sita 12650
update Employee
set SaIary : case
when SaIary < 9000 then
SaIary * 1.1.5
else Salary * L.05
end;
The general form of case statement
case
when pred L then result L
when pred 2 then result 2
CB-\ will not load the data into the column, reject the entered record and will display
e-or message to the user.
These constraints are given a constraint name and the DBA stores the constraints
$;th it's name and instructions internally along with the column itself.
mammS
I:: constraints can either be placed at the column level or at the table level.
Consider the Employees relation and the constraint that no two Employees have CREATE TABI
the same Emp-Code. This Integrity Constraint is an example of a. A key constraint is (customer cod
a statement that a certain minimal subset of the fields of a relation is a unique customer nam
identifier for a tuple. customer add:
Iicense no var(
Specifying Key Constraints in SQL-92 :
In SQL we can declare that a subset of the columns of a table constitute a key by ' 'r Foreign Key
using the UNIQUE constraint. At most one of these 'candidate' kevs can be declared Foreign key repre
to be a primary key, :using the PRIMARY KEY constraint. cl;s that the table
u::ur the foreign ke)
1) Primary Key Gonstraint :
The foreign key,,r
A primary key is one or more columns in a table used to uniquely identify each . rejects an INS
row in the table. Primary key values must not be null and must be unique across the
currently exisl
column.
A multicolumn primary key is called a composite primary key.
. rejects a DELI
o must refer a I
. rvill refer the
1) Column level primary key constraint of columns is
SOL > CREATE TABLE student
(roll_no number(s) PRIMARY KEy,
r must refer a ti
name varchar(2s) NOT NULL, . requires that t
address varchar(2s) NOT NULL, have matching
ph_no varchar(15));
Table created.
SCL> CREATE TA
2) Table level primary key constraint. (ISBN varch
SO],> CREATE TABLE studentl title varcharr
(roll_no number(S),
urit_price nr
name varchar(2s) NOT NULL,
author nam(
address varchar(2s) NOT NULL,
publisher nr
ph_no varchar(L5),
Table create
PRIMARY KEY(roll_no));
Table created.
Example
SOL> CREATE TABLE book
(ISBN varchar(L5) PRIMARY KEY,
title varchar(25), pub-year varchar( ),
unit_price number(4),
author name varchar(2S) references author,
publisher_name varchar(2S) references publisher);
Table created.
lis
3 -24 Relational Model gngema
Database Management SYstems
-- tro rlu
3.2.3 General Gonstraints :erng ValCi
Domain, primary key, and foreign k"y constraints are considered to be a address va
fundamental part of the relational data model and are given special attention
in most
ph_no varc
commercial systerns. Sometimes, however, it is necessary to specify more general
PRIMARY I
constraints. These constraints are explained below:
l-,e ,reated.
1) NULL Value Gonstraints
I Ehfining Integrity
While creating tables, if a row lacks a data value for a particular column, that
value is sa,id to be null. Columns of any data types may contain null values unless r --:-i can also def
the
--r-='--t command.
column was defined as not null rvhen the table was created"
-:s.:er follon ing e
o Setting a null value is appropriate when the actual value is unknown, or il $rdent with defin
when a value would not be meaningful'
-iO.L> CREATE T,
o A null value is nct equivalent to a value of zero. (roll_no nru
o A nuil value wjll evaluate to nulI in an-y expression' Example : null name varcl
.-
-+DD PRTMARY K
1) Column level primary key constraint SOL> ALTERTA]
SOL > CREATE TABLE student
ADD PRIM
(roll-no number(S) PRIMARY KEY,
name varchar(2s) NOT NULL, Table altered.
address varchar(2s) NOT NULL,
ph-no varchar(L5));
: Modify column mn,
(roll_no number(S),
a
name varchar(2s) NOT NULL,
ost address varchar(2s) NOT NULL,
ral ph_no varchar(15),
PRIMARY KEY(roll_no));
Table created.
the You can also define integrity constraints using the constraint clause in the ALTER
TABLE command.
Table altered.
Dept_Name Location
HR A-311
Sales A-101
Marketing A-104
Production B-101
Design A-201
nstrai
Employees(Emp_code, Emp_name, Dept)
on, it
(null, 'Sak','IT',);
with
ing Relational Data
query is a question abou( the data, and the answer consists of a new relation
ring the result. For examp\ we might want to find all employees working in
' departrnent. Such a qu6stion is written using a query language. SQL is the
popular commercial query language for a relational DBMS. Above query is
in SQL as given below:
*
Employees E
E.Dept_n€une :'Marketing';
symbol * means display all fields values of selected tuples in the result. Above
lav
*lets only the tuples where the Depart_name is 'Marketing'. This query
re vl
to the relation shown below:
y key Emp_code Emp_name Dept_name
ertion:
21678 Om Marketing
i
I
Y
Database Management Systerns 3 -28 Relational Model Database Managemenl
In addition to seiecting a subset of tuples, a query can extract a subset of the fields The row, (200I, I(
ofeach selected tuple. We can select o^ly the names of employees working in I,rhn. We can add nen
Marketing department using following query:
SELECT E.Emp_name 3.5.2 Relationship {
FROM Employees E
_ 'Marketing';
-etRbearelationsh
WHERE E.Dept_name --:rrion
of the prirnan-
The above query evaluates to the relation shown below : :escriptive attributes (
= table called R with o
{u''u''
Fcr example, consider
:ttribute Access-date. I
3"5 Logical Database Design : ER to Relational
o Customer, witl
We can represent a database that conforms to an E-R database schema by a
collection of tables. For each entity set and for each relationship set in the database, o Account, with
there is a unique table to which we can assign the name of ttre corresponding entity Thus, the Depositor
set or relationship set. Each table has multiple columns, each of which has a unique
name. Custc
Both the E-R rnodel and the relational database model are logical representation of c(
real-world enterprise. As both the models uses similar design principles, we can c(
convert an E-R design into a relational design. cc
The constraints specified in an E-R diagram, such as primary keys and cardinaliry"
constraints, are mapped to constra\ts on the tables generated from the E-R diagram.
20a2 Ram
2003 Shyam
2004 Rav
:lcis The row, (2001, Iohn) in the table Student, means the Roll_No 200I and Narne
in , ohn. We can add new rows and also delete or update existing rows.
Let A be a weak entity set with attributes 21,22,......,em.Let 'B' be the strong
entity set plus
higher-level entit
entity set on vrhich A depends. Let the primary k"y of B consist of attributes
bt,bz , bn. We rePresent the entity set A by u table called A with one column for o Account, witl
each attribute of the set.
. Saving_accou
. Checking_acc
{rt, ur,...., ar}r {br, b2,...., bn} If the generalizar
For example, consider an entity set 'Transaction' with attributes Transaction-date, of two lower-ler
Debit-amourrt, Credit-amount and Balance. It depends on entity set 'Account' with every entity in
primary k"y Account-no. Thus the Transaction table is represented by coiumns lower-level entit
Account-no, Transaction-date, Debit-amount, Credit-amount, Balance as shown in Instead, create s
l
del Database Management Systems 3-31 Relational Model
the
rute
the
uld
mn
For
rtes Fig. 3.12 E-R with generalization
lt.
1. Create a table for the higher-level entity set. For each lo-wer level entity set,
create a separate table that includes columns for each of the attributes of that
entity set plus a column for each attribute of the primary k"y of the
)ng higher-level entity set. Thus, for E-R diagram in Fig. 3.12 we have three tables :
rtes
o Account, with attributes Acc-no and Balance.
for . Saving-account, with attributes Acc-no, Interest-rate.
. Checking_account, with attributes Acc no and Overdraft amount.
2. If the generalization is disjoint and complete, that is, if no entity is a member
ate, of two lower-level entity sets directly below a higher-level entity set, and if
rith every entity in the higher-level entity set is also a member of one of the
nns lower-level entity sets. Then, do not create table for higher level entity set.
in Instead, create separate tpble for each lower-level entity sets that includes
column for each of the altributes of that entity set plus a column for each
attribute of the higher-leVel entity set. Then for E-R diagram in Fig. 7.47, we
have two tables :
from book;
operations on the vier,v are automatically translated into operations on the View created.
relations from which it is derived. Views are dynamic, that is changes made SOL> select * fron
to base relations are imrnediatelv reflected in the view.
O$ut:
J
Purpose of Views
The view mechanism is desirable for several reasons.
o It simplifies queries.
o It can be queried as a base table.
o It provides a powerful and flexible security mechanism by hiding parts of
the database from certain users.
o It pernnits users to access data in a way that is customized to their needs, so
that the same data can be s6en by different users in different .,^/ays at the
same time. 3-6.2 Selecting Dat
f:ample : Display all
SOI-> select title fr
All updates to a base relation should be immediately reflected in all views that
references the base relation. Similarly, tf a view is updated, then the underlying base where auth
relation should reflect the change. However, there are restrictions on the Vpes of
modifications that can be made through views.
The restrictions are :
. Updates are allowed through a view defined using a sirnple query involving
a single base relation and containing either the primary key or a candidate
key of the base relation"
. Updates are not allowed through views involving multiple base relations.
. Updates are not allowed through views involving aggregation or grouping
operations.
I
del Database Management Systems 3 .,33 Relational Model
Output :
DBMS Basu
DOS Sinha
of
ADBMS Basu
Unix Kapoor
to
1e
3.6.2 Selecting Data from a View
Example z Display aII the titles of books written by author 'Basu
SOL> select title from V Book
hat
rase where author name : 'Basu':
;of
Title
18 DBMS
te ADBMS
1g
Database Management Systems 3-34 Relational Model
Database Managem
Example :
Drop customer
SO.L> ALTER
ADD custotner phone number nnd fax number in the customer relation. DROP (
SOL> ALTER TABLE Customer
ADD (Cust_ph_no varchar( L5 ),
Cust fa:< no varchar(L5));
Table created.
l
4
This form is used to change the width as well as data tFpe of existing relations.
Tlre generalized syntax of this form is shown below.
Example :
Modifu the data type of the publication year as numeric data type.
SOL> ALTER TABLE Book
MODIFY(Pub-year number(4) ) ;
Table created.
1) DROP TABLE
This conunand is used to delete a table. The generalized syntax of this form is
given below :
DROP TABLE relation-name
i) Procedural languages
In procedural language, the user instructs the system to perform a seqrlence of
operations on the database to compute the desired result.
Relational Algebra
The relational algebra is a procedural query language. It consists of a set of
operations that take one or two operations as input and produce a new relation as
their result.
(3 - 37)
Database Management SYstems 3-38 Relational Algebra Databi
o E1v E2 wl
. Et-Ez a
. Etx Ez
. o p(E), where P is a predicate on attributes in E1.
r fI s(4), where S is a list consisting of some of the attributes in E1.
o px (Et), where xis the new name for the result of E1.
The relational algebraic operations are divided into two grouPs : C
i) The first group includes the set operations. Since each relation is defined as a
set of tuples, the set operations are applicable to the relational data model. Set
operations include the following operations :
o Union
o Intersection
. Set difference
o Cartesian product FEr
ii) The second group of relational algebraic operations is developed specially for 1
/ t Rename
o Ioin
e Division
3.8.1.1 Selection
o The select operation selects tupies that satis9 a given predicate.
r The select operation is represented as follows :
where,
. < attribute name > is the name of an attribute (column) of the relation R.
3) Select the tuples for aII books whose pubtishing year is 2000 or price is greater than
300.
(Book)
=o1ye., : zo0o) OR (Price > 300)
The output of the above query is shown below :
4) Select the tuples for all books whose publishing yenr is 2000 and price is greater than
300.
3.8.1.2 Proiection
The project operation selects certain columns from a table while discarding others.
It removes any duplicate tuples from the result relation.
The project operation is represented as follows : '
lI ."ttributelistt (R)
The s;mbol lI (pi) is used to denote the project operation and the attribute list is a
list of attributes from the attributes of the relation R. The result of the project
operation has only the attributes specified in the attribute list and in the same order as
they appear in the list. Hence the degree (number of columns) of the result is equal to
the number of attributes specified in the attribute list.
Title Author
DBMS Korth
Compiler Galwin
OOMD Rambaugh
PPL Sabista
Example :
Title
Compiler
OOMD
PPL
Depositor
Johnson Mumbai
Jones Solapur
Lindsay Nashik
2l
Smith Pune
Turner Mumbai
bot
Borrower
Curry Pune
Hayes Pune
Jackson Solapur
Jones Solapur
Smith Pune
Williams Kolhapur
Example : Find the names of all bank customers who have an account or loan or
both.
The result of union is :
Depositor v Borrower
Customer name City
Hayes Pune
Johnson Mumbai )
Jones Solapur
I
Lindsay Nashik
Smith Pune
Turner Mumbai
Adams Mumbai
Curry Pune
Jackson Solapur I
i
Williams Kolhapur
Depositor n Borrower
Gustome name City
Hayes Pune
Jones Solapur
Smith Pune
Depositor - Borrower
Johnson Mumbai
Lindsay Nashik
Turner Mumbai
4) Gartesian Product
The cartesian product is also known as CROSS PRODUCT or CROSS JOINS. It is
denoted by '*' .The cartesian product of two relations A and B is denoted by A x B.
The result of cartesian product of two relations which have X and Y columns is a
relation that has X + Y columns. The resulting relation will have one tuple or each
combination of tuples from each participating relation. Hence if the relations have n
*
and m tuples respectively, then the CARTESIAN PRODUCT will have n m tuples.
Consider following two relations : Publisher-Info and Book-Info.
Publisher lnfo
Publisher code Name
P0001 McGraw-Hill
P0002 PHI Pi
P0003 Pearson
Book lnfo
Book lD Title
B0001 DBMS
80002 Compiler
Publisher_lnfo x Book_lnfo
Fig. 3.22 Gartesian product of relations Publisher Info and Book Info
3.8.3 Renaming
In relational algebra, you can rename either the relation or the attributes or both.
The general rename operation can take any of the following forms :
For example consider the Book relation with attributes Title, Author, Year and
Price. The rename operator is used on Book relation as follou s :
3.8,4 Joins
The join operation is one of the most useful operations in relational algebra and is
the most commonly used way to combine information from two or more relations.
Different join operators used in relational algebra are explained below.
Database Management Systems 3-46 Relational Algebra Database Manag
In this form, the join operation accepts a join condition c and a pair of relation It is special
instances as argurnents, and refurns a relation instance. The join condition is identical solely of equali
to a selection condition in form. The operation is defined a cross-product followed by a operator (n).
selection as given below:
Example :
R><.S = o.(RxS)
Car>{
where c is the condition. Car D(
CarPri
Car
GarModel GarPrice
CarA 20'000
3) Natural Join
CarB 30'000 The natural
and a cartesian
CarC 50'000
natural-join oP
Fig. 3.23 Relation 'Car' selection forcin;
finally removes
Boat The differ
involving cartel
BoatModel GarPrice
product.
Boatl 10'000
Car A Boat
2) Equijoin : i
It is special of the condition (theta ) ioi^ where the join condition consists
case
solely of equalities between two fields in R and S connected by the logical AND
operator (n).
Example :
Car X Boat
CnrPrice - BoatPrice
3) Natural Join i
The natural-join is a binary operation that allows us to combine certain selectiont I
and a cartesian product into one operation. It is denoted by the 'ioin' symbol D( . The
natural-join operation forms a cartesian product of its two arguments, performs a
selection forcing equality on those attributes that appear in both relation schemes and
finally removes duplicate attributes.
The difference between natural-join and cartesian product is : The query
involving cartesian product includes a selection operation on the result of the cartesian
product.
Example :
Employee Salary
To display the names of all employees with salary, we need to combine the
Employee and Salary relations using cartesian product as follows -
=llemp-n€rme, salary
(oemployee.emp-code : salary. emp-code (Employee x Salary))
Thus, the query using natural-join is simpler than cartesian product query. The natural
joi. operation considers only those pairs of tuples that have the same value on
Emp_code attributes in both relations.
The output of query is :
Emp_name Salary
Hari 2000
Om 5000
Smith 7000
Jay 10000
3.8.5 Division
The division operation is denoted by '*'. It is suited to queries that include the
phrase 'for alI'.
i) Account
Account no Branch name Balance
ii) Depositor
Customer name Account_no
- Hayes- A-1g2
Johnson A-1.o1
Johnson A-201
Jones A-217
Lindsay A-222
Smith A-215
Turner A-305
Branch
.
Fig. 3.X, The Branch Relation
Now, suppose that we wish to find all customers who have an account at all the
located in Brookllm.
1 : We can obtain all branches in Brooklyn by the expression.
Branch_name
Brighton
Downtown
2 : We can find all (Customer-n€une, Branch-name) pairs for which the customer
an account at a branch bY writting.
Database Management Systems 3-50 Relational Algebra
Database ilam
t2 = [ Customer_name,Branch_na*. (Depositor D( Account)
aqcrY 0 n
Fig. 3.31 shows the result of above expression.
Thb SEy
Gustomer name Branch_name frslrr.
Hayes Perryridge
Johnson Downtown Query 5) E
Johnson Brighton This qtroy
Jones Brighton p(Ten
Lindsay Redwood
fi snam
Smith Mianus
Turner Round Hill Query 5) I
Fig. 3.31 Result of ltrr"tomer_name, Branch_nam" (Depositor x Account ) This query
Now, we need to find customers who appear in rz with every branch narne ir rt. P(Ten
The operation that provides exactly those customers is the divide operation.
P snu
Thus, the query is :
Query 7)
I customer_name, Bra'ch_na*" (Depositor D{ Account)
This queq
* H Br"rr"h-name (o grancn-city = "Brookllm" (Brarlch) )
The restrlt of the operation is a relation that contain one attribute Customer narne P(Re
with tuple flohnson). PE(
5+'
3.8.6 Examples of Relational Algebra Queries
fi snat
More examples of relational algebra queries are given in this section.
Consider following rel4tions: Query 8)
1) Sailors(sid: integer, sname: string, rating: integer, age: real) This quer
2) Boa|s(Ad;Algg, bname: string, color: string) fr sia
3) Reserves ) Tc sid
Query D Find the names of sailors who haoe reseraed bont 103.
Query 9)
This qury can be written as follows :
This quer
fr sname (6 nia= p3Reserves) X Sailors)
n(Tt
Query 2) Find the names of sailors who haae reseraed a red boat. frs'u
This query can be written as
follows : QuerY 1(
fi sname((o Reserve$( Sailors) This que
color=,rro,Boats)X
P(Tt
Query 3l Find the colors of boats reseraed by Lubber.
fism
This query can be written as follows
fr color ((o ,nr^r= ,7u66ur,Sailors)AReserves x Boats)
l
Database Management Systems 3-51 Relational Algebra
Query 4) Find the names of sailors who haae reseraed at least one boat.
This query can be written as follows :
fi sname (Sailorsx Reserves)
Query 5l Find the names of sailors who haae reseraed a red or a green boat.
Query 6) Find the names of sailors who hnae reseraed a red and a green boat.
Query 7) Find the names of sailors who haae reseraed at least two boats.
This query can be written as follows :
p (Reservations, fi sid, snamr, 61g
(Sailorsx Reserves))
Query 8l Find the sids of sailors with age ooer 20 who haae not reseraed a red boat.
This query can be written as follows :
n 116
(o age>zo Sailors)
Query 9l Find the names of sailors who haae reseraed all boats.
Query 701 Find the names of sailors utho haae reseraed all boats called lnterlake.
/
This query can be written as follows :
p(Tempside, (n sid, 6iT,Reserves) / (n nia6
6niilne=, Interrake,Boats)))
fr sname (Tempsides x Sailors)
Database Management Systems 3-52 Relational Algebra Database Manage
{/tP(4}
Database Management Systems 3-53 Relational Algebra
that is, it is the set of all tuples f such that predicate P is true for t.
In tuple relational calculus -
tlA] - denotes the value of tuple on athibute A,
t e r - denotes tuple f in relation r.
Consider following relations
1) Loan
Loan no Branch name Amount
L-11 Round Hill 900
L-14 Downtown 1500
L-1 5 Perryridge 1 500
L-1 6 Perryridge 1 300
L-17 Downtown 1 000
L-23 Redwood 2000
L-93 Mianus 500
2) Depositor
3) Borrower
Curry L-93
Jackson L-1 5
Jones L-17
Smith L-11
Smith L-23
Williams t-17
This exprss
:2\-e an account
1) Find all tuples fro* the Depositor relntion.
customers
= {t lt c Depositor} =-os€
=om the bank.
2) Find the Loan_no, Branch_name and Amount for loans of oaer $ 1200.
F Formal Elefil
=+ {tlt e Loan n t [Amount] > I2OOI
A tuple'relal
Suppose we want only Loan_no attribute, rather than all attributes of the
Loan relation. To express this request, we need to construct 'there exist' from {
mathematical logic. The notation" where,
Ir €'(o(4) F
means "there exists a tuple t in relation r such that predicate O (4 is true".
A tuple vari
3) Find loan number of each loan with loan amount greater than 1,200.
there exists, V :
Thus in,
= {t lf se Loan(t [Loan_no] -s[Loan_no] ns[Amountl > 1200)]
In English, we read the preceding expression as "The set of fuples f such f€ Loa
that there exists a tuple s in relation Loan for which the values of f and s for f-isa
the Loan_no attribute are equal, and the value of amount attribute is greater s-isa
than $ 1200.
5) Find the names of aII customers who haae a loan fro* the Perryridge branch. t
is defin
= {tl I s e Borrower(t[Customer_name] :s[Customer namel operatol
nl u e Loan (u [Loan-no] : s [Loan-nol n u [Branch-name] : "PerrYridge"))] whose t
8) Find all customers who haoe an account at the bnnk but do not haae a lonn fro* the bank.
. If a(t)
+ {t ll u e Depositor(t[Customer_namel : u[Customer namel n then f I
This expression uses the I u e Depositor (...) clause to require that the customer
have an account at the bank, and it uses the -., f s e Borrowe. (. clause to eliminate
)
those customers who apPear in some tuple of the Borrower relation as having a loan
from the bank.
Thus in,
f e Loan n I se Customer [t [Branch_name] = s [Branch_name]]
f - is a free variable
s - is a bound variable
A tuple relational formula is built up out of atoms. An atom has one of the
following forms :
7) Find sailors who haae reseraed all red boats. loan amout
1) Find the loan number, branch name and amount loans of oaer $
for 1200.
5) Find the names of all customers who haae, an account at the perryridge branch.
+{< c> | I d1c,a> € Depositor n Il b,n (< a,b,n> e Account A b = "perryridge,,)}
V
Database Management Systems 3-58 Relational Algebra Database Manac
6) Find the names of all customers who haue a loan, an account, or both at Perryridge brnnch.
Consider fol
+ { <c> | f 1(<c,I> e Borrower
Sailors(s:
n 1 b,a(< /,b,a >€ loan xb = " Perryridge") Boats(bic
v I a (<c,a> eDepositor Reserves
n 1 b, n (< a, b, n> e account n b - "Perryridge"))) 7 t Find the name
{ (1, N, T,
3.9.3 Expressive Power of Algebra and Calculus
2t Find the nnme
{(N) l= L
A tuple relational calculus expression may generate an infinite relation. nl Ir, Br,
Consider the expression, j, Find the name
{rl-.' (re Loan) } {(N) llL
means, tuples that are not in Loan. There are infinite tuples that are not in Loan n1I, Br, )
relation. Hence, such tuples of expressions should not be allowed. !, Find the name
Thus, to restrict the tuple relational calculus, the concept of the domain of a tuple {(N) l= L
relational formuld, P, is introduced. The domain of P denoted by, dom (P) - is the set 18r7, Br,
of all values referenced by P. They include values mentioned in P itself, as well as j' Find the name
values that appear in a tuple of a relation mentioned in P. Thus, the domain of P is
{(N) lf I,
the set of all values that appear explicitly in P or that appear in one or more relations vB, Biv (
whose names appear in P. (1 (Ir, Br,
For example, j, Find sailors w
dom (te Loan nt > 1200)
[amount] {(I' N' T'
is the set containing 1200 as well as the set of all values appearing in Loan. Also (C='red
dom (-- (t e Loan)) is the set of all values appeari.g ir Loan, since the Loan relation is
mentioned in expression. Therefore, this expression is not safe. University G
The expression { t I P(4} is safe if all values that appear in the result are values
from dom (P).
Q.1 Define u,
Ans. : Refer se
Expressive Power of Languages :
Q.2 Whnt are
The tuple relational calculus restricted to safe expressions is equivalent to the basic
Ans. : Refer -
relational algebra operations (with the operators \), -, X, o and p without extended
relational operators). Thus, for every relational algebra expression using only the basic Q.3 Consider
operation there is an equivalent expression in the fuple relational calculus and for PROIEC
every tuple relational calculus expression, there is equivalent relational algebra EMPLO'
expression. AS5/G\
Write tht
i) Find E
Database Management Systems 3-59 Relational Algebra
1) Find the names of sailors who harse reseraed at least two boats.
{(N) lf I, T, A N,(Q,
T, A)e Sailors x
I Br7, Br2, D7, D2, ((1, Br1, DI)e Resenzes n (1, Br2, D2)e Resenres n Br7+ nr2 )]
5) Find the names of snilors who haae reseraed aII boats.
{(V,) | f I, T, A ((1, N, T, A)e Sailors n
VB, BN, C (-', ((8, BN, C)e Boats) v
(1 Qr, Br, D)e Resenzes (I= Ir n Br= B))))\
Q.3 Consider the following schema giaen. The primary keys are underlined.
Cf @rclqetpurn, P r oj e c t _N ame, Chief_Ar chit e c t )
P RO I E