You are on page 1of 59

Unit-III

?art I -, Relational Model

al htroduction to Relational Model

ll-l Overview of Relational Model


fhe relational model was introduced by Dr. E.F. Codd in 1970 and has evolved
fu flren, through a series of writings. The relation at model represents data in the
h of two dimensional tables. Each table represents some real world entity, or thing.
aganization of data into relational tables is known as the logical view of the
&base.
A basic und,erstanding of the relational model is necessary to effectively use
rfinal database software such as Oracle, Microsoft SQL Server, Sybase, which are I

lH on the relational model. I

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

1) Relational database management : A relational database management system @ lr r*rcsf


uses only its relational capabilities to manage the inJormation in its database. MUE@ T :

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

12) Database distribution : The database language implemented


by the RDBMS
supports the ability to distribute the database without requiring
changes to be
made to application programs.
tem 13) Non subversion : If the RDBMS supports facilities that allow application
). programs to operate on the tables a row at a time, an application
program
eis using this type of database access is prevented from by passing entity
integrity
ake or referential integrity constraints that are defined for ih" dutubase. ;

11.1.1 Relations I

Relation : A relation is defined as a set of types that have same


attributes. A
relation consists of a relation schema and relation instance.
Relation Schema: The schema specifies the relation's name, the name
for of each I
field (or column, or attribute) and the domain of each field. A domain
:be is t
referred by the domain name and set of associated values.
tbe
Example : Consider following relation schema :
Employee (Emp-code : string, Emp-rame : string, Dept : string)
is
the Here, the field Emp-code has a domain named string, and the
set of values
lto associatedwith domain string is the set of all character strings.
Relation Instance .' An instance of a relation is a set of tuples (records)
in
which each tuple has the same number of fields as the relation schema.
An instance E10f 'Employee' reration is shown in Fig. 3.1.
Fields (Columns, attributes)

Emp_code Emp_name Dept_name Field names


01234 John HR

12567 Smith Sales


Cardinality
Tuples 21678 Om Marketing
(Rows, Records )
12456 Sa Production

12457 Jay Design

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,

3.1.1.2 Relational Integrity Glrin -t of attri


Integrity constraints guard against accidental damage to the database, by ensuring
that authortzed changes to the database do not result in a loss of data consistency.
Referential ir
Examples of integrity constraints are: &base scheme
. An account balance cannot be null. fui a relationshi

. No two students can have same roll no. As shown in


I"et Ki denote t
In general, an integrity constraint can be any arbitrary predicate pertaining to the
database. However, arbitrary predicate can be costly to test. Hence, the most database -lationship set l
frreign key that I
systems allow one to specify integrity constraint that can be tested with minimal
overhead.

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.

create domain Dollars numeric(I2, 2)


create domain Pounds numeric ('/.,2,2)
Oatabase Management Systems 3-5 Relational ft|odel

. We eannot assign or compare a value of :qrpe Dollars to a value of tFp"


Pounds.
Elowever; we can convert type as below:
(cast r.A * Pounds)
o (Shoufd abo multiply by the dollar-to-powrd conversion-rate)

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.

Fig. 3.2 An n-ary relationshiP set


T
3-6 Relational Model Database llanage
Database Management SYstems

Another source of referential integrity constrarnts are wea\


en\r\ >e\>'\\s'rs\s\rss
key of the entity set on whic-
scheme for a weak entity set must include the primary
a foreign ko
it depends. Thus, the reration scheme for each weak entity set includes
that leads to a referential integrity constraint.

are defined as part of the - €=-


Using SQL, primary key, candidate key, and foreign key ':G't
create table statement as given below : ':G,(
Example : 1t,.-_'
"'@ : r--, -

create table Deposit (Branch-name char(L5)' dI. Ele :D: l--=-.


Acc no char(L0), l@ _r- 1:--Ei l
Cust name char (20) not nuII,
Balance integer, | =-rnrs€ Cbf
primarY keY (Acc-no, Cust-name),
-n=t 1-: ::
foreign key (Branch-name) references Branch'
@Cfrr#t
foreign key (Cust-name) references Customer) ;

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--- -:-:

in referential-integrity constraint violation, the delete-cascades- to the


-:
unit-,-:-i --L8 0i
Account relation, dereting the tupre that refers to the branch
that was deleted.
-T - :--:-e u-i1n
. Cascading updates are similar' ? Characteristi
. If there is a chain of foreign-key dependencies across multiple relations, with
update at one il- -;--ge t'
on delete cascad.e specified for each dependerlcy, a deletion or
ry= =e u--r tl
end of the chain can ProPagate across the entire chain' -;.-- {L rsque
. If a cascading update to delete causes a constraint violation that cannot be :;:-: !-
--i :C t-p
the transaction'
handled by u further cascading operation, the system aborts :r--: :-- s--ai SQi
As a result, all the changes caused by the transaction and its cascading i6.€ {L requc
actions are undone.
. Referential integrity is only checked at the end of a transaction.
Intermediate ' Advantages

steps are allowed to violate referential integrity provided


later steps remove -:-e -'-arlo''ri i

the violation. otherwise it would be impossible to create some database o SQLL<a


states. than pro
q Database Management Systems 3 -7 Relational Model
on Example:
ch
ey Insert two tuples whose foreign keys point to each other :
# Example: spouse attribute of relation
Marriedperson (N ame, Ad dress, Spouse)

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.

3.1.2 Introduction to SQL - 92


Structured Query Language (SQL) is the standard command set used to
IS
communicate with the relational database management systems. All tasks related to
re
relational data management creating tables, querying the database for information,
t.
modifying the data in the database, deleting them, granting access to users and so on
can be done using SQL.

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.

3.1.2.1 SQL Data Types and Literals


Thete are four kinds of literal values supported in SQL. They are :

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

decimal point. Examples of exact numeric literals are given below :


.9
.90
o 90.00
. 0.9
o * 99.99
o - 99.99
rl) Approximate Numeric
Approximate numeric literals are written as exact numeric literals followed by the
hter 'E', followed by u signed or unsigned integer. Some example are
o 5E5
o 55.5E5
o* 55E-5
o 0.55E
o - 5.55E-9

11.2.2 DDL, DML


SeL provides set of conunands for a variety of tasks including the following :
o Querying data
. Updating, inserting and deleting data I
o Creating, modifying and deleting database objects
o Controlling access to the database
. Providi^g for data integrity and consistency' I
For example, using SQL statements you can create tables, modify them, delete the
tables, query the data in the tables, insert data into the tables, modify and
delete the
data, decide who can see the data and so on'
The SeL statement is a set of instructions to the RDBMS to perform an action.
tes
in
SQL statements are divided into the following categories :
o Data Definition Language (DDL)
o Data Manipulation Language (DML)
r Data Query Language (DQL)
o Data Control Language (DCL)

l) Data Definition Language (DDL)


Data definition language is used to create, alter and delete database objects.
The commands used are create, alter and drop'
3-10 Relational Modcl
Database Management SYstems

