0% found this document useful (0 votes)
90 views69 pages

BX4004 - Database Management System

The document covers the fundamentals of Database Management Systems (DBMS) and the Relational Model, focusing on SQL as a standard language for database manipulation. It details SQL commands for data definition and manipulation, as well as Codd's 12 rules that define the characteristics of a relational database. The content is intended for students in the Master of Computer Applications program at Anna University.

Uploaded by

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

BX4004 - Database Management System

The document covers the fundamentals of Database Management Systems (DBMS) and the Relational Model, focusing on SQL as a standard language for database manipulation. It details SQL commands for data definition and manipulation, as well as Codd's 12 rules that define the characteristics of a relational database. The content is intended for students in the Master of Computer Applications program at Anna University.

Uploaded by

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

lOMoARcPSD|44483619

BX4004 UNIT 1 Database management systems

Master of Computer Applications (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sarankumar S ([email protected])
lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

BX4004( DBMS Unit 2) RELATIONAL MODEL AND QUERY


EVALUATION
Bridge course (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sarankumar S ([email protected])
lOMoARcPSD|44483619

Unit ll RELATIONAL MOD EL AND QUERY EVALUATION

2 .1 Relational Mod el con ce pts and 2.2 Relationa l Algebra


Pdf file (slides 1-39)

2.3 SQL . .
SQL is a standard language for accessing and manipulating databases.
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases .
• SQL is an ANSI (American National Standards Institute) standard
What Can SQL do ?
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views
SQL is a Standard - BUT.... . .
Although SQL is an ANSI (American National Standards Institute) standard, there are different versions of the
SQL language.
However , to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT,
UPDATE , DELETE , INSERT, WHERE) in a similar manner.
Using SQL in Web Site
To build a web site that shows data from a database, you will need:
• An RDBMS database program (i.e. MS Access, SQL Server, MyS QL)
• To use a server -side scripting language, like PHP or ASP
• To use SQL to get the data you want
• To use HTML / CSS to style the page
RDBMS
RDBMS stands for Relational Database Management System .
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server , IBM D82, Oracle ,
MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables . A table is a collection of related data entries and it
consists of columns and rows.
Every table is broken up into smaller entities called fields. The fields in the Customers table consist of
CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country. A field is a column in a table
that is designed to maintain specific information about every record in the table.
A record, also called a row, is each individual entry that exists in a table . For example, there are 91 records in the
above Customers table. A record is a horizontal entity in a table.
A column is a vertical entity in a table that contains all information associated with a specific field in a table.
Codd's Rule
E.F Codd was a Computer Scientist who invented Relational model for Database management. Based on
relational model, Relation database was created. Codd proposed 13 rules popularly known as Codd's 12 r~ -
test DBMS's concept against his relational model. Codd's rule actualy define what quality a DBMS ·
order to become a Relational Database Management System(RDBMS). Till now, there is hardl~
product that follows all the 13 Codd's rules. Even Oracle follows only eight and half o~i
Wiesare as follows.

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619


Rule zero
This rule states that for a system to quali
. DBMS tt must be ahlc to man age database entirely through the
fy as an R '
relational capabilities .
Rule 1 : 111/ormationmle
. d d t· . cells of tables. The rows and
All information(includm g mctncinta) •,s to bc rcprcs cntcd as store a a 10 columns
have to be strictly unordered .
Rule 2 : Guarantcd Access
Each unique piece ofdata(atomic value . N + rimary key(Row) +
) should be acccstble by: Table amc
Attributc(column).
P
NOTE : Ability to directly access via POIN
TER is a violation of this rule
Rule 3: Sptcmctic treatment of NULL
Null has ;e, era! meanings, it can mean h di d 'stently
missing data, not applicable or no value
. It should be an e conSI ·
PrimaI} key must not be null. Expressio
n on NULL must give null.
Rule 4 : Active Online Catalog
Database dictionary(catalog) must have
description of Database Catalog to be
the database. The same query language governed by same rule as reSt of
to be used on catalog as on application
Rule 5: Powerful language database.
One well defined language must be there
to provide all manners of access to data
supporting table can be accessed by any Example: SQL. If a file ,
manner except SQL interface, then its a
Rule 6: View Updation rule violation to this rule.
All view that are theoretically updatable
should be updatable by the system.
Rule 7: Relatio11allevel Operation
There must be Insert, Delete, Update oper
ations at each level of relations. Set oper
and minus should also be supported. ation like Union, Intersection
Rule 8 : Physical Data llldepe11de11
ce
The physical storage of data should not
matter to the system. If say, some file supp
moved from one disk to another, it shou orting table were renamed or
ld not effect the application.
Rule 9 : logical Data Independence
If there is change in the logical structure(
table structures) of the database the user
Say, if a table is split into two tables, view of data should not change.
a new view should give result as the join
difficult to satisfy. of the two tables. This rule is most
Rule IO: Integrity Independence
The database should be able to conforce
its own integrity rather than using other
constraints, trigger etc should be store programs. Key and Check
d in Data Dictionary. This also make RDB
Rule 11 : Dist MS independent of front-end.
ribution Independence
A database should work properly regar
dless of its distribution across a network.
This lays foundation of distributed
database.
Rule 12: Nonsubversion rule
If low level access is allowed to a system
it should not be able to subvert or bypa
This can be achieved by some sort of ss integrity rule to change data
looking or encryption.
SQL keywords are NOT case sensitive:
select is the same as SELECT
Semicolon after SQL Statements?
Some database systems require a semi
colon at the end of each SQL statement
Semicolon is the standard way to sepa .
rate each SQL statement in database
systems that allow more than one SQL
statement to be executed in the same
call to the server.

2.4 Some of The Most Important SQL


Commands

• SELECT - extracts data from a database


• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INS ERT INTO - inserts new ~ta into
a datab ase
,.ti
II.',
Downloaded by Sarankumar S ([email protected])
lOMoARcPSD|44483619

• CREATE DATABASE - creates a new database


• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE- modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX- creates an index (search key)
• DROP INDEX- deletes an index
SQL is a programminglanguage for Relational Databases. It is designed over relational algebra and tuple relational
calculus. SQL comes as a package with all major distributionsof RDBMS.
SQL comprises both data definition and data manipulationlanguages.Using the data definition propertiesof SQL,
one can design and modify database schema, whereas data manipulationpropertiesallows SQL to store and
retrieve data from database.
Data Definition Language
SQL uses the following set of commands to define databaseschema-
CREATE
Creates new databases, tables and views from RDBMS.
For example -
Create table article;
Create view for_students;
DROP
Drops commands,views, tables, and databases from RDBMS.
For example-
Drop table article;
Drop view for_students;
ALTER
Modifies database schema.
Alter object_type object_name parameters;
For example--
Alter table article add subject varchar;
This command adds an attribute in the relation article with the name subject of string type.
Data Manipulation Langua ge
SQL is equipped with data manipulation language(DML). DML modifiesthe database instance by inserting,
updating and deleting its data. DML is responsible for all forms of data modification in a database. SQL contains
the following set of commands in its DML section -
• SELECT/FROM/WHERE
• INSERT INTON ALUES
• UPDATE/SET/WHERE
• DELETE FROM/WHERE
These basic constructs allow database programmersand users to enter data and informationinto the databaseand
retrieve efficientlyusing a number of filter options.
SELECT~ROM/WHERE
• SELECT - This is one of the fundamentalquery command of SQL. It is similar to the projection
operationof relational algebra. It selects the attributesbased on the condition described by WHERE
clause.
• FROM - This clause takes a relation name as an argumentfrom which attributes are to be
selected/projected.In case more than one relationnames are given, this clausecorrespondsto Cartesian
product.
• WHERE - This clause defines predicateor conditions,which must match in order to qualify the attributes
to be projected.
For example -
Select author_name
From book_author

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Rule zero . d tabase entirely through the


This rule states that for a syst RDBMS 1t mu st be able to manage a
em to qualify as an
'
relational capabilities.
Rule 1: lnformatio11 rule
d as stored data in cells of
The rows and columns
All information (including tables.
metadata ) ·is tO be represente
have to be strictly unordered
.
Rule 2: Guara11tedAccess
Each unique piece of data(a . b . Table Name+ primary
tomic value) should be acc key(Row) +
esible Y ·
Attribute ( column) .
NOTE : Ability to directly . · h' I
access vta ' It'
POINTER 1s a v10 a ion oft1srue.
Rul e 3: Systemetic treatme
nt of NULL
Null has several meanings, . It hould be handled con
it can mean missing data, sistently.
Primary key must not be nul not applicable or nova 1ue.
l. Expression on NULL mu s
st give null.
Rule 4: Active Online Catalo
Database dictionary(catalo g
g) must have description db le as rest of
the database. The same que of Database. Catalog to be
ry language to be used on governe Y same ru
catalog as on application dat
Rule 5: Powerful language abase.
One well defined language
must be there to provide all
supporting table can be acc manners of access to data.
essed by any manner except Example: SQL. If a file
Rule 6: View Updation rul SQ L inte rfac e, the n its a violation to this rule.
e
All view that are theoretica
lly updatable should be upd
Rule 7: Relational Level atable by the system.
Operation
There must be Insert, Delete
, Update operations at eac
and minus should also be sup h level of relations. Set ope
ported. ration like Union, Interse
ction
Rule 8: Physical Data Ind
ependence
The physical storage of dat
a should not matter to the
moved from one disk to ano system. If say, some file sup
ther , it should not effect the porting table were renamed
application. or
Rule 9 : Logical Data Ind
ependence
If there is change in the log
ical structure(table structu
Say, if a table is split into res) of the database the use
two tables, a new view sho r view of data should not
uld give result as the join of change.
difficult to satisfy. the two tables . This rule is
most
Rule 10: Integrity Indepe
ndence
The database should be abl
e to conforce its own integrit
constraints, trigger etc sho y rather than using other pro
uld be stored in Data Diction grams . Key and Check
Rule 11 : Distribution Ind ary . This also make RDBM
ependence S independent of front-end.
A database should work pro
perly regardless of its distrib
database. ution across a network. Thi
s lays foundation of distrib
uted
Rule 12 : Nonsubversion
rule
If low level access is allowe
d to a system it should not
This can be achieved by som be able to subvert or bypass
e sort of looking or encryp integrity rule to change dat
tion. a
SQL keywords are NOT cas
e sensitive: select is the sam
Semicolon after SQL Statem e as SELECT
ents?
Some database systems req
uire a semicolon at the end
Semicolon is the standard of each SQL statement.
way to separate each SQL
statement to be executed in stat ement in database systems
the same call to the server that allow more than one SQ
. L

