BX4004 - Database Management System
BX4004 - Database Management System
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.
•
•
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.
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
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
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
u,._
Update• Yicw
COIDl1l8aClfor view is
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
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.
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.
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
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.
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
4 16
2 4
7 9
Since for each value of A there is associatedone and only one value of B.
Example
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:
r --- -- -~---
1:·
Silo. Sn .1m11 S.1111u~ G ly
Slll1\ll!I 20
Ankir ,~ :..rnr1111,n
I
l ,,m11 10 A11111t1-,r
J
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
.
· 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
Colour
Wt
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
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,.
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
r Prim,uy K~y
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
•
_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
1
SALUTATION ID __
SALUTATION
,'-,;.;.;....-----l
Iz Mr.
Ms.
l3
4 Mrs.
Dr.
keys.
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
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
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
Whereas the subset {EmpID, ProjectID} can easily determine the {Days}
spent on the project by th~
employee.
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 -
>->
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
!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.
The above relation is decomposed into two relations EMPLOYEE and DEPARTMENT
EMPLOYEE table:
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,"""
......·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:
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
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
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
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.
+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
SALUTATION ID SALUTATION
1 Mr.
2 I Ms.
3 · Mrs.
Dr.
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.
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.
M3001
- - --- --
2013 Black
Here columns COLOR and MANUF_ YEAR are dependenton BIKE_MODELand independentof each
other.
This can be read as "BIKE MODEL multideterminedMANUF YEAR" and "BIKE MODEL
multideterminedCOLOR". - - -
n al form (4NF)
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
Cricket
74
59 I lockey
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
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
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
Basic Structure
t- Exampleof a Relation
Thus, a relation is a set of n-tuples (a,, St, ...• a,,) where each a, D,
A-101 Downtown 500 E
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)
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
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
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
__J
1. ii
. 1-
• Example o/ selection:
a_ ___ {ao:ounl)
a a 1 7
p p 23 10
[] 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
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
[] 2
1
ITT
u_W
s
Defined as:
r-s = {ti te rand t II! s}
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
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
Example Queries
t. Banking Example
branch (branch_nsme, branch_city,assets)
Find all loans of over $1200
Ii
Kor1h and Sudl,,t,an DNba• 9r,am Concept.t • ,- Eddon. Jucw 15, 2005
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)
.. ,.,_
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
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
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
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])