Theprincipaldatadefinitionstatementsare:
o Create table, create view, create index
. Alter table
o Drop table, droP view, droP index

2) Data Manipulation Language (DML)


insert, modify and delete the data
Data manipulation ranguage corrunands ret users
statements insert, update and
in the database. sel. provides three data manipulation
delete.

3) Data Query Language (DQL)


This sQL statement
This is one of the most commonry used sel statements.
enabres the users to query one or more tables
to get the information th"y want' sQL
has only one d.ata query statement'select''

4) Data Control Language (DGL)


The data contror language consists of commands
that control the user access to the
database objects. various DcL cornmands are
: Commit, Rollback, save point, Grant,
Revoke.

3.1.2.3 SQL OPerators


such as addition'
operators and conditions are used to perform operations
subtraction or comparison on the data items in
an sQL statement'

Different Vpes of SQL operators are :

add, subtract, multiply, divide


Arithmetic operators are used in sQL expressions to
is a number value'
and negate data values. The result of this expression
Unary oPerators (B)

+. - | Denotes a positive or negative expression

Binary oPerator (B)

Multiplication

I Division

+ Addition

Subtraction

Fig. 3.3 Arithmetic oPerators


a\
lel Database Management Systems 3-11 Relational Model
I

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 =

ent Greater than

QL Less than
>= Greater than or equal to
<= Less than or equal to

the N Equal to any member of set

rnt, NOT IN Not equal to any member of set

ls NULL Test for nulls

ls NOT NULL Test for anything other than nulls

LIKE Returns true when the first expression


matches the pattern of the second expression

ALL Compares a value to every value in a list

ANY. SOME Compares a value to each value in a list

EXISTS True if subquery returns at least one row


'ide
BETWEEN x and y >=xand<=y

Fig. 3.4 Comparison operators


hmples :

Lt c,et the name of students who haae secured first class.


= select student name
from student
where percentage >: 60 and percentage < 6T ;
Database Management SYstems 3-12 Relational Model

2) Get the out of state students name


= select student name
u
from student
where state < > 'Maharashtra' ;

3) Get the names of students lioing in 'Pune'.


=+ select student name
from student
where citY = 'Pune' ;

4) Display the names of students with no contact phone number.


+ select student n€rme
from student
where Ph No is NULL ;

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 ;

A logical operator is used to produce a single result from combining the


separate conditions. Following figure shows logical operators and their definitions.

Operator Definition

AND Returns true if both component conditions


are true; otherwise returns false.
OR Returns true if either component condition is
true; otherwise returns false.
NOT Returns true if the condition is false;
otherwise returns false.

Fig. 3.5 Logical operators

Examples :

1) Display the names of students liaing in Pune and Bombay.


= select student name
ftom student
where city - 'Pune' or city = 'Bombay' ;

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

Set operators combine the results of two separate queries into


Following table shows different set operators with definition.

Operator Definition
UNION Returns all distinct rows from both queries

INTERSECT Returns common rows selected by both


quenes

MINUS Returns all distinct rows that are in the first


query, but not in second one.

Fig. 3.6 Set operators


Eamples :

Consider following fwo relations :

Permanent_Emp {Emp_Code, Name, Salary}

Temporary_emp : {Emp_Code, Name, Daily_wages}


g DLsplay name of nll employees.

= 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

o Overrides the normal operator precedence


3 -14 Relational Model tr
Database Management SYstems
- :)PFITE- 'tr

+,- Unary operators


I Multiplication and division
+ Addition and subtraction

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

Fig. 3.7 OPerator Percedence

3.1.3 Creating and Modifying Relations (Table) using SQL-92


The foundation of every Relational Database Management system
is a database
tables, which store the
object called table. Every database consists of one or more
name and consists of
database,s d.ata/rnformation. Each table has its own unique
d !F

columns and rows. -Tr* rE-.t5


own unique names :: .-
The database table columns (called also table fields) have their =-1-
the data types, the :-
and have a pre-defined data types. while table columns describe
table rows contain the actual data for the columns. -.1-
a

data' The first


Here is an example of a simple database table, containing customers
remaining rows contains
row, listed in bold, contains the names of the table columns,
actual data for the columns'
-111 l':.:*r
Ff' >==
]S
T
0410511974
_=
05101t1978 9822041236 a-

2011011980 --rg

Table 3.1 Customer -rls = -+t

Sl[-:''=
3.1.3.1 Greate Table _+
The Tables are created using Create table command' There are
two waYS of
J.

creating tables in SQL. TheY are explained below :


:tt-iF
tthragement Systems 3 ,15

TE TABLE
This command is used to create a new relation and the corre.qtonding sfntar is :

CREATE TABLE relation name


(fietdl data tlpe (size), field2 data t]tpe (size),..., fieldn data tlrye (size));
Fig. 3.8 Syntax of CREATE TABLE

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

customer table definition is as'follows :

)create table Customer


(Cust_no varchar(4) priuiary key,
Cust_name varchar(2S ) ; Cust-add varctrar(30),,
Custph varohar(15));
created.

sales table definition is as follows :

)create table Sales


(Cust_no varchar(4), ISBN varchar(lS),
Oty nrlmber(3),
primary key(Cust_no, ISBN)) ;
created.

book table definition is as follows :

>create table book


(ISBN varchar(lS) primary key,
Title varchar(2S), Pub_year varchar(4),
Unitjrice nurnber(4),
Author name varchar(25));
.r"ur"a.

thor table definition is as follows :

''cre- -teFblg Author


'_traffre' varchar(2S) primary key,

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

llre delete statement fu


CREATE TABLE relation name 1.
iem from r. The where
(fieldL, field2, ...., fieldn)
A delete command
AS SELECT fieldl, field2, ...., fieldn
relations, we mu
FROM relation name 2; =r-eral
Examples :

Create the structure for specinl customer fro* the structure of Customer table. Delete all books from B

The required command is shown below. SOL > delete from Bo


SOL> create table Special-customer where Pub_Ye
(Cust-no, Cust-name, Cust-add)
Delete aII books from B
as select Cust-no, Cust-name, Cust- add
SOL > delete from Bo
from Customer; .1r

Table created. where Pub-Ye

Delete nII books of autl,