2.4 Some of The Most Im


portan t SQL Commands

• SELECT - extracts data fro


m a database
• UPDATE - updates data in
a database
• DELETE - deletes data fro
m \ database
• INSERT INTO - inserts new
t'tata into a database
f,t
r

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

- creates a new database


• CREATE DAT ABASE
- modifies a database
• ALTE R DATABASE
E - creates a new table
• CREA TE TABL
E - modifies a table
• ALTER TABL
deletes a table
• DROP TABLE - arch key)
X - creates an index (se
• CREATE INDE onal
DROP INDEX - delete
s an index al algebra and tuple relati

lat ion al Da tab ase s. It 1s designed over relation
guage for Re .
SQL is a programming lan trib utions of RDBMS .
..
e wi th all ma jor dis n pro per tie s of SQL,
calculus. SQL comes as
a packag
tio n lan gu age s. Us ing the data definitio
nipula
a definition and data ma ulation properties allows
SOL to store and
SQL comprises both dat a, wh ere as dat a ma nip
y database schem
one can design and modif
se.
retrieve data from databa
ng ua ge
Data Definition La abase schema -
use s the fol low ing set of commands to define dat
SQL
CREATE S.
les and views from RDBM
Creates new databases, tab
Fo r exa mple -
Create table article;
Create view for_students;
DROP m RDBMS.
, tables, and databases fro
Drops commands, views
For example--
Drop table article;
Drop view for_students;
ALTER
a
Modifies database schem
ame param eters;
Alter obj ect_type object_n
For example--
ject varchar; t of string type.
Alter table article add sub on art icle with the name subjec
rib ute in the rel ati
This command adds an att
Data Manipulation Lang
uage instance by inserting,
(D ML ). DM L modifies the database
a manipulatio n lan gu age abase . SQL contains
SQL is equipped with dat nsi ble for all for ms of data modification in a dat
data. DML is respo
updating and deleting its
ma nds in its DML section -
the following set of com
RE
• SELECT/FROM/WHE
VES
• INSERT INTON AL
T/W HE RE
• UPDATP/SE
• DELETE FROM/WHE
RE into the database and
gra mm ers and use rs to enter data and infonnation
ow database pro
These basic constructs all
ly usi ng a number of filter options.
retrieve efficient
SELECT/FROM/WHE
RE r to the projection
ent al qu ery com mand of SQL. It is simila
e of the fun dam bed by WHERE
• SELECT-This is on sel ect s the att rib ute s bas ed on the condition descri
ebra. It
operation of relational alg
cla use . attributes are to be
nam e as an argument from which
• FROM -This clause
tak es a rel ati on corresponds to Cartesian
tha n on e rel ati on nam es are given, this clause
e more
selected/projected. In cas
e~
product. tch in order to qualify th
def ine s pre dic ate or conditions, which must ma
• WHERE - This clause
to be projected.
For exarnple-
~J• author_name
Of

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Where age> 50;


This command will yield the nam h tion book author w h ose age is 0areater than SO.
es of auth0 rs from t e re1a
-
INSERT lNTON ALUES
This command is used for insertin . f t
g values mto the rows O a a ble (relation).
Syntax-
INSERT INTO table (column\
(, column2, column3 ... ]) VALUE S ( 1ue 1 [ val ue2 val ue3 ••• ])
Or va ' '
INSERT INTO table VALUES
(value\, [va\ue2, ... ])
For example -
INSERT JNfO tutorialspoint (Au t
thor, Subject) VALUES anonym
ous , compu ers ,
11 11 11 11 )•
(

UPDATE/SET/WHERE
This command is used for updatin I · )
g or modifying the values of colu
mns in a table (re ation ·
Syntax -
UPDATE table_name SET colu
mn_name =value(, column_nam d" · ]
e =value ...] [WHERE con ition
For example -
UPDATE tutorialspoint SET Aut
hor= webmaster WHERE Aut
11 11
11

DELETE/FROM/WHERE hor= anonymous 11


;

This command is used for removin


g one or more rows from a tabl
Syntax- e (relation).
DELETE FROM table_name [WH
ERE condition);
For example -
DELETE FROM tutorialspoints
WHERE Author= unknown
11 11
;

TCL : Transaction Control Lan


guage
These commands are to keep a
check on other commands and thei
annul changes made by other com r affect on the database. These
mands by rolling back to original commands can
state. It can also make changes
Command Description permanent.
commit to permanently save
rollback to undo change
savepoint to save temporarily
DCL : Data Control Language
Data control language provides
command to grant and take back
authority.
Command Description
grant grant permission of right
revoke take back permission.
DQL : Data Query Language
Command Description
select retrieve records from one or mor
e table

2.5 Complex sql queries

To fetch ALTERNA TE records


from a table. (EVEN NUMBER
select* from emp where rowid ED)
in (select decode(mod(rownum,2
To select ALTERNATE records ),0,rowid, null) from emp);
from a table. (ODD NUMBER
select* from emp where rowid ED)
in (select decode(mod(rownum,2
Find the 3rd MAX salary in the ),0,n ull ,rowid) from emp);
emp table.
select distinct sal from emp e 1
where 3 = (select count( distinct
Find the 3rd MIN salary in the sal) from emp e2 where e \ .sal
emp table. <= e2.sal);
select distinct sal from emp el
where-3 = (select count(distinct
sal) from emp e2where el.sal >="
e-2-C

ft
Downloaded by Sarankumar S ([email protected])
lOMoARcPSD|44483619

from a table.
Se lect FIRST n records
rownum <= &n;
select * from emp where
from a table (select count(*) - &n fro
m emp);
Se lect LAST n records ere rownum
fro m em p wh department.
select* from emp mi nu
s sel ect *
ts in wh ich the re ar e no employe in the
es
en
me for all the de partm
List dept no., Dept na ptno from emp),
deptno no t in (se lec t de a.deptno = b.deptno);
select* from de pt where ex ist s (se lect* from cmp b where d
* from dept a wh ere no t eptno(+) - b.deptno an
alternate so lution: select de ptn o,d na me fro m emp a. dept b where a.d
ect empno,cname.b
altertnate solution: sel
empno is null; order by a.sal
ies ? b where a.sal <= b.sal)
How to get 3 Ma\'. sa lar t count(d ist inc t sal ) fro m em p
emp a where 3 >- (selec
select distinct sal from
desc; ;
How to ge t 3 M in sa lar
ies ? b where a.sal >= b.sal)
ere 3 >= (se lec t co un t(distinct sal) from emp
emp a wh
select distinct sal from
ere a.sal >= b.sal);
How to get nth max sa laries ?
= (se lec t co un t(d ist inct sal) from emp b wh
from emp a where &n
select distinct hiredate le.
CORD S fro m emp tab m emp b where a.emp
no=b.empno);
Select DISTINCT RE (se lec t ma x(r ow id) fro
ere rowid =
select* from emp a wh
te rows in a table? mpno=b.empno);
How to delete duplica lec t ma x(r ow id) from emp b where a.e
rowid != (se
de lete from emp a where se.
of em plo yees in departm ent wi ere a.deptno(+)=b.deptn
o group by
Count of number fro m em p a, de pt b wh
b.deptno, dname
select count(EMPNO), sa lary of each and
b.deptno,dname; ide d by em p tab le. How to fetch monthl y
prov
al salary informa tion
Suppose there is annu
every employee?
monthlysal from emp;
select ename,sal/ 12 as o =10 or 40.
emp table where deptn
Select all record from O;
deptno=30 or deptno=l
select* from emp where ptn o= 30 and sa l>IS 00 .
rec or d fro m em p table where de
Select all 00;
deptno=30 and sa l> 15
select * from emp where not in SALESMAN or
CLERK.
m em p wh ere job
Select all record fro N ','CLERK ');
job not in ('SALESMA d'FORD'.
select* from emp where e in 'B LA KE ','SCOTT' ,'KING'an
emp where en am
Select all record from NE S', 'BLAKE ','SCOTI' ,'KIN
G' ,'FORD ');
en am e in( 'JO
select* from emp where lenth is 6 char.
or ds wh ere en am e starts with 'S' and its
Select all rec
ename like'S__ '; ld end with 'R '.
select * from emp where y no of character but it shou
ere enam e ma y be an
Select all re cord s wh
wh ere ename like'%R';
select * from emp .
ir sa lary in emp ta ble
Count MGR and the
nt(sa l) from emp;
select count(MGR),cou
+sal as total sal .
In emp table add comm m emp;
comm, 0)) as tota lsal fro
select ename,(sal+nvl(
0 from emp table.
Select any salary <300 ere sal<3000);
p wh ere sa l> an y(s e lec t sa l from em p wh
select * fro m em
0 from emp table.
Select all salary <300 sa l<3 000 );
p wh ere sal > all (se lec t sal from emp wh ere
select* from em in descending order.
the em plo ye e gr ou p by deptno and sal
Select all ptno,s al d esc ;
l from emp ord er by de
select ename,deptno,sa ucture as emp?
ate an em pty tab le empt with same str
How can I cre 1= 2;
ect* from emp where
Create table empl as sel 00 to 2000?
where sal between 10
How to retrive record 0
e sal>=IOOOAnd sal<200
Select* from emp wher

r
li
,,
Downloaded by Sarankumar S ([email protected])
lOMoARcPSD|44483619

d dept table matches.


Select all records where d~pt no of bth emp a~where emp.deprno==dept.deptno) h all the recods but
select* from emp where ex1sts(select from dep record. How can I fetc
both have common
If there are two tables empt and emp2 , an d
common records only once?
(Select* from emp) Union (Select* fro~ empl) l?
t bles emp and emp ·
How to fetch only common records from two a
(Select* from emp) Intersect (Select* from empl) . ?
2
How can I retrive all records of emp 1 those should not present m emp ·
(Select* from emp) Minus (Select* from empl) .
Count the totalsa deptno wise where more than 2 employees exiSi.
SELECT deptno, sum(sal) As totalsal
FROMemp
GROUP BY deptno
HAVING COUNT(empno) > 2

2.6 SQLView

A view in SQL is a logical subset of data from one or more tables. View is used to restrict data access.
Syntax for creating a View,
CREA TE or REPLACE view view name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Example of Creating a View


Consider following Sale table,
oid order_name previous_balance customer
11 ordl 2000 Alex
12 ord2 1000 Adam
13 ord3 2000 Abhi
14 ord4 1000 Adam
15 ord5 2000 Alex
SQL Query to Create View
CREATE or REPLACE view sale_view as select* from Sale where customer= 'Alex'; "-
The data fetched from select statement will be stored in another object called sale_view. We can use create
seperately and replace too but using both together works better.
Example of Displaying a View
Syntax of displaying a view is similar to fetching data from table using Select statement.
SELECT * from sale_ view;
Force View Creation
force keyword is used while creating a view. This keyword force to create View even if the table does not exist.
After creating a force View if we create the base table and enter values in it. the view will be automatically
updated.
Syntax for forced View is,
CREATE or REPLACEforce view view_name AS
SELECTcolumn_name(s)
FROM table_name
WHERE condition

u,._
Update• Yicw
COIDl1l8aClfor view is

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Syntax to Update a View is,


UPDATE view-name
set value
WHERE condition; omatically.
updates base table data aut
If we update a view it also
Read-Only View access to the view.
read-only option to restrict
We can create a view with
th Read-Only Access
Syntax to create a view wi
ce view view_ name AS
CREATE orREPLACE/or
SELECT column_name(s)
FROM table name
WHERE condition with rea
d-only o read-only view. It
rea d-o nly pu rpo se, we can not Update or Insert data int
view for
The above syntax will create
will throw an error.

Types of View
w,
There are two types of vie
• Simple View
• Complex View

Complex View
Simple View
le
Created from one or more tab
Created from one table
Contain functions
Does not contain functions
a
data Contains groups of dat
Does not contain groups of

2.7 Contraints
aints on views and
itio n to con str ain ts on tab les. You can specify constr
on views in add straint as
you can create constraints lev el usi ng the ou t_of _li ne_constraint clause and con
constraint at the view as.
object views. You define the use after the appropriate ali
att rib ute spe cif ica tio n usi ng the inline_constraintcla
part ofcolurnn or ws in oracle:
som e of the con str ain ts, which can be applied to vie
Here are
aints
1. View check option constr
ts
2. View read-only constrain
3. View primary key con
straints
r aints
4. View unique key constr
e appeared
5. View RI constraints e bee n aro un d for sev era l years but the last three hav
aints on views hav query rewrite.
The first two types of constr do cle ver tric ks, particularly in the area of
help the op tim ize r ns. Declarative
more recently and exist to ery by hid ing the ent ire internal table joins operatio
plify a complex qu en below.
Oracle views are used to sim str ain ts can no w be defined against views as giv
foreign key con The problem
primary key, unique key and ine d wi th the DI SA BL E NOVALIDATE clause.
idated so they must be def
The constraints are not val defined against any view.
ws is tha t ref ere nti al int egrity constraints cannot be
with traditional vie
ing constraints on views: view so it cannot be
Oracle supports the follow ly fro m the bas e tables that make-up the
ays inheri ted dir ect
• NOT NULL: This is alw
declared explicitly .
defined upon any column
of the view.
un iqu e con str ain ts to be
acle allows for
• Unique constraints: Or
ALTER VIEW Emp_ w vie
_view_ unq
ADD CONSTRAINT emp
SABLE NOVALIDATE;
UNIQUE (first_narne) DI ntsdefineddirectlyupon the
view.
t primarykey constrai
• Primarykey: Today we can ge

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

CREATE VIEW Emp_view OVALlDATE , firstnarne)


(.d
t
PRIMARY KEY DISABLE N
.d 1 name
AS SELECT employee_t ' first -

FROM employees h ver a view has foreign key


WHERE departrnent_id == 10; . . ow directly available w ene
. • ke referential integrity ts n
• Foreign key: Foreign Y With Oracle, we can
dependencies against other base tables. impact on query performance. . k
. . I110
. . s can have a severe pie of a pnmary ey
Managing referential integrity wit view . d views Here is an exam
bypass the traditional problems assoc1a · t d w·th
1 non-constrame ·
e
constraint created on a view:
ALTER VlEW widget_ orders
ADD CONSTRAINT widget_orders_pk
PRIMARY KEY (cust_name, order_date, product_name)
DISABLE NOV ALIDATE; . f straint is useful when
Another type of constraint supported on a view · · RELy constraint Thts type O con
ts a · d ti the data relationships
queries typically access views instead of base tables, and the OBA thus ne~ds to e me . t where they may
. .
between views rather than tables. View constramts are part1cu1ar1Y use fiu1 10 OLAP env1ronmen s,
enable more sophisticated rewrites for materialized views.

Constraints on Materialfaed views:


Oracle does not enforce view constraints. However, operations on views are subject to the integrity conSlraints
defined on the underlying base tables. This means that you can enforce constraints on views through constraints on
base tables. If the materialized view is being created with ON COMMIT REFRESH specified, then the owner of
the materialized view requires an additional privilege if any of the tables in the defining query are outside the
owner's schema. In that case, the owner requires the ON COMMIT REFRESH system privilege or the ON
COMMIT REFRESH object privilege on each table outside the owner's schema.

Restrictions on view constraints: View constraints are a subset of table constraints and are subject to the
following restrictions:
• You can specify only unique, primary key, and foreign key constraints on views. However, you can define
the view using the WITH CHECK OPTION clause, which is equivalent to specifying a check constraint
for the view.
• Because view constraints are not enforced directly, you cannot specify INITIALLY DEFERRED or
DEFERRABLE.
• View constraints are supported only in DISABLE NOY ALIDA TE mode. You must specify the keywords
DISABLE NOV ALIDA TE when you declare the view constraint, and you cannot specify any other mode.
• You carinot specify the using_index_clause, the exceptions_clause clause, or the ON DELETE clause of
the references_ clause.
• You cannot define view constraints on attributes of an object column.

2.8 What is Relational Calculus?

Relational calculus is an query language which is non procedural, and instead of algebra it uses mathematical
predicate calculus. The relational calculus is not the same like that of differential and integral calculus in
mathematics, but takes its name from a branch of symbolic logic termed as predicate calculus. When applied to
databases, it is found in two forms. These are
• Tuple relational calculus which was originally proposed by Codd in the year 1972 and
• Domain relational calculus which was proposed by Lacroix and Pirotte in the year 1977
In first-order logic or predicate calculus, a predicate is a truth-valued function with arguments. When we replace
with values for the arguments, the function yields an expression, called a proposition, which will be either true Qf
false.

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Example : rking' Course would be:


s inv o lve d in list ing all the employees who attend 'Netwo
For example, step
E = 'NETWORKING'
EC T the tup les from CO UR SE relation with COURSENAM
SEL
from above result
PROJECT the COURSE _ ID lted above.
relation with COURSE _ID resu
SELECT the tuples from EMP

2.9 Tupl e Relational Calculus


true. The calculus is dependent
you wil l hav e to find tuples for which a predicate is
In the tuple relational calc ulu s a var iable who's
iab le is a var iab le tha t ' ran ges over ' a named relation : i.e.
A tuple var
on the use of tuple variables.
tup les of the relation.
only permitted values are
Example: Staff relation, we write:
ge of a tuple variable Sas the
For example, to specify the ran

Staff(S)
true', we can write:
ress the que ry 'Fin d the set of all tuples S such that F(S) is
To exp

{SI F(S)} express the query


ed fon nul a, or wff in ma the matical logic). For example, to
ll-fonn
Here, Fis called a fonnula (we all staff earning more than
me , !Na me , pos itio n, sex , DOB, salary, and branchNo of
'Find the staffNo, fNa
£10,000', we can write:

{ S I Staff(S) A S.salary> 100


00}

Example:
RY>2000 0}
{t I TEAC HER (t) and t.SALA ry
g tea cher tuples will have sala
the t upl es from TE AC HE R in such a way that the resultin
- It implies that it selects ues.
~ ple_<:f_s_elec! in~-a ran ge of v~l
grea!er ~an 20000. Thi~ is ex
_ID = 6}
{t I TEACHER (t) AND t.DEPT or
le variable with ' For All ' (?)
of teac her s ~am e ~ho wo rk under Department 8. An y tup SA LA RY
-T select all the tuples of
mple , for any range of values
sts' ( con diti on is ten ned as bound variable. In the last exa se ran ges of tuple variables
'there exi 7)
s not alte r. Bou nd variable.5 are tho
ng of the con diti on doe
greater than 20000, the meani by another tuple variable .
ng wil l not alte r if the tuple variable is replaced lay the teacher
wh ose me ani
use d DE PT_ ID = 8 wh ich me ans only for DEPT _ID = 8 disp
e on is
In the second example, you hav r All ' or 'there exists' conditi
is call ed free var iab le. An y tuple variable without any 'Fo
details. Such variable
called Free Variable.

us
2.10 Domain Relational Calcul
relation. In the domain
s, you hav e use var iab les that have series of tuples in a
In the tuple relational calc ulu domains of
var iab les but in this cas e the variables take their values from
use at
relational calculus, you will also relational calculus expression
has the following general form
les of rela tion s. An dom ain
attributes rather than tup

, dm)} m n
{dl, d2, ... , dn I F(dl, d2, ... ed
stands for a formula compos
, dm stan d for dom ain var iables and F(dl, d2, ... , dm)
where di, d2, ... , dn, ...
of atoms.

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

suppose - dept 8 is CornPut


Example: AME of teachers who work for department 8, (where
selectTCHR_ID and TCHR_N
ApplicationDetartment) DEPT ID = 10}
. tchr- name=""> ?· TEACHER J\
{<tchr_id, tchr_name=""> I <tchr_td, -

Get name of the departmentname where Karlos works: ME - K I )}

{DEPT_NAMEI< DEPT_NAME >? DEPT A ? DEPT_ID (?. TEACHER J\ TCHR NA - ar os . .


. 1 t' 1calculus is restncted to safe expressions,
It is to be noted that these queries are safe. The use domain _re~ iona . 'milar to the relational algebra.
moreoverit is equivalentto the tuple relational calculus which m tum 15 SI

Unit III

2.11 A functional dependency- A functional dependency is an association between two attributes of the same
relational database table. One of the attributes is called the determinant and the other attribute is called the
detennined.For each value of the detenninantthere is associatedone and only one value of the determined.
If A is the _detenninantand B is the detennined then we say that A fimctiona//y determines B and graphically'
representthis as A-> B. The symbols A a B· can also be expressedas B isfimctionally determined by A.
Example

The following table Illustrates A c::=::=:::> B :


A 8
1 1
2 4
3 9

4 16

2 4

7 9

Since for each value of A there is associatedone and only one value of B.
Example

The following table illustrates th.it A docs not functionally dctenninc B:

1
2 4
3 9
4 16
3 10
Since for A= 3 there is associatedmore than one value ofB.
Functionaldependencycan also be defined as follows:
An attributein a relationalmodel is said to be functionallydependenton anotherattribute in the table if it can take
only one value for a given value of the attributeupon which it is functionallydependent.
Example: Considerthe databasehaving followingtables:

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

1110 SL1ppliu1 T.ii.tie

r --- -- -~---
1:·
Silo. Sn .1m11 S.1111u~ G ly

Slll1\ll!I 20
Ankir ,~ :..rnr1111,n
I
l ,,m11 10 A11111t1-,r
J

11111 P11r1 fob lu

Ptlo. Pnatlm Colo r City

Pl
th1t
-I Rod I] a..<11,m
P2
13-0Jt
I Amrh11a1
Pl s.a..-w I
Gree"

ll lue
"
II A1111lis.1r
p,i
~ 1. Rad u Q.1dl ,1n

Th'I T,iih,19
...,.-
sue-. Poo. C'f'f

S1 P1 270

.S1 P2 JIii)

S1 Pl 700

si Pt 210

S7 P7 i'OO

Sl P2 10fl
Here in Supplier table
Sno Supplier number of supplier that is unique
Sname Supplier name
City City of the supplier
Status Status of the city e.g. A grade cities may have status 10, B grad cities may have status 20 and so on.
Here, Sname is FD on Sno. Because, Sname can take only one value for the given value of Sno (e.g. S I) or in
other words there must be one Sname for supplier number SI.
r FD is represented as:
Sno aSname
FD is shown by a which means that Sname is functionally dependent on Sno.
Similarly, city and status are also FD on Sno, because for each value ofSno there will be only one city and status.
FD is represented as:
Sno - City
Sno - Status
S. Sno - S (Sname, City, Status)
Consider another database of shipment with following attributes:
Sno Supplier number of the supplier
Pno Part number supplied by supplier
Qty Quantity supplied by supplier for a particular Part no
In this case Qty is FD on combination of Sno, Pno because each combination of Sno and Pno results only for one
Quantity.
SP (Sno, Pno)--> SP.QTY

DependencyDiagrams

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

.
· of th. e attnbute
A dependency diagram consists names an d aII functional dependencies in a given table. 1ht
dependencydiagram of Suppliertable is.
I I
I
I ,~ ---------, { _ __crily--~

Su:un~ Storus

Here, following functionaldependenciesexist in suppliertable


Sno Sname
Sname - Sno
Sno City
Sno Status
Sname - City
Sname - Status
City - Status (
The FD diagram of relation P is
The FD diagram of relation P is
Pnamc,
P.No.

Colour

Wt

Here following functionaldependenciesexist in Part table:


Pno- Pname
Pno-Color
Pno- Wt

The FD diagram of relationShipmentis


Here followingfunctionaldependenciesexist in parts table
SP (Sno, Pno)- SP.QTY
Fully FunctionalDependence(FFD)
Fully FunctionalDependence(FFD) is defined, as Attribute Y is FFD on attribute"X, if it is FD on X and not FD
on any proper subset of X. For example, in relation Supplier, differentcities may have the same status. It may be
possiblethat cities like Amritsar,Jalandharmay have the same status l 0.
So, the City is not FD on Status.
But, the combinationofSno, Status can give only one correspondingCity ,becauseSno" is unique.Th~
(Sno, Status) City
It means city is FD on composite attribute (Sno, Status) however City is not fully functio
compositeattribute,which is explained below:

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

(Sno, Status) City


X y

c,ty is· f,'D .on one proper subset .of X i.e. Sno
Here Y is FD on X, but X has two proper subsets Sno and Status;
Sno City
subset of X, but here City is FD in one subset .of X
According to 'FFD definition Y must not be FD on any proper
i.e. Sno, so City is not FFD on (Sno, Status)
Consider another case of SP table :
Here, Qty is FD on combination of Sna, Pno.
(Sno, Pno) Qty
X y
Here, X has two proper subsets Sno and Pna
one quantity.
Qty is not FD on Sno, because one Sna can supply mare than
may be supplie d many times by different suppliers with different .or
Qty is also not FD on Pno, because .one Pna
same quantities.
So, Qty is FFD and composite attribute of (Sno, Pno) a Qty.
Oth er Functional Dependencies
play a vital rule during the process .of nonnalization
( There are same rather types of functional dependencies, which
of data
Ca ndidate Functional Dependency
that includes all attributes of the table ft should also
A candidate functional dependency is a functional dependency
least one candidate functional dependency, and that
be noted that a well-fanned dependency diagram must have at
for a given dependency diagram.
there can be more than .one candidate functional dependency
Primary Funct ional Dependency
ency that is selected to detennine the primary
A primary functional dependency is a candidate functional depend
is the primary key of the relational database table.
key. The determinant of the primary functional dependency
functional dependency. If a relational database table
Each dependency diagram must have one and only on primary
tically becomes the primary functional dependenc)
has .only .one candidate functional dependency, then it automa
possible types of functio nal depende ncies:
Once the primary key has been detennined, there will be three
Description
e.
A a B A key attribute functionally detennines a non-key attribut
e.
A a BA non-key attribute functionally determ ines a non-key attribut
e.
A a BA non-key attribute functionally determines a key attribut
nal depend ency where the determinant consists of key attributes , but
A partial functional dependency is a functio
y attributes.
( not the entire primary key, and the determined consist~ of non-ke
ency where the detenninant consists of non-key
A transitive functional dependency is a functional depend
attributes and the determined also consists of non-key attribut es.
ency where the determinant consists of non-key
A Boyce-Codd functional dependency is a functional depend
attributes and the determined consists of key attributes.
independent multi valued facts about the same
A Multi-Value Dependency (MVD) occurs when two or more
R having A, Band C as attributes, B and Care
attribute occur within the same table. It means that if in a relation
A aaC ,then multi value dependency exist only if B
multi-value facts about A, which is represented as A aaB and
and C are independent on each other.
A Join Dependency exists if a relation R is equal to the join
of the projections X Z. where X, Y, z projections of
R.
between the attributes is represented as X->Y,
fR is a relation with attributes X and Y, a functional dependency
inant set and Y is a dependent attribute. Each
which specifies Y is functionally dependent on X. Here X is a determ
value ofX is associated precisely with one Y value.
n two sets of attributes. Defining functional
Functional dependency in a database serves as a constraint betwee
contributes to aspect nonnalization.
dependency is an important part of relational database design and

2.12 Normal forms

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

What is Normalization?
. h ·
. t bles •in a manner that reduces redundancy and
Normalizationis a database design hich organizes a
tee mque w
dependencyof data. . · h.
It divides larger tables to smaller tables an d rmks them usinghrelatio
h
ns 1ps.
. I d f normalization with the 1ntroduct1onof
The inventorof the re\ationa mo e I Ed Codd propos ed t e t eory o
gar . d and Third Normal Form. Later he joined with
First Normal Form, and he continued to extend theory with Secon
Raymond F Boyce to develop the theory of Boyce-Codd Normal Form.
·
Theory of Data Normalization in SQL is still being · f h F mple t here are d.1scuss.1onseven on
developed urt er. or exa ' . . rd N
· · ·
6th Nonna\ Form. However, in most practic al apphcattons, norma 1·iza f1on achieves ,ts best m 3 orma 1
Form. The evolution of Normalization theories is illustrated below-
1st Normal
Form Form
Database Normalization Examples -
Assume a video library maintains a database of movies rented out.
Without any normalization , all information is
stored in one table as shown below.
Full Names - iP hysical __ _ Movies rented Sah1tation Category
Address
lanet Jones 1 First Street Plot Pirates of the Ms. · Action, Action
No 4 Caribbean,
,-.....-,---- --.-------
4 Clash of the Titans (
Robert Phil rd
\ 3 Street 34 Forgetting Sarah Mr. Romance,
Marshal, Romance
Daddy's Little Girls
Robert Phil · s •;;:-n-:-
A-11e_n_u_e__ -+I-C..,..la_s_h.:...o_f th j'
- e-T-it-an
_s:_, _ M
_r_- ----. -A-ct-ion___ _
1
Here you see Movies Rented column has multiple values.
Database Normal Forms
Now let's move into 1st Normal Forms
lNF (First Normal Form) Rules
• Each table cell should contain a single value.
• Each record needs to be unique.
The above table in lNF-
lNF Example
FUL!. NAMES - !PHYSICAL -- MOVIES RENTID___ i SALUTfllON
1 ADDRESS
JanetJones I First Street Plot Pirates of the , Ms.
I No4 Caribbean
Janet Jones First Street Plot Clash of the Titans Ms.
I No4
Robert Phil 3n Street34 Forgetting Sarah I Mr.
Marshal
Robert Phil f 3n Street 34 --
Daddy'sllttle Girls I Mr.
Robert Phil - ~All~ Clash of the Titans ! Mr.
Before we proceed let's understand a few things --
What is a KEY?
A KEY is a value used to identify a record in a table uniquely.A KEY
could be a single column or combinationof
multiple columns
Note: Columns in a table that are NOT used to identify a record unique
lyare called non-key columns.
What is a Primary Key?
A primary is a single column value used to identifya database record
uniquely.
It has following attributes
• A primary key cannot be NULL
• A primary key value must be unique
• The primary key values cannot be changed
• The primr key must be given a value when a new record i:s,.

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

What is ~omposite Key?


.
A compo s ite key is a p nma ry key co
mpo sed of multipl e column tify a record uniq uely
In our da ta base we have le with the same name Robe s us_ed to iden
, two peop
they live in different places.
rt Phil, but
~be =~
rttJii]f"----:;'llr;:'!£.. ( •:Hllpo• II I' K •y
·"cbert Phil Mr.
A Da::ld•(s Little Girls
Rebert Phil 5111 Mr
venue Clash cf the T tans
¾ jo" f\ C14.l ......_t.. "-So ...i'-'1 A,.J.;..,11,$.s. +.
"""q_, C:.0 1W\M QI\.. c.q,

ov\ii-,.t-1!1 i.lt..ttifrJA,. <U..o<.l


Hence , we require both Fu ll N · ·
ame and Address to 1'd enffy 1 a record uniquely . That 1s a composite key ·
, l '-'
Lets move into second n orma 1orm 2NF

es
2NF (Seco nd Normal Form) Rul
• Rule 1- Be in INF
Key
• Rule 2- Single Column Primary . nd ss we partition
fi d ak • base in 2 Normalization form unle
It is clear that we can 't mo ve orwar tom e our simple data
the table above. SALUTATION
MEMBERSHIP JD ' FULL NAMES I PHYSICAL ADDRESS
First Street Plot No 4 . Ms.
(( 1 Janet Jones
2
l
I Robert Phil I 3
th
rd
Stre_:t 34
I Mr
Mr .
Ro bert Phil 5 Avenu e
3
-·--- -- - ,I
MEM385HIP ID :Mo,11Es RENTED

1 Pirates of the Caribbean


1 Clash of the Tit ans
2 Forgett ingSarah Marsha l
2 Daddy's Utt fe Girts
3 Clash of the Tit ans
member information .
tabl e into two tabl es viz. Tab leland Table2. Table l contains
We have divided our INF
movies rented.
Table 2 contains information on e 1. Records can be
new colu mn calle d Mem bers hip _id which is the primary key for tabl
We have introduced a
g membership id
uniquely identified in Table l usin
Database - Foreign Key
Foreign Key
In Table 2, Membership_ID is the
MEMBERSHIP ID MovtES RENTED
·t· Pirates of the Caribbean
( Clash of the Titans
I Forgettfng Sarah Marshal
J Daddy's Little Girls
j
. Clash of the Trtans
· ··• ··• · ·--··-· ·-•.

connect your Tables


ary key of another Table! It helps
Foreign Key references the prim
name from its primary key
• A foreign key can have a different
corresponding rows in another
• It ensures rows in one table have they aren't
not have to be unique. Most often
• Unlike the Primary key, they do
gh primary keys can not
• Foreign keys can be null even thou

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

,., 1-ore1gn K~Y


~o _____ _

'" \1E~IBERSHIPID - MOVIES~E~~ED -


1
- p~esJf the Carib~ean __
1 - · I Clash of the litans _-.
z - ---j ForgettingSdrah Mmhdl ,
- - 1 Daddy'sLittleGirls
Clash of the litans

For eign K e y references Primary Ke y rimJry key


.
f or eign K e y t.J n on IY IIJ Ve VJ
lues µresent . III P K y
It could h ave a n ame other t h an that of Pnmary e

r Prim,uy K~y

~::;;:=~;;;;:: 4 FULL Nt\llES PHYSICALADD~ESS I SALUTATION

Janet Jones Rrst Street Plot No 4 M~


-'-'--------
2 Rebert Phil 3•d Street 34 Mr .
Robert P~1I S'h Avenlll;_ Mr.
3 (
Why do you need a foreign key?
Suppose an idiot inserts a record in Table B such as . .
You will only be able to insert values into your foreign key that exist in the unique key in the parent table. This
helps in referential integrity.
11\s.e-rt"~,.! II\ T ...l,le.. 2 ~U't, l'{\~b- tt> -=IOI
:MEMBERSIIIP ID MOVIES RENTED
_Mission Impossible
101
~.J l'(\t,,,,.~s.lur tl:> 101 ts. >'<rt ~t.tt+ l1\ T .41<!, I
MEMBERSHIP ID I FULL NAMES PHYSICAL ADDRESS SALUTA l'IUN
Janet Jones 1
1 First Street Plot No 4 Ms.
2
----+--
1
Robert Phil I 3•• Street 34 ! Mr .
<{~~- Robert Phil 5
th
Avenue Mr.

~+~"S,<!,..ult fk.-GOW M f.RROR. . -n.rs. ke.-lrs. '" f'<!,f~t ,~ ..½

The above problem can be overco me by declaring membership id from Table 2 as foreign key of membership id
from Tablel (
Now, if somebody tri es to insert a value in the membership id field that does not exist in the paren t ta bl e, an error
will be shown!
What are transitive functional dependencies?
A transitive functional dependency is when changing a non-key column, might cause any o f th e ot her non- key
columns to change
Consider the table l. Changing the non-key column Full Name may change Salutation.
--- - ·····-·- ··--- - --- -- ···•· - ---···-----
MF\4RF.R<;IIIP In Fl Ill . NALH'.<; PHY~ICAL A ,nRF.S<;
SA1.1rr ,n1n 111
1. Janet Jones 1-lrstStreet Plot ~o 4 I Ms.
R:,b•r+ rhil 3'd Street 3~ I
2 MrI

3 ; R:>liP.rtPnil :A Sm Avenue 1 Mr

Let's move into 3NF


.. "'~" s.d.111:li..1

3NF (Third Normal Form) Rules


• Rule 1-Be in 2NF
• Rule 2- Has no transitivefunctionaldependencies
To move our 2NF table into 3 , we ~need to~

Downloaded by Sarankumar S ([email protected])


3NF Example
lOMoARcPSD|44483619


_MD!BE~Hrp ID
1 -- . - - FULL NAME<:
· ADDRESS
PHYSICAL - 1
SALUTATtONID
2 - J;neuo;;; First Street Plot No_4__ ::.:::2 . ·-
3 -- . RobertPhil
Robert Phil
t-t Street
I Avenue
51h
34 1
-~-.i.---:------- [S
1

MHtSERSMlP ID MOvlES RENTED


1 --- Pirates of the Caribbean
1 Clash of the ntans
2 Forgetting Sarah Marshal
2 Daddy's little Girls
3 Clash of the Trtans

1
SALUTATION ID __
SALUTATION
,'-,;.;.;....-----l

Iz Mr.
Ms.

l3
4 Mrs.
Dr.

. ur a es an d created a new table which


We have again divided O t bl .
stores Salutations. There are no transitive
. . , ence our ta e IS m ,NF. In Table 3 Salutation ID is primary key, and in Table 1
fu nct1onal dependencies and h bl • . ,.,
Salutation ID IS foreign to primary key in Table 3. Now our little example is at a level that cannot further be
decomposed to attain higher forms of normalization. In fact, it is already in higher normalization forms. Separate
efforts for moving into next levels of normalizing data are normally needed in complex databases. However, we
will be discussing next levels of normalizations in brief in the following.

Boyce-Codd Normal Form (BCNF)


BCNF is really an extension of 3rd Nonnal Fonn (3Nf). For this reason it is frequently tenned 3.SNC JNr states
that all data in a table must depend only on that table' s primary key, and not on any other field in the table. At fi,st
glance it would seem that BCNF and 3NF are the same thing. However, in some rare cases it does happen that a
3NF table is not BCNf-compliant. This may happen in tables with two or more overlapping composite candidate

keys.

datab ase Normal


If no (Fourth
4NF Form)
table insta Rulesns two or more, independent and multivalued data describing the relevant entity,
nce contai

th
t hen it is in 4 Norma l Form.

SNF (Fifth
A table Form)
s" Normal
is inNormal Rules
Form only if it is in 4NF and it cannot be decomposed into any number of smaller tables

without loss of data .

6NF (Sixth Normal Form) Proposed .


6"' Normal fonn is not standardized, yet however, it is being discussed by database experts for some ume.
Hopefully, we would have a clear & standardized definition for 6'' Nonnal Fonn in the near future...

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

BX4004 - DBMS -Unit 3-Functional Dependency-Transitive


Dependency
Bridge course (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sarankumar S ([email protected])
lOMoARcPSD|44483619

Unit III

S -
or more attributes. It has the following types in DBM
Dependencies in DBMS is a relation between two
• Functional Dependency
• Fully-Functional Dependency
• Transitive Dependency
• 1 lultivalued Dependency
• Partial Depende ncy
Let us start with Functional Dependency -
Functiona l Dependency
If the information sto red in a table can uniquely deter
mine another information in the same table, then it is
iationbetweentwo attributesof the same relati on.
cal led Functional Dependency. Consider it as an assoc
If P functionally determines Q, then
->Q
Let us see an example -
<Emp loyee>
EmpID EmpName

EOI Amit

E02 Rohit

In the above table, EmpNa me is functionally


on EmpID because EmpName can take only one
value for the given val ue of EmpID:
EmpID -> EmpNa me

The same is displayed below -

EmplD -> EmpName

Employee Name (EmpName) is functionally


dependent on Employee ID (EmplD)

Fully-functio nally Dependency


attribute
r attribute , if it is Functionally Dependent on that
An attribute is fully functional dependent on anothe
and not on any of its proper subset.
ionally
dependent on another attribute P, if it is Funct
For example, an attribute Q is fully functional
of P.
Dependent on P and not on any of the proper subset
Let us see an example -
<ProjectCost>

l
Downloaded by Sarankumar S ([email protected])
lOMoARcPSD|44483619

ProjectID ProjectCost
-
001 1000
002 5000

<EmployeeProject>
EmplD ProjectID Days (s pe nt on the project)
E099 001 320
E056
!002 190

The above relations states:

IEmpID, ProjectID, ProjectCost -> Days


However, it is not fully functional dependent.

Whereas the subset {EmpID, ProjectID} can easily determine the {Days}
spent on the project by th~
employee.

This summarizes and gives our fully functional dependency -


l{EmplD, ProjectID} -> (Days)

Transitive Dependency
When an indirect relationship causes functional dependency it is called Transitiv
e Dependency.
If P -> Q and Q -> R is true, then P-> Risa transitive dependency.
Multivalued Dependency
When existence of one or more rows in a table implies one or more other
rows in the same table, then the
Multi-valued dependencies occur.
If a table has attributes P, Q and R, then Q and Rare multi-valued facts of
P.
It is represented by double arrow -
>->

For our example:


P->->Q

I_Q->->R
In the above case, Multivalued Dependency exists only if Q and Rare independent attribute
s.
Partial Dependency
Partial Dependency occurs when a nonprime attribute is functionally depende
nt on part of a candidate key.
The 2nd Normal Form (2NF) eliminates the Partial Dependency. Let us
see an example -
<StudentProject>
StudentID ProjectNo tudentName rojectName
SOI 199 Katie

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

!Cluster Exploration
\S02 1120 IOI lie
ndency ; let us see how -
In the above table, we have partial depe
D and ProjcctNo.
The prime key attributes are StudcntI
ally dependent on
e attri bute s i.e. Stud cntN amc and ProjcctNamc should be function
As stated, the non-prim
Dependent.
part of a candidate key, to be Partial
ial Dependent.
entN ame can be dete nnin ed by StudentID that makes the relation Part
The Stud
Partial Dependent.
by ProjectID, which that the relation
The ProjectName can be detennined

Relational Decomposition
then the decomposition of a
Whe n a rela tion in the rela tion al model is not in appropriate normal fonn
o
relation is required.
into multiple tables.
o In a database, it breaks the table
s like loss of information.
mposition, then it may lead to problem
o If the relation has no proper deco
anomalies,
is used to elim inat e som e of the problems of bad design like
o Decomposition
inconsistencies, and redundancy.
Types of Decomposition

Decomp osition

Lossless Dependency
Decomposition Preserving

Lossless Decomposition
decomposition will be
info rma tion is not lost from the relation that is decomposed, then the
o If the
lossless.
lt in the same relation as it
loss less deco mpo sitio n guar ante es that the join of relations will resu
o The
was decomposed.
decomposition give the
rela tion is said to be loss less deco mposition if natural joins of all the
o The
original relation.

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

33 25 Delhi 438 Marketing


Alina

46 Stephan 30 Banga lore 869 Finance

52 Katherine 36 Mumb ai 575 Production


----- -- -
60 Jack 40 No ida 678 Testing

The above relation is decomposed into two relations EMPLOYEE and DEPARTMENT
EMPLOYEE table:

EMP_ID EMP_NAME EMP_AGE .EMP_CITY

22 Denim 28 Mumb ai
..,., -- - . -
.).)
Alina 25 Delhi
- - --
46 Stephan 30 Bangalore
52 Katherine 36 Mumbai
- -- - ---- ---- -- --
60 Jack 40 Naida
DEPARTMENTtable

DEPf_ID EMP ID
-
..''
,. . ,.-_- t "~
< _, DEPT
<I.; -
NAME , -
.) - L,"""

..... 1 ;;. '

......·r·~-
1
827 22 l Sales
438 33
------
Marketing

869 46 Finance

575 52 Production

678 60 Testing

No-w, when these two relations are joined- on the common- cohrrnn-"EMP-jD", then the resultant relation will
look like:

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

25 Delhi 438 Marketing


33 Alina

Bangalore 869 Finance


46 Stephan 30

Mumbai 575 Production


52 Katherine 36

Noida 678 Testing


60 Jack 40
sless join decomposition.
Hence, the decomposition is Los
Dependency Preserving
database.
0 It is an important constraint of the
ry dependency.
y pre serv atio n, at leas t one decomposed table must satisfy eve
o In the depend enc
must be a
into rela tion Rl and R2, the n the dependencies of R either
ed
o If a relation R is decompos ofRl and R2.
be der iva ble from the com bin ation of functional dependencies
part of Rl or R2 or must y set (A->BC). The
e the re is a rela tion R (A, B, C, D) with functional dependenc
o For example, suppos
y preserving because FD
dec om pos ed into Rl( AB C) and R2(AD) which is dependenc
relational R is
ABC).
A->BC is a part ofrelation Rl(

Normal forms
What is Normalization? redundanc y and
tech niq ue wh ich org ani zes tables in a ma nner that reduces
ign
Normalization is a database des
depende ncy of data.
tionsh ips.
er tables and links them using rela
It div ides larger table s to small with the introduction
al mo del Edg ar Cod d pro pos ed the theory of normalization
The inventor of the relation rmal Fann . Later he
and he con tinu ed to ext end theory with Second and Third No
of First Nonna! Fonn,
Codd Normal Form.
to develop the theory of Boyce-
joined with Raymond F. Boyce
le, there are discussions
nna liza tion in SQ L is stil l bei ng developed further . For examp
Theory of Data No t in
its bes
ver, in most practicalapp lications,normalizationachieves
even on 6 Nonna! Fann. Howe
th
ow-
ation theories is illustrated bel
rd
3 Norm al Form. The evolution ofNormaliz
bt Normill
Form

s-
DatabaseNormalization Example lization, all information
inta ins a dat aba se of mo vie s rented out. Without any norma
Assume a video library ma
below.
is stored in one table as shown

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

.... · ······-···· · salutation T Category


i\lt·;vks rented
Fuil N.unc s Physical
Add ress
Jan~ t Jon~-- Flrst Stre;i:Pl;t ~es of the
Caribbean,
-- I Ms.
Action, Action

7
No4
Clash of the Titans- , ------r,:; R::o:m::.a:n;::ce:,-,
Rober!Phil 1 ~getting Sarah Mr.
3" $tr,ot 34 . Romance
Marshal,
Daddy's Little Girls ___ -, Actlon
Robert Phil 1 51~ Avenue
_1_e1,sh~~•Titan, ?'_·-~-~-~--__,
Here you see Movies Rented column has multiple values .
Database Normal Forms
Now let's move into 1st Normal Forms
lNF {First Normal For m) Rul es
• Each table cell should contain a single value.
• Each record needs to be unique.
The above table in lNF-
lNF Example
-
r-FuLL NAMES TADDRESS
PHYSIC.Al. MOVIES RENTED I SAWTATION -
II
I

Ja net Jones First Street Plot Pirates of the I Ms.


No4 Caribbean
IJanetJones First Street Plot Clash of the Tltans Ms.
No4
, Robe rt Phil 3"' Stre e t34 Forge tting Sarah Mr.
I Marshal
I Robe rt Phil I 3"' Stree t 34 Daddy' s Uttle Girls Mr .
Robert Phil 1
5"' Avenue Clash of t he Titans . 1. Mr. -.........
--L....:... - -·-----·- ·-- )
Before we proceed let's understand a few things --
What is a KEY?
A KEY is a value used to identify a record in a table uniquely. A KEY could
be a single column or
combination of multiple columns
Note: Columns in a table that are NOT used to identify a record uniquely are
called non-key columns.
What is a Primary Key?

A primary is a single column value used to identify a database record uniquely


.
It has following attributes
• A primary key cannot be NULL
• A primary key value must be unique
• The primary key values cannot be changed
• The primary key must be given a value when a new record is inserted.
What is Composite Key?
A composite key is a primary key composed of multiple columns used to identify
a record uniquely
In our database, we have two people with the same name Robert Phil, but they live
in diff'ere

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

r ( Olllp .. ,,, ... K .•y

3 $tree· 34 Dadd/s Little Girls Mr.


..,.v,....e_nu~e-- Clash cf the fta ns Mr:.. __]
____ _ __.__slh_A
~¼ fMlu C.011\11110 1\. ~ c.q, 10" l\ !lA;A M,,\ 'l; 11\S. WIIAI A.U ...v..r. +o
"'1\1'{,."'_l~ i..ltA~ 4' "',<.,JW' ,.\

key.
to 1denti fy a record uniquely . That is a composite
Hence, we require both Full Name and Address
Let's move into second nom1al fom1 2NF

2NF (Second Normal Form) Rules


• Rule 1- Be in lNf
• Rule 2- Single Column Primary Key
we
simple database in 2 Normalization form unless
nd
It 1s clear that we can't move forward to make our
partition the table above
l\·1EMBERSHIP ID I FULL NAMES , PHYSl~A!:.'~RESS I SALUTATION
1
2
3
Janet Jones
Robert Phil
Robert Phil
First Street Plo t No 4
3 rd Street 34
5th Avenue
h~;: ----
Mr.

M::M3E~HIP ID I MOVIES RENTED I

1 , Pirates of the Caribbean


1 I Clash of t he Titans
2 Forgett ingSarah Marsha l
2 I Daddy's Littfe Girls
3 Clash of the Titans

Table 1 and Table2. Table 1 contains member


We have divided our lNF table into two tables viz.
s rented.
information . Table 2 contains information on movie
can
_id which is the primary key for table I. Records
We have introduced a new column called Membership
id
be uniquely identified in Table 1 using membership
(
Database - Foreign Key
ln Table 2, Membership_ID is the Foreign Key
MEMBERSHIP ID MOVIES RENTED
1 Pirates of the Caribbean I
I

1 Clash of the Titans I

2 Forgetting Sarah Marshal


2 Daddy's Little Girls
3 Clash of the Titans

! It helps connect your Tables


Foreign Key referencesthe primary key of anotherTable
ary key
• A foreign key can have a differentname from its prim
in another
• It ensures rows in one table have correspondingrows
e. Most often thof
• Unlike the Primary key, they do not have to be uniqu
not
• Foreign keys can be null even thou&h primary keys can

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

d' 1-oreign Kev


,r-
ME.\IBERSHIPID M0~1ESRE;iTED
1 Piratesof the Caribbean
1 Clash of the Titans

_,, ____ Clash of t~s


ForgettingSarah Ma~ial
D;ddy'sLittle Girls
--
For-eign Key refer-ences Primar-y Key . . kt:
for-eign Kt:y can only havt: valut:s 11r-t:sent_m pnr';c:.-y Y
It could have a name other than that of Pnmar-y Y

r fZf? Prima.-y K ey

SA LUTAT IO'I
MEMBERSHIP 10 I FULL N,\MES PHYSICAL ADDR ESS
, Janet Jones First Street Plot No 4 M s.
2 Robert Ph il =1£ Strcct34 Mr.
--·- -
3 J. Robert Ph_!!
---- Avenue
---- Mr.

Why do you need a foreign key?


Suppose an idiot inserts a record in Table B such as
You will only be able to insert values into your foreign key that exist in the unique key in the parent table.
This helps in referential integrity.

11\s.~"' ~J. )J\ T.J.le, 2 ~e...l:.- U> ==-IOI


MEMBERSHIP ID I MOVIES RENTED
101 . I MissionImpossible

+IY\-.b_--s.k•rt!> m,
j; .. 1s. rt..+ r,s.w .... T4te- 1
MEMBERSHIP ID I FULL NAMES : PHYSICAL ADDRESS 1
SALUTATION
1 lan et Jones First Street Plot No 4 : Ms.
2 Robe rt Phil 3 rd Str eet 3 4 I Mr.
th
3 Robert Phil 5 Avenue l Mr-.

I'· L.
The above problem can be overcome by declaring membership id from Table2 as foreign key of membership
id from Tablel
Now, if somebody tries to insert a value in the membership id field that does not exist in the parent table, an
error will be shown!
What are transitive functional dependencies?
A transitive functional dependency is when changing a non-key column, might cause any of the other non-key
columns to change
Consider the table I. Changing the non-key column Full Name may change Salut~tion.
FULL NAIJIES PHYSICALADDRESS SA.LUTJo.TlON,
1 Ja tJones
2
3

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Let's move into 3NF

3NF (Third Normal Form) Rules


• Rul e 1- Be in 2NF
ndencies
• Rule 2- Has no transitive functional depe
need to again divide our table .
To move our 2NF table into 3NF, we again
3NF Example
I
SALUTATION ID
IMEMsER.S_H_:Pm
-- FuLL NAMES
------+- --- ----- PHYSICAL ADDRESS
2
1
-------
JanetJones
----~ FirstStreetP!otNo4
'--
____________
1
Robert Phil 3rd Street 34
--------
_______ ---
1
2 ... th 1
3
.__ Rob Phil----~-
--ert-- ; 5 Avenue ;._,;__

[ MDl3ERSHIP ID MOVIES RENTED

1 Pirates of the Caribbean


1 Clash of the Titans
Forgetting Sarah Marshal I
2
2 ---- ~ Daddy's Little Girl~ ___ --1
3 Clash of the Titans

SALUTATION ID SALUTATION

1 Mr.
2 I Ms.
3 · Mrs.
Dr.

There are no transitive


have agai n divid ed our table s and crea ted a new table which stores Salutations .
We
ary key, and in Table
is in 3NF . In Table 3 Salutation ID is prim
functional dependencies, and hence our table
cannot further be
e 3. Now our little example is at a level that
l Salutation ID is foreign to primary key in Tabl
alization forms.
alization. In fact, it is already in higher norm
decomposed to attain higher forms of norm
databases.
rts for mov ing into next leve ls of norm alizing data are normally needed in complex
Separate effo
.
ls of normalizations in brief in the following
However, we will be discussing next leve

Boyce-Codd Normal Form (BCNF)


ly termed 3.5NF. 3NF
Form (3NF). For this reason it is frequent
BCNF is really an extension of 3rd Normal
r field in the
all data in a table mus t depe nd only on that table's primary key, and not on any othe
states that
in some rare cases it
. At first glan ce it wou ld seem that BCN F and 3NF are the same thing. However,
table
two or more
mpliant. This may happen in tables with
does happen that a 3NF table is not BCNF-co
overlappingcompositecandidatekeys.

l ·
· ce containstwo or more, independentand multiva
Porm.
Downloaded by Sarankumar S ([email protected])
lOMoARcPSD|44483619

SNF (Fifth Normal Form) Rules . decomposed into any number of smaller
A table is in 51" Normal Form only .if it. .is .m 4NF and it cannot be
tables without loss of data.

6NF (Sixth Normal Form) Proposed . b erts for some time.


1h
· bemg
· 1s
6 Normal Fonn is not standardized,yet however, it · d1scussed by data ase exp
. . fior 61h Normal Form in the near future...
Hopefully, we would have a clear & standardizeddefimt1on

MultivaluedDependency
o Multivalueddependencyoccurs when two attributes
· · ta bl e are m
ma · dependent of each other but, both
depend on a third attribute.

o A multivalued dependency consists of at least two attributes that are dependent on a third attribute (
that's why it always requires at least three attributes.
Example: Suppose there is a bike manufacturercompany which produces two colors(white and black) of
each model every year.

BIKE_MODEL MANUF_YEAR ;·- COLOR

M201 I 2008 White


- - ----
M200I 2008
---
Black

M300I 2013 White

M3001
- - --- --
2013 Black

M4006 2017 White


--·---
M4006 2017
-- ---- .
Black

Here columns COLOR and MANUF_ YEAR are dependenton BIKE_MODELand independentof each
other.

In this case, these two columns can be called as multivalueddependenton BIKE_MODEL.The


representationof these dependenciesis shown below:
I. BIKE_MODEL - - MANUF_ YEAR
2. BIKE_MODEL -+ -+ COLOR

This can be read as "BIKE MODEL multideterminedMANUF YEAR" and "BIKE MODEL
multideterminedCOLOR". - - -
n al form (4NF)

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

es of B exists, then the relation will


a single value of A, multiple valu
° For a dep end ency A-+ B, if for

I Example
be a multi-valued dependency.

STUDENT

COURSE HOBBY
STU ID

Computer Dancing
21

Math Singing
21

Chemistry Dancing
34

Biology Cricket
74 ~--j
( Hockey
59 Physics
t entity. Hence,
e is in JNF , but the COU RSE and HOBBY are two independen
The given STUDENT tabl
RSE and HOBBY.
there is no relationship between COU and Math and two
, a stud ent with STU _ID , 21 contains two courses, Computer
In the STUDENT relation
STU_ID, which leads to
and Sing ing. So ther e is a Multi-valued dependency on
hobbies, Dancing
unnecessary repetition of data .
es:
, we can decompose it into two tabl
So to make the above table into 4NF
STUDENT_COURSE

COURSE
STU_ID

Computer
21
( Math
21

Chemistry
34
Biology
74

Physics
59
STUDENT_HOBBY

Dancing

Singing

Dancing

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Cricket
74

59 I lockey

Fifth normal form (5NF) . · in dependency and joining should be


0 A relation is in 5NF if it .is ·,n 4NF and not contains any JO I

lossless. bl possible in order to avoid


0 SNF is satisfied when all the tables are bro ken 1'nto as many ta es as
redundancy.
o 5NF is also known as Project-join normal form (PJ/NF).
Example

SUBJECT LECTURER SEMESTER

Computer Anshika Semester I

Computer John Semester l

Math John Semester l

Math Akash Semester 2

Chemistry Praveen Semester I

In the above table, John takes both Computer and Math class for Semester I but he doesn't take Math class for
Semester 2. In this case, combination of all these fields required to identify a valid data.

Suppose we add a new Semester as Semester 3 but do not know about the subject and who will be taking that
subject so we leave Lecturer and Subject as NULL. But all three columns together acts as a primary key, so
we can't leave other two columns blank .

So to make the above table into 5NF, we can decompose it into three relations PI, P2 & P3:
Pl

Keep Watching
Competitive questions on Structures in Hindi00:00/03:34

Semester I
Computer
Semester I
Math

Chemistry
Semester2

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Computer Anshika

Computer John

Math John

Math Akash

Chemistry Praveen

P3

SEMSTER LECTURER

Anshika
Semester 1
John
Semester 1
John
Semester 1
Akash
Semester 2
Praveen
Semester l

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Chapter 2: RelationalModel
t Structure of Relational Databases
Fundamental Relational-Algebra-Operations
Additional Relational -Algebra-Operations
Extended Relational-Algebra-Operations
Null Values
Modification of the Database
Chapter 2: Relational Model

Database System Concepts, 5'" Ed.


~Uberschotz. Korth and Sudorshan
See www .db-book .com tor conditions on nM1se
11 O.~t>ue Systtrn ConotPlS · ,. &tltk>n, June 15. 2005
II
Koma and~

Basic Structure
t- Exampleof a Relation

accounLnumber branch_nmne balance


Formally, given sets D,, 0 2,
0 1 X 02 00
X ••• X
• •• • D0 a relation ris a subset ot

Thus, a relation is a set of n-tuples (a,, St, ...• a,,) where each a, D,
A-101 Downtown 500 E

A-102 Perryridge 400 Example : If


• customer_namea {Jones, Smith, Curry, Lindsay, •••}
A-201 Brighton 900
r
Set of all customernames •1
A-215 Mianus 700
• customer_streeta {Main, North, Park, •.•} r set of an street names•/
A-217 Brighton 750 • customer_ city a {Harrison, Rye, Pittsfield, ..• } r set of all city names •1
A-222 Redwood 700 Then r = I (Jones, Main, Harrison),
A-305 Round Hill 350 (Smith, North, Rye),
(Curry , North, Rye),
(Lindsay, Park, Pittsfield) I
Is a relation over
____customer_nsme
_.. ___ ,,._x custome,:_s118et
,._ x customer~c:f!X
-~ua

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

AttributeTypes RelationSchema
Each attribute of a relation has a name A,. A,,, ..., A" are attributes
The set or allowed values ror each attributeis called the domain of the
attribute
R = (A,. A,,, ..., A" ) is a relation schema
Attribute values are (normally)required to be atomic; lhat is, indivisible
• E.g. the value of an attributecan be an account number, Example:
but cannot be a set of account numbers Customer_schema= (customer_name,customer_street,customer_cily)
Domain is said to be atomic if all its members are atomic
The special value null Is a member of every domain
r(R) denotes a relation ron the relation schema R
The null value causes complicationsIn the definitionof many operations
Example:
• We shall ignore the effect of null values in our main presentationand
consider their effect later customer(Customer_schema)

.___°'-otl-~fdllon. ..... ,,._

Relation Instance - - Relationsare Unordered


i
The current values (relationinstance) of a relation are specifiedby a Order of tuples is irrelevant(tuples may be stored in an arbitra,yorder)
table
Example: accountrelation with unordered tuples
An element tot r is a tuple, representedby a row in a table

attributes
accounLnumber branch_1UZme
A-101 Downtown
mm
~(or columns)
I - I A-215 Mianus 700
-
customer name customer streerl custome::

Jones
A-102 Perryridge 400
Main Harrison
Smith Nor1h Rye tuples A-305 Round Hill 350
Curry
Undsay
Nor1h
Park
Rye
Plttslletd
Pc or rows)
A-201 Brighton 90Q
A-222 Redwood
A-217

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Database The customerRelatlon


A database consists of multiple relations custonter_,ia111e customer_str!et rnstomer city
Inform ation about an enterprise Is broken up Into parts, with each relation
Adams Spring Pittsfield
storing one part of the information
Brooks Senator Brooklyn
acco unt : stores information about accounts
depositor: stores Information about which customer Curry North Rye
owns which accoun t Glenn Sand Hill Woodside
customer: stores information about customers Walnut Stamford
Green
Stori ng all Information as a single relation such as Hayes Main Harrison
bank(account_number, balance, customer_name, ..)
Johnson Alma Palo Alto
results in
Jones Main Harrison
• repel1hon of mformahon
Lindsciy Park Pittsfield
e.g.,if two customers own an account (Whal gets repealed?)
Smith North Rye
• the need for null values Stamford
Turner Putnam
e.g., lo represen t a customer without an account Princeton
Nassm.1
l Normalization theory (Chapter 7) deals w1lh how lo design relational schemas
Williams

~SyslemCoN:::.PlS • ~Edltb'I.Juna tS,. 20UJ 2.cnumbtn-


11
<6111)1rscha2.KOl1hand$f.tdafshan DIIUib&NSys\lfflCorceptt•,-.Edlllon.June 15. 2005

l Keys
The depoSltOrRelation
LetK~R
K is a superkey of R if values for Kare sufficient to identifya unique tuple of
each possible relation r(R)
• by "possible r • we mean a relation r that could exist in the enterprisewe
customer name accounLnwnber are modeling.
Hayes A-102 • Example: {customer_name,customer_stree~and
Johnson A-101 {custome,:__name}
A-201 are both superkeysof Customer,ii no two customerscan possiblyhave
Johnson
A-217 the same name
Jones • In real life, an attribute such as customer_ldwouldbe used instead of
Lindsay A-222
customer_nameto uniquelyidentify customers,but we omit it to keep
Smith A-215 our examples small, and instead assume customernames are unique.
Turner A-305

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Foreign Keys
t Kis a candidate key if K is minimal
Keys (Cont.)
A relation schema may have an attribute that corresponds to Iha
key of another relation. The attnbute 1s called a foreign key
• E.g customer name and acc:ount_numberattnbutes of deposito,
Example: {customer_name}is a candidate key for Customer, since it for~ign keys to customerand accountrespectively
is a superkey and no subset of it is a superl<ey. • Only values occurring in the primary key attnbute of the referenced
Primary key: a candidatekey chosen as the principal means of relation may occur in the foreign key attnbute of the referencing
identifyingtuples within a relation relation.

• Should choose an attribute whose value never, or very rarely, Schema diagram
n,.stu,M'T
changes. /mmt."ff
• E.g. email address is unique, but may change ,'r,111td1-ltt l~
lorn11Jw.:1!y
i/!,."-,'/':'-

lo,m

',mn1..!t-lL!:Z:k~
il""-1Urtl
l
~KcrflandSUmrlhan ~~Coraps • !-&Hcrl..U- 1.S. .:om
SVstom ConctPlS·,-Edition. ..11.N 1~ 2005

t Query Languages t- Procedural language


RelationalAlgebra
Language in which user requests informationfrom the database.
Six basic operators
Categoriesof languages
• Procedural • selectG
• Non-procedural,or declarative • project:TI
"Pure• languages: • union: u
• Relationalalgebra • set difference:-
• Tuple relationalcalculus • Cartesianproduct: X

• Domain relationalcalculus • rename:p


Pure languagesform underlyingbasis of query languagesthat people The operatorstake one or two relationsas inpulS and producea raw
use. relationas a result.

__J
1. ii
. 1-

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Select Operation- Example


Relation r
t Nolalion: a ,J/1
Select Operation

• pis called !he selection pndlc:ale


• Oellned as:
a a 1 7
a,(1' - [t I rE rand .o(t.11
a /3 5 7
W!lenl p is a formula 11 propositionalcalculusconsisllng r:J ..,_
/3 /3 12 3 canned9d by ,. (and). v (or).~ (nal)
B B 23 10 Each tarm IS one al:
<attribute> op <all!ibuhl> or ceonllant>
wt>era QP is one at: • "• >, :t. <- s

• Example o/ selection:
a_ ___ {ao:ounl)

a a 1 7
p p 23 10

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

_-l. Union Operation- Example Union Operation


Relations r, s:
Notation: ru s

[] rn
u_W
Defined as:
r us= {/ I t e ror t e s}
For ru s to be valid.
s 1. r, smus t have the same arlty (same number of attributes)
r

2. The attribute domains must be compatible (example: 2"" column


of , deals with the same type of values as does the 2""
column of s)
rus:

rn
Example: to find all customers with either an account or a loan
2
ncus,,.,,.,_nam,, (depositor') u nC"""'"8r_name (bo"ower)
1
3

~SyS1emCorc:iepq.5--Edftlo!\June,1s_ 20Cl5


"'-"Silbetsc:h-.z.Korth Otld SudDfshan OabbaseSystem Concepcs• S-- fdlUon, Jurw 15,, 2005

Set DifferenceOperation- Example


Relations r, s; Set DifferenceOperation
GE] GE] Notation r - s

[] 2
1
ITT
u_W
s
Defined as:
r-s = {ti te rand t II! s}

Set differencesmust be taken between compatible


relations.
r -s: • rand s must have the same arity
GE] • attributedomains of rand s must be compatible
r:r,i
w_J

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

i _. cartesian-ProductOperation- Example Cartesian-ProductOperation


Relations r, s: Notation rx s
Defined as:
a 10 a r x s • {t q I t e ra nd q e s}
/3 10 a
/J 20 b Assume that attributes of r(R) and s(S) are disjoint. (That is, R /'"\ S • .0).
r 10 b
If attributes of r(R) and s(S) are not disjoint, then renaming must be
s
rx s: used.

a 1 a 10 a
a 1 /3 10 a
a 1 /J 20 b
a 1 y 10 b
/J 2 a 10 a
/J 2 /3 10 a
/J 2 /3 20 b
11 2 V rn h

o.obeM 5Yswn Corc»pCs • !P" 6d1Uon, June 15, 2005


Ii
,~ ber9c:NCZ.KonhandSudat9Nf'I DN1:1aNSystefflCorapta • S-6dlllon ,.knl 15, 2005

Compositionof Operations Rename Operation


Can build expressions using multiple operations
Allows us to name, and therefore to refer to, the results of relational-
Example: o.-.c(rx s) algebra expressions.
• rxsl A~I~1c--.-l--,-o1--,£I
8
Allows us to refer to a relation by more than one name.
Example:
a 1 a 10 a
a 1 /J 10 a p x( E)
a 1 /3 20 b
a 1 y 10 b
a 10 a returns the expression E under the name X
/J 2
/3 2 /3 10 a If a relational-algebra expression E has arity n, then
2 /3 20 b
2 V 1n h Px(A,.Az,- .A,,l(E)

returns the result of expression £ under the name X, and with the
attnbutes renamed to A,. Az, ... . , A•.
a 1 a 10 a
/J 2 /J 10 a
/J 2 /J 20 b

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Example Queries
t. Banking Example
branch (branch_nsme, branch_city,assets)
Find all loans of over $1200

customer (customer_name, customer_stroet,customer_city) (Jamount> 1200


(loan)
account (account_number,branch_name,balance)
ach loan of an amount greater than
loan (loan_number,branch_name,amount) Find the loan number tor e
$1200
depositor(customer_name,account_number)
IT1oan_number (<Jamounl > 1200 (loan))
borrower(customer_name,loan_number)
Find the names of all customers who have a loan, an account, or both,
tram the bank

ncvstomer_name(borrowe,1 v ITcvstomer- namt1 ( deposi tof1

Ii
Kor1h and Sudl,,t,an DNba• 9r,am Concept.t • ,- Eddon. Jucw 15, 2005

Example Queries ExampleQueries


Find the names of all customers who have a loan at the Perryridge Find the names of all customers who have a loan at the Perryridge branch.
branch.

fL:ustome,:_name( (J branch_name-·Perryridge· • Query 1

( O'bonower.loan_number• loan.Joan_numbe,(borrowerx loan))) I"Ia.stomer_name( crbranch_name• "Penyridge" (

Find the names of all customers who have a loan at the <1txmower.loan_number• loan.loan_number(borrowerX loan))}
Perryridgebranch but do not have an account at any branch of
the bank.
• Ouery2
ITeus1ome,_nam«, (<Jbranch_name • "Perryridge"
flcustomer_name(C11oan.1oan_m.m11er• bomlwer.loan_numblr(

---•______
x loan))) -
(<Jl:lcJnuwet-.loan_number•loan.loan_numt,e,(borrower

nCl.lltomltr__,,.(depositor)
.. ,.,_

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

I
I
l, ExampleQueries ·( Formal Definition
Find the largest account balance A basic expressionIn the relational algebra consists of either one of the
• Strategy: following:
Find those balances that are not the largest
• A relation In the database
- Rename account relation as d so that we can compare each
account balance with all others • A constant relation
Use set di~erenceto find those account balances that were not found Let E, and E, be relational-algebraexpressions;the following are all
1n the earlier step. relational-algebraexpressions:
• The query is:
• E 1 u E2
ITba,ance(account)- ITaccount.balance
(craccount.balance<d .balance (account x pd (accounO)) • E1 x E2
• <lp (E ), P Is a predicate on attributes in E 1
1

• TT.(E,), Sis a list consisting of some of the attributesin E1

Dlltabae 9'fSWTICo,apu • Edl\k>n.Junt 15, 31(15


Ii
<'SllbM'sdnU,Kor1h and 9.Kl;lnhan
~~and SudlnfWI

Set-IntersectionOperation
AdditionalOperations
Notation: rn s
We define additional operations that do not add any power to the
Defined as:
relational algebra, but that simpllfy common queries. rns:{tlferandtesl
Assume:
Set intersection
• r, s have the same arity
Natural join
• attributesol rand s are compabble
Division
Note: rn s • r- (r-s)
Assignment

Downloaded by Sarankumar S ([email protected])


lOMoARcPSD|44483619

Natural.Joinoperation
Set-IntersectionOperation- example
i. • Notation: r IXl s
Let rands be relations on schemas Rand S respectively.
Relation r, s: filJB /A IBI Then, r IXl s is a relation on schema Ru S obtained as follows:
a
a
1
2
ial7l • Considereach pair of tuples t, from rand t5 from s.
p 1
• If t, and 1 have the same value on each of the attributes in R n s, add a
s 5
tuple t to the result, where
rr. s
• t has the same value as tr on r

• I has the same value as ts on 5

Example:
R= (A, 8, C, 0)
S=~ 8, D)
• Result schema = (A, 8 , c, o, E)
_ • r sis defined as ·
OlltDbutSystam Con:::epta,,.. £dl1lon.June 15, 2005 System Conc::tptS • 5"' Mitton. J\I,. lS,. 200$ • ,~ 2.~

t ...
NaturalJoin Operation-~ample
• Relationsr, s:

a
p
1
2
a
y
a
a
l
y 4 p b
a 1 a
0 2 J?_
s
r t>(ls
A B C

a 1 y
a 1 r a
o 2 b

i\
t,t
,.f
Downloaded by Sarankumar S ([email protected])

You might also like