3.1.3.2 Rename Table
you can rename a table provided you are the owner of the table. The general SOL > delete from Bc
syntax is : where Author
(select Authot
RENAME old table name TO new table name ;
from Author
where Countr
SOL> RENAME Test TO Test info; lt Delete all books haaing
Table renamed.
SOL > delete from Bc

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

Book relation where pubtishing year is less thnn 1997 '


I Delete all books fro*
SOL > delete ftom Book
where Pub-Year < 1997 ;

relation where publishing year is between 1997 to


1-999'
D Derete au books from Book

SOL > delete from Book


where Pub-year between L997 and 1999'
of authors liaing in country 'l-[..K.', f'o* Book relation
JDelete atl books

SOL > delete from Book


where Author-name in
(select Author-name
ftom Author
where Country = 'U'K'');
Delete all boolcs haoing price less than aag price of books.

SOL > delete ftom Book


where Unit-Price <
EE (select avg (UnitSrice)
from Book) ;

Delete all books from Book relation'


SOL > delete ftom Book ;
Database Management Systems 3-18 Relational Model

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-

Customel - {Cust_no, Cust_name, Cust_add, Cust_ph} to- = records of err


YT> -Iect*fron
Example z Insert a new customer record with customer no. fls 05, customer_Name as
'Pragati', Address - 'ABC' and ph. no. as 9822398910.
SOL >insert into Customer
values (05, 'Pragati', 'ABC' ,9822398910) ;

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

SOI-> update EmF


set SalarY =
Consider two relations :
. Student = {Roll_No, Name, Flag} ::rrrs updated.
. Defaulter_student = {Roll_No, Name} The updated salar
SOL> select * fron
Suppose we want to insert tuples from Sfudent relation to Defaulter student where
flag is 'D'. Fut:
The query for above statement is :

SOL > insert into Defaulter student


select RoIl no, Name
from Student
where flag - 'D';
It is also possible to assign values only to particular attributes while inserting a
tuple. l*-ease snlary of em

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.

Consider following relation :


Employe. - {Emp_code, Name, Salary} ;

\o. of records of employee relation are:


SOL> select * from Employee;

Emp_code Name Salary

1 Ram 10000

2 Jim 7000
mg
3 John 9000
AS
4 Sita 1 1000

!1 htnease salary of all employees W 15 %.

SOL > update Employee


set Salary - Salary * 1.15;

rows updated.

The updated salary values are:


SOL> select * from Employee;

$rt:
Emp_code Name Salary
1 Ram 1 1500
2 Jm 8050
3 John 1 0350
4 Sita 12650

! fuense salary of employees who earn less than 9,000 by 15 %.


SL> update Employee
set Salary : Salary " 1.15
where Salary < 9000;
I row updated.
Ttre updated salary values are:
Database Management Systems 3 -20 Relational Model Ease Managenr

SOL> Select * from Employee; update Emp


set Salary -
Emp_code Name Salary when Sala
Salary
1 Ram 1 0000
else Sala:
2 Jm 8050
end;
3 John 9000 3e general form o
Sita 11000 case
4
when pred
3) Increase sa"ary of employees by 1-5 % who earn less than the aaerage salary of employees. when prd

SOL > update Employee


when prd
*
- Salary 1.15
set SaIary end el,se res
where Salary < (select avg(Salary)
The operation t
ftom Employee);
fto: Ls satisfied ; if
2 rows updated.
The updated salary values are: 12 Integrity Cor
SOL> select * from Employee;
il*ides the columr
Emp_code Name Salary ;a*sed to the DBA
1 Ram 1 0000 These data con
fiedata being loa,
2 Jm 8050
DBA will not load
3 John 10350 {ror message to th
4 Sita 1 1000 These constrain
rith it's name and
4) Increase salary of employees by 15 % who earn less than 9000 and for
employees giae 5 "/" salary raise. The constraints can
For above example, we require two update statements :
1) Column level co
i) update Employee
set SaIary - Salary " 1.15 If the constrair
where SaIary < 9000 .-olumn level const
' ,, constraint spans ac
ii) update employee
2) Table level cons
set Salary - Salary " 1.05
whereSalary>-9000; , If the data col
contents of anothe
SQL provides a case construct, which we can use to perform both the updates with a
constraints.
single update statement.
Database Ma nagement SYstems 3 -21 Relational Model

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

when pred n then resultn


end else result
The operation returns result i ; where i is the first of pred 1, pred 2, ...., pred
fut is satisfied ; if none of the predicate is satisfied the operation returns result 0.
3.2 Integrity Gonstraints over Relations
hides the colurrrn name, datatype and length, there is other parameters, that can be
;assed to the DBA at cell creation time.
These data constraints are checked by DBA when data is assigned to columns' If
.+Frp data being loaded fails any of the data constraint checks fired by the DBA, the

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.

f) Golumn level constraints


are defined along with the column definition, it is called a
If the constraints
cc{umn level constraint. Column level constraint can be applied to any column. If the
cnstraint spans across multiple columns, the user has to use table level constraint.

! Table level constraint


U the data constraints 'attached to a specific column in a table references the
crr'-tents of another column in the table then the user will have to use table level
; with a
crrr-straints.
Database Management Systems 3 -22 Relational Model hrhass Managemen

3.2.1 Key Gonstraints , Example :

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.

2) Unique Key Constraint


Unique key is used to ensure that the information in the column for each record is
unique, as with license number. A table may have many unique keys.
Database Management Systems 3 -23 Relational Model

CREATE TABLE sPecial_customer


(customer_code number(S) PRIMARY KEY,
customer name varchar(2s) NOT MJLL,
customer address varchar(3O) NOT NULL,
license no varchar(1s) constraint uk_ license_no UNIOUE);

?22 Foreign Key Gonstraints


Foreign key represents relationship between tables. The existence of a foreign key
inplies that the table with the foreign key is related to the primary key table from
rlrich the foreign key is derived.
The foreign key / references constraint
rejects an INSERT or UPDATE of a value, if a corresponding value does not
currently exist in the primary key table.
rejects a DELETE, if it would invalidate a REFERENCES constraint.

must refer a PRIMARY KEY or UNIQUE column in primary key table.


will refer the PRIMARY KEY of the primary key table if no column or group
of columns is specified in the constraint.
must refer a table, not a view or cluster.
requires that the FOREIGN KEY column(s) and the CONSTRAINT column(s)
have matching data types.

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

multiplied by L0 is null. a Test with definitio


. When a column name is defined as not null, then that column becomes a SCtr> CREATE T.,
mandatory coitrmn. It irnplies that the user is forced to enter data into that (roll_no nur
colurnn. subject_ID
marks num
2) Detault Value Constraints
- Subject_info with
A primary key is or,e or more columns in a table used to uniquely identify each
SOL> CREATE T.,
rr:w in the table. primary key values must not be null and must be unique across the (subject_ID
colurnn.
subject_na
A multicolumn primary key is called a composite primnry key '
3e following examp

.-
-+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,

SO.L> ALTER TA]


-==Tabfe created.
- MODIFY (n
2) Table level primarv key constraint'
SOL> CREATE TABI.E studentl
lel IHbase Management Systems 3 -25 Relational Model

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

hat 3! Defining Integrity Constraints in the ALTER TABLE Gommand

the You can also define integrity constraints using the constraint clause in the ALTER
TABLE command.

Consider following existing tables :

if Student with definition :


SOL > CREATE TABLE student
(roll_no number(3),
ill name varchar(2S));

-l Test with definition :


a SOL > CREATE TA,BLE test
Lat
(roll_no number(3),
subject_ID number(2),
marks number(2));

-) Subject_info with definition :


SOL> CREATE TABLE subject_info
(subject_ID numbe{2) PRIMARY KEY,
subject_name varchar( L 5)) ;

fhe following examples show the definitions of several integrity constraints.

l) ADD PRIMARY KEY constraints on column roII no in student table.


SOI-> ALTER TABLE student
ADD PRIMARY i(EY(roll_no) ;

Table altered.

2) Modifu column marks io include NOT NULL constraint.


SOL> ALTER TABLE test
nrOOrpVGlXlrrurnJcer( 3 ) NOT NULL );
Dffibase Managern
Database Management SYstems 3 -26 Relational Model
This update ric
r:th Emp_code 7E
you can drop an integrity constraint if the rule that it enforces is no longer true or
The impact of
if the constraint is no longer needed. Drop the constraint using the ALTER TABLE
command with the DROP clause.
=s to rectifu a for
- --n-.id er f oll or+'in g
The follo'wing examples illustrate the dropping of the integrity constraints.

1) Drop the primary key of student table.


SOL> ALTER TABLE student
DROP PRIMARY KEY;
Table altered.

2) Drop unique key constraint on column license-no in table customer.


SOL> ALTER TABLE customer
Deieting Depart
DROP C ONSTRAINT license-ukeY ;
EEFrs-\ e€' table.

3.3 Enforcing Integrity Gonstraints Fr-rilorring inse:


.qa:a'lent'[T' is n
Integrity Constraints are specified when a relation is created and enforced when a }ERT
relation is rnodified. The impact of domain, PRIMARY KEY and UNIQUE constraints
\TO Employees
is straightforward: if an insert, delete, or update command causes a violation, it is -.--{!IJES (null, 'S
rejected.
Consider the instance E1 of Employees shown in Figure 3.1. The foll l| Querying Re
insertion violates the primary key constraint because there is already a tuple with
Emp-cod e 01234 and it will be rejected by the DBMS :
{ querv is u q
rnrnrz-ing the resu
INSERT
INTO Employees(Emp-code, Emp-name, Dept)
kretrng' departn
rnm ;rcpular com
VALUES (01,234,' Vijay',' Marketing');
@. rn SQL as g
The following insertion violates the constraint that the primary key cannot con ir FcI *
nuII : €}{ Employee
INSERT
IERE E.Dept_
INTO Employees(Emp-code, Emp-name, Dept)
VALUES (null,' Ganesh','Design',);
3e =rrnbol * n
,F -lets onl)-
Of course, a similar problem arises whenever we try to insert a tuple with a val aba-= to the reli
in a field that is not in the domain associated with that field, i.e., whenever we viola
a domain constraint. Deletion does not cause a violation of domarn, primary key
unique constraints- an update can cause violations, similar to an insertion:
{owever,
UPDATE Employee'{
SET E.Emp ode : t2567
WHERE E.EmP_ode : 01234;
htabase Management Systems 3 -27 Relational Model
rl Model
.- This update violates the primary key constraint because there is already a tuple
Emp_code 12567.
The impact of foreign key constraints is more complex because SQL sometimes
to rectify a foreign key constraint violation instead of simply rejecting the change.
ider following'Departrnent' relation:

Dept_Name Location
HR A-311

Sales A-101

Marketing A-104

Production B-101

Design A-201

Deleting Department 'Sales' from 'Departrnent' table is not allowed as it is used in


' table.
insert query also violates foreign k"y integrity constraint as the
when t 'IT' is not present in 'Department' table :

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.

3.5.1 Entity Sets to Tables . Redundancy of Ta


Let E be a strong entity set with descriptive attributes a1,22,.....an. We represent Consider two entitr
this entity by a table called E with n distinct column, each of which corresponds to relationship Loan -p a-),n
one of the attributes of E. Each now in this table corresponds to one entity of the Jepends on entitv set
entity set E. =ince Loan-pavment ta
For example, consider an entifv set 'Student' with attributes : Roll No and Name. Loan_no, Payment_nol
-could also be present j
We represent this entity set by a table 'Student' with two columns 'Roll No' and
'Name' as shown in Fig. 3.9. -s redundant. In genera
rts corresponding stronl
Roll No Name rpresentation of an E-I
2001 John

20a2 Ram

2003 Shyam

2004 Rav

Fig. 3.9 The Student table


del Database Management Systerns 3 -29 Relational Model

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

3.5.2 Relationship Sets to Tables


;et R be a relationship set. Let al,ez,...,em be the set of attributes formed by the
--rnion
of the prirnary keys of each of the entity sets participating in R, and iet the
:escriptive attributes (if any) of R be b1,b2,...,h,r. We represent this relationship set by
: table called R with one column for each attribute of the set.
{ur, u, ur} v {br,br,.... , bn}
:cr example, consiCer the relationship set Depositor. In Fig. 3.10 ',,vith descriptive
'ttribute Access-date. This relationship set involves two entity sets :
. Customer, with the primary-key Custorner-id
Ya
ase/
r Account, with the primary-key Account-no
tit)' Thus, the Depositor table has three columns as shown in Fig. 3.i0.
que
Customer id Account no Access date
c0001 40001 1011212000
rot
can c0002 40002 1311012001

c0003 40003 09t10t2004


c0004 40004 12t12t2001
Llity
1.
Fig. 3.10 The depositor table

' Redundancy of Tables


;ent Consider two entity sets Loan and Payment, which are linked to each other using
;to :=-:ationship Loan-payment with no descriptive attribute. The weak entity set Payment
the :mends on entitv set Loan. The primary key of Payment is {Loan_no, Payment_no}
ile Loan-pavment table has no descriptive attributes, it would have two columns
me. -.-'an-no, Payment--no). Every {Loan_no, Payment_no} combination in Loan-payment
t-tuld also be present in the Payment table, and vice versa. Thus, Loan-payment table
and
-* redundant. In general, the table for the relationship set linking a weak entity set to
._- corresponding strong
entity set is redundant and does not need to present a tabular
r-resentation of an E-It diagram.
Y
Database Management Systems 3-30 Relational Model Database Management t

We handle composite attributes by creating a separate attribute for each of the


component attributes; we do not create a separate column for the composite attribute
itself. Suppose Address is a composite attribute of entity set Customer, and the
comPonents of Address are Street and City. The table generated from Customer would
then contain columns Address-street and Address-city; there is no separate column
for Address.

Consider an entity set Employee with multivalued attribute Dependent_name. For


such multivalued attribute, create a separate table as Dependent_info with attributes
Dependent-name, and Employee-id which is the primary key of Employee entity set.
1. Create a table fr
3.5.3 Translating Weak Entity Sets create a separate

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

Fig.3.11. column for each


attribute of the l
Account-no Transaction-date Debit-amount Gredit-amount Balance have two tables :
4001 20112t2000 100 0 2100
. Saving_accou

4002 12t10t2001 0 200


. Checking_acc
1 800

A009 01t01t2002 200 0 1 500 15,5 Translating ER


4101 2112t2003 0 300 2000 For E-R diagrarn in I
gegation of Works-o
Fig. 3.11 A transaction table riute in the prima{
h--xks-on. It would als<
3.5.4 Translating Glass Hierarchies
There are two different methods for transforming to a tabular form an E-R that -<t-
includes generalization. Consider the generalization shown in Fig. 3.12 where Account
is a higher-level entity, while Saving-account and Checking_account are lower-level
entities.

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 :

. Saving_account, with attributes Acc-no, Balance and Interest-rate.


. Checking_account, with attributes Acc_no, Balance and Overdraft-amount.
35.5 Translating ER Diagrams with Aggregation
For E-R diagrarn in Fig. 1,.45, the table for the relaionship set Manages between the
etgregation of Works-on and the entity set Manager includes a column for each
ffibute in the primary keys of the entity set Manager and the relationship set
Itbrks-on. It would also include the descriptive attributes of relationship set, if any
qist.
hat
unt
:vel
Database Management Systems 3-32 Relational Model Database Managemer

3.6 Introduction to Views 3.6.1 Creating Vier

c The dynamic result of one or more relational operations operating on the


$ntax :

base relations to produce another relation is called aiew. A view is a virtual


relation that- does not necessarily exist in the database but can be produced
upon request by u particular user at the time of request.
r A view is object that gives the user a logical view of data frorn an
underlying table or tables. You can restrict what users can view by allowing
Erample : Create uieu
them to see only a few attributes/columns from a table.
SOtr > create view
o A view is a relation that is created using one or more base relations. The select title,i
\,
contents of a view are defined as a query on one or more base relations. A.y
I

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

3.6.1 Creating View


:!
Syntax :
IC
al CREATE VIEW viewname as
:d SELE CT columnname, cloumnname
FROM tablename
WHERE columnname _ expression list ;
IN
rg
Erample : Create aiew on Book table which contains two fields title, and author nnme.
SOL > create view V Book as
1e select title,author name
ry from book;
1e View created.
le SOL> select * from V Book;

Output :

Title Author name


Oracle Arora

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

3.6.3 Updatable Views 2) ALTER TABLE ..


Views can also be used for data manipulation i.e. the user can perform Insert,
This form is u:
Update and the Delete operations on the view. The views on which data manipulation
Tne generalized syr
can be done are called lJpdatable Views, views that do not allow data manipulation are
called Rendonly Views. When you give a view name in the Update, Insert or Delete
statement, the modifications to the data will be passed to the underlying table.
For the view to be updatable, it should meet following criteria :

o The view must be created on a single table.


. The primary key column of the table should be included in the view. 1

. Aggregate functions cannot be used in the select statement.


7 Example :
. The select statement used for creating a view should not include Distinct,
Modify the dnta
Group by or Haaing clause.
SOL> ALTER.T.
. The select statement used for creati.g u view should not include subqueries. MODIFY(
o It must not use constant, strings or value expressions like total/S. Table created.

3.7 Destroying/Altering Tables and Views


Using the alter
3.7.1 Altering Table . Change the
The definition of the table is changed using ALTER TABLE statement. The ALTER . Change the
TABLE is used to add, delete or modify columns in an existing table. It is
explained below :
. DroP a coh
o Decrease *
1) ALTER TABLE .... ADD ....
This is used to add some extra columns into an existing table. The generalized 3) ALTER TABLE .

format is given below. To delete a colt


ALTER TABLE relation name
ADD (new fieldl datatype (size),
new field2 datatype (size), ......,
new fieldn datatype (size)) ; Erample:

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

Database Management Systems 3-35 Relational Model

2) ALTER TABLE .... MODIFY 1

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.

ALTER TABLE relation name


MODIFY (fieldi new data tYPe (size),
field2 new data tlrpe (size),

field' new data type (size)) ;

Example :

Modifu the data type of the publication year as numeric data type.
SOL> ALTER TABLE Book
MODIFY(Pub-year number(4) ) ;
Table created.

Restrictions of the Alter Table


Using the alter table clause you cannot perform the following tasks :

. Change the name of the table


. Change the name of the column
o Drop a column
o Decrease the size of a column if table data exists.

3) ALTER TABLE .... DELETE


To delete a column in a table, use the following syntax:
ALTER TABLE table name
DROP COLUMN column name

Drop customer fax number from the customer table.


SOL > ALTER TABLE Customer
DROP COLUMN Cust fa< no;
Database Management Systems 3-36 Relational Model

3.7.2 Deleting Table


The tables are deieted permanently from the database using DROP TABLE
Unit-ffl
command. We can remove all the data from the table using TRUNCATE TABLE
command. It is explained below :

1) DROP TABLE
This conunand is used to delete a table. The generalized syntax of this form is
given below :
DROP TABLE relation-name

3.8 Relational Al1


SOL > DROP TABLE Special customer;
A query langual
,iatabase. These l*i
Table dropped. programming langua

2l Truncate a Table i) Procedulral langual


Truncating a table is removing ali records from the table. The structure of the table In procedural lar
stays intact. The SQL language has a DELETE statement which can be used to remove operations on the dai
one or more (or all) rows from a table. Truncation releases storage space occupied by
the table, but deletion does not. The syntax is : -) Nonprocedural lan

CATE TABLE table name ; In a nonprocedu


tr\ing a specific proc
SOL > TRUNCATE TABLE Student : Relational Algebra
The relational al
3.7.3 Deleting View operations that take
A view can be dropped by using the DROP VIEW command. their result.

Syntax : i Formal definition o


DROP VIEW viewname : A basic expressior
o d reiation in
Example :

DROP VIEW V Book :


o I constant re.
A constant r(
{(A - 101 Do-w
A general exprer
apressions. Let Q a
relational algebra expr
Unit-III

Part II - Kelational Algebra

3.8 Relational Algebra


Aquery language is a lan guage in which a user requests information from the
ciatabase. These languages are usually on a level higher than that of a standard
programming languages. Query languages can be categorized as :

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.

ii) Nonprocedural languages


In a nonprocedural language, the user describes the desired information without
Sving a specific procedure for obtaining that informaticn.

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.

i Formal definition of the relational algebra


A basic expression in the relational algebra consists of either one of the following :

o A reiation in the database


o A constant relation
A constant relation is written by listing its tuples within { }, for example
t(A - 101 Downtown, 500) (A - 215, mianus, 700)).
A general expression in relational algebra is constructed out of smaller sub
erpressions. Let E1 and E2 be relational algebra expressions. Then, following all are
relational algebra expression :

(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

relational databases. Some of the operations of this grouP are :


o Select
. Project

/ t Rename
o Ioin
e Division

3.8.1 Selection and Projection

3.8.1.1 Selection
o The select operation selects tupies that satis9 a given predicate.
r The select operation is represented as follows :

o< select conaitiont (R)


The symbol o is used to denote the select operator and the < selection condition >
is an expression specified on the attributes of the relation R. The expression specified
in the selection condition is made up of number of clauses of the form :
< attribute name > < compnrison operator > < constnnt aalue >
or
< nttribute name > < comparison operator > < atttibute name >
Database Management Systems 3-39 Relational Algebra

where,
. < attribute name > is the name of an attribute (column) of the relation R.

o < comparison operator > is one of the following comparison operators | =, *,


113,)-r).
. < constant aalue > is the constant value from the attribute domain. Clauses
are connected by boolean operators AND, OR and NOT to form general
selection condition.
Consider following Book relation as shown in Fig. 3.13.

Book ld Title Author Publisher Year Price


80001 DBMS Korth McGraw-Hill 2000 250
80002 Compiler Ulman 2004 350
80003 OOMD Rambaugh 2003 450
80004 PPL Sabista 2000 500

Fig. 3.13 Book relation


) Examples :

Following are the some examples of the select operation.


1) Display books published in year 2000.

ioyear : 2000 @ook)

The output of above queiy is shown below :

Book ld Title Author Publisher Year Price

80001 DBMS Korth McGraw - Hill 2000 250

80004 PPL Sabista 2000 500

2) Display sll books haaing price greater than 300.

=oprice > 3oo(Book)


The output of the above query is shown below :

Book ld Title Author Publisher Year Price

80002 Compiler Ulman 2004 350

80003 OOMD Rambaugh 2003 450

B0004 PPL Sabista 2000 500


Database Management SYstems 3-40 Relational Algebra

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 :

Book ld Title Author Publisher Year Price

80001 DBMS Korth McGraw - Hill 2000 250

80002 Compiler Ulman 2004 350

80003 OOMD Rambaugh 2003 450

80004 PPL Sabista 2000 500

4) Select the tuples for all books whose publishing yenr is 2000 and price is greater than
300.

=olyear = 2000) and (Price > 300) (Book)

The ouput of above query is shown below :

Book ld Title Author Publisher Year Price

B0004 PPL Sabista 2000 500

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.

The following are the examples of project operation on Book relation.


1) Display all titles with author name.
= lI Titre. Autho, (Book)
Database Management Systems 3-41 Relational Algebra

The output of above query is given in Fig. 9.1,4.

Title Author

DBMS Korth

Compiler Galwin

OOMD Rambaugh

PPL Sabista

Fig. 3.14 Title and Author of Book


2) Displny all book titles with authors and price.
= lI ritle ' Author ' Price (Book)
The output of abo e query is given in Fig. 3.15.
I
I
Title Author Price

DBMS Korth 250

Compiler Galwin 350

OOMD Rambaugh 450

PPL Sabista 500

Fig. 3.15 Title, Author and Price of Books

33.1.3 Composition of Select and Project


The relational operations select and project can be combined to form a complicated
query. '

Example :

1) Display the titles of books haaing price greater than 300.


= lI r" (orrice > 3oo @ook))
"t
The output of the above query is given in Fig. 3.16.

Title

Compiler

OOMD

PPL

Fig. 3.16 Title of the Books


Database Management SYstems 3-42 Relational Algebra

3.8,2 Set Operations


Union, intersection and difference operations require that the tables involved be
union compatible. Two relations are said to be union compatible if the following
conditions are satisfied :
o The two relations/tables must contain the same number of columns (have
the same degree).
. Each column of the first relation/table must be either the same data type as
the corresponding column of the second relation/table or convertible to the
same data tFpe as corresponding column of the second.
Consider following two relations :

Depositor

Customer name City


Hayes Pune

Johnson Mumbai

Jones Solapur

Lindsay Nashik
2l
Smith Pune

Turner Mumbai
bot
Borrower

Gustomer name City


Adams Mumbai

Curry Pune

Hayes Pune

Jackson Solapur

Jones Solapur

Smith Pune

Williams Kolhapur

Fig. 3.17 A Depositor and Borrower relation


The two relations are union compatible. Now we will see four set oriented 3) Di
operations. Th
differe
1) Union
Borrov
The result of operation is denoted by Depositor w Boruower, is the relation that
includes all tuples that are either in Depositor or Borrower or in both. Duplicates are
eliminated.
Database Management Systems 3-43 Relational Algebra

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

Fig. 3.18 Result of union operation


2l Intersection
The result of intersection operation is a relation that includes all tuples that are in
both Depositor and Borrower. The intersection operation is denoted by
Depositor nBorrower.
Example : Find the names of customers who have both an account and loan.
The result of intersection is :

Depositor n Borrower
Gustome name City
Hayes Pune

Jones Solapur

Smith Pune

Fig. 3.19 Result of intersection operation


3) Difference
The difference operation is denoted by Depositor - Borrower. The result of the
difference operator is the relation that contains all tuples in Depositor but not in
Borrower.
Database Managennent SYstems 3-44 Relational Algebra

Depositor - Borrower

Gustomer name City

Johnson Mumbai

Lindsay Nashik

Turner Mumbai

Fig. 3.20 Result of difference operation


Both union and intersection operations are commutative and associative operations'
This means that following are true :
. AVB _ BWA and AaB-BaA
. Aw(BuC) : (a rB) uC and a n(r..rC) = (A n B) nC
The difference operation is not commutative. This means that A - B is not the
same as B - A or in other words A -B+B-4.

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

Fig. 3.21 Publisher-lnfo and Book_lnfo relation


3.8
The relation Publisher-InJo has 2 columns and 3 tuples. The relation Book Info has
2 columns and 2 tuples. So the cartesian product has 4 columns (Z + Z) and 6 tuPles
' * Z).The cartesian product of Publisher-lnfo and Book Info is given in Fig. 3.22. the
Dift
Database Management Systems 3-45 Relational Algebra

Publisher_lnfo x Book_lnfo

Publisher lD Name Book lD Title

P0001 McGraw-Hill 80001 DBMS

P0002 PH 80001 DBMS

P0003 Pearson B0001 DBMS

P0001 McGraw-Hill 80002 Compiler

P0002 PHI B0002 Compiler

P0003 Pearson 80002 Compiler

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 :

i) P S (new atrrib,rte.ra-es) (R)


ii) p 5 (R)

iii) P (new arrribr," r,u-.r) (R)


The svmbol 'p' (rho) is used to denote the RENAME operator . 'S' is the new
relation and 'R'is original relation.
The first expression renames both the relation and its attributes, the second
third renames only the attributes.
renames the relation only and the

For example consider the Book relation with attributes Title, Author, Year and
Price. The rename operator is used on Book relation as follou s :

1) P r"-p(Bname, Aname, Pyear, Bprice) @ook)


Here both the relation name and the attribute names are renamed.
2) p r"-p (Book)
Here only the relation name is renamed.
3) P 1nrlu-e, Aname, pyear, Bprice) (Book)
In this case, only the attribute names are renamed.

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

1) Condition Joins (or theta join) 2) Equijoin :

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

Consider following two relations Car and Boat :

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

Boat2 50'000 Example :

Boat3 60'000 Consider tl


Fig. 3.24 Relation 'Boat' i) Employe
The condition join ii) Salary, I
Car p4 Carprice2 Boatprice Boat yields following relation : The EmPlo

Car A Boat

CarPrice > BoatPrice

CarModel CarPrice BoatModel BoatPrice

CarA 20'000 Boatl 10'000

CarB 30'000 Boatl 10'000

CarC 50'000 Boatl 10'000

CarC 50'000 Boat2 50'000


Database Management Systems 3 ' 4? Relational Atgebra

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>< Carprice= Boatprice Boat yields following relation :

Car X Boat
CnrPrice - BoatPrice

CarModel GarPrice BoatModel BoatPrice

CarC 50'000 Boat2 50'000

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 :

Consider two relations :

i) Employee, with attribute Emp-code and Emp-name


ii) Satary, with attributes Emp-code and Salary.
The Employee and Salary relations are shown below :

Employee Salary

Emp_Code Emp_name Emp_Code Salary

E0001 Hari E0001 2000

E0002 Om E0002 5000

E0003 Smith E0003 7000

E0004 Jay E0004 10000

Fig. 3.25 The Employee and Salary relations


Database Management Systems 3-48 Relational Algebra

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

The above query is rewritten using natural-join as follows :

til"-p_narne, salary @mployee D( 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

Fig. 3.26 Result of fI Emp_nome, Solory (Employee D( Solory)

3.8.5 Division
The division operation is denoted by '*'. It is suited to queries that include the
phrase 'for alI'.

Consider three relations :

i) Account
Account no Branch name Balance

A-101 Downtown 500

A-102 Perryridge 400

A-201 Brighton 900

A-215 Mianus 700

A-217 Brighton 750

A-222 Redwood 700

A-305 Round Hill 350

Fig. 3.27 The Account Relation


tHabase Man egement SYstems 3-49 'Relatioi#Ailgebm

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

Fig; 3.28 The Depositor Relation

Branch

Branch name Branch_city Assets


Brighton Brooklyn 71000

Downtown Brooklyn 191000

Mianus Horseneck 21000

North town Rye 351200

Perryridge Horseneck 40000

Pownal -. Bennington.. 500.0

Redwood Palo Alto 12340

Round Hill Horseneck 1000

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

4 = fI Branch narne (o granctl-city = "Brookllm" (BraDch) )

The result of this expression is shown it Fig. 3.30.

Branch_name
Brighton
Downtown

Fig. 3.30 Result of fI Bronch-no-" (orronch-ciry = ,,glqsklyn" (Bronch))

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.

This query can be written as follows :


p(Tempboats, (o color= ,rr6,Boats) w (6 ,olor= ,green,Boats))

fr sname (TempboatsX ReservesX Sailors)

Query 6) Find the names of sailors who hnae reseraed a red and a green boat.

This query can be written as follows :


p(Tempboats2, (o color= ,rr4, Boats)a (o color= ,green,Boats))

p sname (TempboatsT x Reserves x Sailors)

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

p (Reservationpairs (1+ sid1,2+ sname 1, 3+ bidl, 4+ sid2,


5 + snameZ, 6 + bidz), Reservationsx Reservations)
fi snamel o
$idl = sid 2) ^ (bidl * bid )Reservationpairs

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)

fisia ((o cotor=,red Boats) x Reserves A Sailors)

Query 9l Find the names of sailors who haae reseraed all boats.

This query can be written as follows :


n(Tempsids, (nsid, 616 Reserves) / (n 6laBoats))
fi sname (Tempsidsx Sailors)

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

3.9 Relational Galculus that is, it is tt


In tuple relati
Relational calculus is the collective term used for fuple calculus and domain
r[A] - d
calculus. The queries in the relational algebra are procedural. The users are only
te r - dt
required to specify what information they need without considering how to obtain
information from the database and the RDBMS decides how to get it. Consider followir

In relational calculus, a query is expressed as a formula consisting of a number of 1) Loan


variables and an expression involving these variables. The formula describes the
properties of the result relation to be obtained. There is no mechanism to specify how
the formula should be evaluated. It is up to the RDBMS to convert these
non-Procedural queries into equivalent, efficient procedural queries. In relational tuple
calculus, the variables represent the tuples from specified relations. In domain calculus
the variables represent the values drawn from specified domains.
Relational calculus is a formal query language where the queries are expressed as
variables and formulas on these variables. Such formulas specify the properties of the
required result relation without specifying the method of evaluating it. Thus, a
relational calculus exPression specifies what is to be retrieved rather than how to 2) Depositor
retrieve it. Therefore, relational calculus is considered to be a non-procedural language.
This is where relational calculus differs from telational atgebra. Retational algebra is a
procedural language, where we must write a sequence of operations to specify a
retrieval request. It is possible to specify in relational calculus any retrieval that can be
specified in the relational algebra and vice versa.
Some of the most conunon data manipulation operations that are required in
conunercial query language cannot be performed with the basic relational algebraic
operations or relational calculus formulae. These includ e aggregate ftmctions like SUM,
COUNT, AVERAGE, MIN,MAX etc., recursive relations etc.
The relational calculus comes in two types :
' Tuple Relational Calculus (TRC) : Variables range over tuples of a relation. 3) Borrower
o Domain Relational Calculus (DRC) : Variables range over elements of a
domain.
o The concepts used in Relational calculus include : Variables, constants,
comparison, operations, logical connectivities and quantifies.

3.9.1 Tuple Relational Galculus

The tuple relational' algebra is a nonprocedural query language. It describes the


desired information without giving a specific procedure for obtaining that information.
A query in the tuple relational calculus is expressed as,

{/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

Customer name Account no


Hayes A-102
Johnson A-101
Johnson A-201
Jones A-217
Lindsay A-222
Smith A-215
Turner A-305

3) Borrower

Gustomer name Loan no


Adams L-1 6

Curry L-93

Jackson L-1 5

Jones L-17

Smith L-11

Smith L-23

Williams t-17

Fig. 3.32 The loan, depositor and borrower relations


Database Management Systems 3-54 Relational Algebra Database Manag

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.

4) Find name and nccount numbers of aII customers. following fo


= {t I I s e Depositor (t [Customer_name] - s [Customer name] n o se f,w
t [Account_no : s [Account_no]]
' s[x] o r.,

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

6) Find aII customers who haae an account, a loan or both. . s[x]0c


is a con
In relational algebra, we have used union operator. In tuple relational calculus we
need two "there exists" clauses connected by or (v).
+ { t I I s e Depositor (t [Customer_namel - s [Customer_name]) v o An ator
f u e Borrower (t [Customer name] : u [Customer_name])]
r If4is
7) Find only those customers who haoe both an account and a loan at the bank.
. If P1 an
={ t | 3 s e Depositor (t [Customer_narre] - s [Customer_name]) n
I u e Borrower (t lCustomer_name]) : u [Customer_name]) ] is impli

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

-- I s eBorrower (t lCustomer_namel - s [Customer_name] ) ]


Database Management Systems 3-55 Relational Algebra

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.

A tuple-relational calculus expression is of the form,


{ f tP(t }
where,
P - is a
formula, several fuple variables may appear in a formula.
A tuple variable is said to be free variable unless it is qualified by a I or V. ( I
there exists, V : for all ). '

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 :

o s e r; where s is a tuple variable and r is a relation.


' t[r] e ,lf], where s and u
tuple variables , x is an attribute on which s
are
is defined, y is an attribute on which a is defined, and 0 is a comparison
operator. (a, 3,=,*,>, >) ; we require that attributes x and y have domains
whose members can be compared by 0.

' t[4 0 where s is a tuple variable, x is an atlribute on which s is defined,


q,
0
is a comparison operator, and c is a constant in the domain of attribute x.

we build up formulae from atoms by using the following rules :


o An atom is a formula.
o lf Pr is a formula, then so are - pt and (p1).
. If P1 and P2 arc formulae, then so are P1v P2 , pL A p2 and, pt p2 (where +
=
is implies operator).
o If 4 (t is a formula containing a free tuple variable s and r is a relation,
then f se r (Pr(4) ana v se r (pt(s)) are arso formulae.
Database Management Systems 3-56 Relational Algebra Database Man

Equivalences in tuple relational calculus : Formal de

1) 4 n Pz is equivalent to -(-(4) " --(Pr)) An expres


2) v t. r(4 (0) is equivalent to -' I re t (-& (0) {."
where,
3) & - Pz is equivalent to -- (Pt) , Pz. x1, x',

Additional Queries : P-fr


Consider following schema: An atom i

Sailors(sid: integer, sname: string, rnting: integer, age: teal) . <X1,,


Boats(bid: integer, bname: string, color: string) doma

Reserves(sid : integer, bid : integer, day : date) . x@A,

1) Find the names and ages of sailors with a rating nborse 7.


(.' s,
@.

{P l= Se Sailors (5. rating> 7 n P. name= S. sname n P. age= S age)} o x@c,


2) Find the sailor name, boat id, and reseraation date for each reseruation. consta

{P l= Re Reservesl Se Sailors Formulae


(R. sjd= S. sldn P.bid= R. bid n P. day= R. day n P. sname - S. sname)j o An atr
3) Find the nnmes of snilors who haae reseraed boat L03. o IfPli
{P l= Se Sailorsl Re Reservers (R.sid- S.srdn R.bid= 103nP.snilnl€= S.sname)}
o If P1 t
4) Find the nnmes of sailors who hnae reseraed a red boat. . rf 4(
{P I Se Sailorsl Re Reserves (R. sid- S. s,rdn P. sname= S. sname and V
=
n1 Be Boates (B.bid= R.bid n B. color- red'))j ' ExamPle
5) Find the names of snilors who hnae reseraed at least two bonts. I) Find the loa
{P l= Se Sailorsf Rle Reservesf RZe Reserves I,b,a
(S.srd= Rl.sidnRl.sid: R2 sidn Rl.bid+ R2.bidn P.sname- S.sname)]
= {.
2) Find aII lon
6) Find the names of sailors who haae reseraed nll boats.
{P I
=
Se Sailors Y Be Boats ={.ltl
(f Re Reserves (5. sid= R. sid n R.bid= B.bid n P. sname- S. sname))\ 3) Find the na

7) Find sailors who haae reseraed all red boats. loan amout

{S / Se Sailors nY Be Boats = { < c,a


(8. color =' red =+ (tRe Re serves(S. sld= R. sid n R.bid = B.bid))I
4) Find the ru

3.9.2 Domain Relational Calculus ={<c>l


Domain relational calculus uses domain variables that take on values from an 5) Find the nr
attributes domain, rather than for an entire tuple.
+{<c>
Database Management Systems 3-57 Relational Algebra

An expression in the domain relational calculus is of the form :


r
t .rt, x2,....., xn, I P(rt, X2,..., rn)I
where,
xI,xZ,....xn - represent domain variables.
P - formula composed of atoms.
An atom in the domain relational calculus has one of the following forms :
' 1x1, xz,...,xn) e r; where r is a relation on n attributes and xt,xz,...,xn ate
domain variables or domain constants.
' 'x @ Y, where r and y are domain variables and @ is a comparision operator
(., (, =, #, >, >). Athibutes x and y have domains that can be compared by
@.

' x@ c, where ris a domainvariable,@ is a comparision operator, and c is a


constant in the domain of the attribute for which r is a domain variable.
Formulae are build up from atoms using the following rules :
. An atom is a formulae.
. If 4 is a formula, then so are - pr urrd (4)
o rf Pt p1v p2, p1x p2 and
and' P2 are formulae, then so are pz.
4=
' If Pr(4 it a formula in x, where x is a domain variable, then
=
x (er(4)
and V , (Pr(4) are also formulae.

1) Find the loan number, branch name and amount loans of oaer $
for 1200.

= {. I,b,at | ./,b,a> e koan xa > 1200}


2) Find all loan numbers for loans with an amount greater than g L200.
> I I b,a (< I,b,a> e
= {./ hoann a > 1200)}

3) Find the names of all customers who haae a loan


[ro* the Perryridge branch and find the
Ioan amount.

=+ { < c,d) lll(< c, I}eborrower n f b (<I,h,a>€ loannb ="perryridge',)}


4) Find the names of aII customers who haae a loan at the Perryridge branch.

={<c>l I I(<c,I>e Borrowerni b,a ((<l,b,a>c Loan n b="perry.idge"))}

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

Consider following schema:


Sailors(sid;lnte_qer, sname; string, rating: integer, age: real)
Boats(bid: inteqer, bname: string, color: stfing)
Reserves(sid: inteqer, bid: integer, day: date)

D Find the names and ages of sailors with a rnting aboae 7.


{ (1, N, T, A) \f/, ry, T, A)e Sar/orsn T>7}
! Find the names of snilors who haue reseraed boat 103.
{rry | = I, T, A ((1, N, T, A)e Sailors
nf Ir, Br, D (Qr, Br, D)e Resewesn .Ir= I n Br= 103))\
il Find the names of sailors who haae reseraed a red boat.
{(N) l= I, T, A ((1, N, T, A)e Sailors
n1I, Br, D)e Resenres n1(Br, BIV ' red' )e Boats)\

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

il Find sailors who haae reseraed nll red bonts.


{(1, N, T, A)l (1, N, T, A)e Sar/ors xY (8, BN, C)e Boats
(C=' red'=1 (Ir, Br, D)e Resentes(I= Ir n nr: B))l

University Questions with Answers


Q.1Definewithexamples,thereIationandreIationschema,
Ans. : Refer section 3.1.1.1.

Q.2 What are the notations used in SQL commands.


Ans. : Refer section 3.1.3.

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

EMPLOY EE (Empnum, Empname)


ASS/CNE D _T O (Proj ectnum, Empnuml
Write the following queries in tuple relational calculus
i) Find Empnum of employees working on project COMP4S4