You are on page 1of 101

Module-: |NTRODä CTiON to DATABAsE SysTtMs

Dota 9 is aw and isolated/ norganized facts Jhat con ke


ecOrde d (in Jhe form f text , Audio, video, mage etc)
Ly bata. needs to be þooces sed Oheol se it is o6 no use
Ly Infosmahon ! pooce ssed, meoning fl and (Usabe data
Ly Data and informahon Used intenchanyelouy
L eg' In Youhube clalciba se, Jhene milion o6 ideos. Pertson
A cd B' have eXam lomomw and Ohey e Se rchin DBM
Videos on Youuloe . Jhy got 'x', 'y, z ' channel, an Sugses ha
'A' is u0atthtng tom x is oalehin from
fo A! X in (oYinOicn Y, is data
for 8! Y is nGomah on X, Z is data
for Youhbe. evey hing dak only
Database: Database is Collechon Telated data Jhat

Tepresents SOme world enh hes.

L Meaning of el ated data ta Ke an eXample IRCTC, it hay


OLon dalabase. wshen you log in to IRCTC wht
inkormahons oi40 RCTC hawe Trains inkormchan pasengen
in foYmakcn , hotel, in (omahon in fomain. No w Buses

Passenge infomahcn contin in fomahon


Jhose passengeas sho have booked icket any ine,
lgcTC
not have infomahn about cUe pSSenGens
IRCTC Contun nly Jhe in ormahon
Anothen example,
Jhose horel usiich has Some tied
O6
not Con)oin infomahen oo l l hotely e .
Dotabase 0s not Colleci cn Ob any data 9t should be
Collechon related daas So Jha We. Can Temeve
cnd Solve Some
Some infomahon feChvely prble
Database is used o Teeve , in sent cand delote Jhe
cdaB estienty Cmodity also).
Newspoper is iso collec hcn o clata but not dalba se
because you cant mociy Jhe cdata about an eniy.

typialy stored . elechenically (Strucwyed/unstuchwveo)


Jhat 9 dijfeont
Comforts
Iheydata^s. tor
o6 an dalabase
oftype exeniv
daabas
Cdalabano)Cmpony
se. pes Dalabase
is
sualuy
danohed time
databa
elated ty datebase.
(dajabane)
Pixabey
daalsane) clireent gg .sysem
response
steret Aateu
se,Oononls this NOTE applicakona
pi asey
( Seng enter Conjainkand study Jhe Stoved
isSt Cenralized maÀntained
incye an
Youkube Jheir
undeas Such
il
each tho. Sevenol ’
update
’ We Oñented
dalabase
: data
the
fechin
consisBency
is Datcbase’l
daabane! all :databaseacceSS
databane!
database
dalclbane dalabase
dolcbase: understand dhrugh to
daleban database
database: at
dalabase
(image.Cdaa)
Song dalabano.
daabase Nor
eay
Videos
(daka)
daJa) Jhis Hieraschical daa
to
dala
fomm
is Cenraized
USers Poos!
Dala
a Nehuoyk ocah
ons
hashas wncdersood Cenhraiged
) Disibuted
Relahonal biey
a has databases
!. NOSQL
cloudObjec
stores
the
CONS:
hashas flipKut
faobookNetflix
lwhen
the lkeTC Having us
OLA
Let
i) j v) V) Vi) và) Vit)
L
and
heued
dis
Cahon
muni
Com (tupla/ecord) but
is
Seweel
velahonal
data
model 1970. wrde
ange
of
dfenent Heteogeneows of
in
diffeant form
in Docunmon-
omenled
databane.
enform Cselahon!
togeth fovm
tabulan
Cenhalized dasabase
in
aning
anons o res.
doabace
Gaph
systemn data sloing sto
cted
Conne Key
Vaue
storage..
of mn
bured
disbi distibuted use
Same.
ArpliCc«hon forme Stoyetables Colu
On for
used databQ9e.
Unike Same
operahng
handuoave. cand the not
only vau \ide
based
CUle
dalabane invented key
Jhe Columy
(atthbute
) Call
we
isdata,
:dalabase organlzahon Homoseneo
us Relakonal
database. : lahonal
daBabases Same
Dalabase stoes
data @ (D
daa
in
talabase elahonal
A dd
technically
Co re
Distibuked
on system
A
execas
E.F.
Typos
daabase Jhe
se
an
StoTes Sal L
not
a
itL
Jhis
No L>
i)
V) Cloud dabae, , A daoba se uhene ddata is Slored n
Vixal enionmon t and execulis Uen (ho cloud
Compubng ystems/ piatfma. S- pronce use1
S+
Vamos Cloud Compubng Sesvio, (SaaS
vancus ( PaaS, laa Se)
for accening tha database, cloud platfo e.
Amozon web enwico, (Aw)
Micosogt CIZZUYe

Cioogk cloud SQL et


v)
vi object -oniented database Jhe type ot database that
Uses object-based dadata modaly
moolely ppronch for storing daa
in dotaloona. ysler

vi) HiesaYchical dalabase : # selk shudy

vi) Nehoyk databaue # Selk Shudy.

. Why Use databa se ?


Ly Databases ase ed able to Stoye Vast mo, of beCords in
L ince di bly simple and quick to l9cate dala e(fecive man
grs Simple to add neuw dota, moci4y or delet also
LDala Can be easiy Seonched by datalsase techinques
ing, binau Seanch et.
indexing
yDae Can be and easily Sorted
qyickiy
L Daabase pronce. Secumlý of dala.
3

daba)
Having undensiood Jhe Concept o6 database (collecion of velahed
and ushy do We need database (fer esfcienty Solviy a problem
Nlow We,
oiu shedy what is DBMS.

DBMs): - Shands for daabace managemon ysk


also se fenied an daabase Syslems.
-the database.
St is SOtuoaie used to manaye
examples ! Oyacle MySQL, lBM DB 2 etc.
Now
gain,
hay to mangye
IRCTC caabase ue have, DBMS tach Compony uo20 hawe Jheiy
han to manaye
Netflix s database we hcves, DBNS database and to manaye
to manye Jhe. ewey company
flipKant han database we hove DBS wiee hawe Jheir Own dalcbane
manapemor sysem (DBMS)

B Data
Data
M Daa
(usen Daba
4sey Comnnicate to S Daba
bBMS interfac. for
efhient and faster
Diff Progpam
Cocle to in sert Daabase
way os Guil th Aling his dalet, update
Crd quoy dateubane
Tequivemont
infovmahon

prvides Qn
intonface to þei7otm vasous operchbny
liKe daabase Creahon, Serinr data updakns, doleiny data,
L poonden rolechon nd Secuihy to Jhe databane
DeMS’sohuane /managemont of daabase
Allows usen the follootng tas Ks.
(a)
CDaa. definahon : Used for cieahon , modiffcaion cand
that doGnes dhe
definihon -hat 7anizohen t
Temova o
Ihe daa
(o) Dala up daion.. Used for insenhon modifaakon ond cdeleion
aChual dala database
Tehievent data fom cdakaban
Daa retieval: used for

(a) Usen Adminsahca: used for monibin and regisheing


Usens matainy dala integiy, dalabase SecumlG ek.

ReLATIONAL DATABASE MANACtMENT sysTEM ( RDBMS

L All MOdean bBMS hke SQL, MYSQL ^eve , lBs DB2 yacle and
micYosot aC Ces based On ROMS
Based on, selahonal data model DBMS for veahonal(table)
L Al opeyahono liKe in Sert dolota "ane þergomed on
tables
Data is Depre Sented in tesm ok tuply CoLos) n RDBMS
Due. o a Collechon of oYganized Ser oG tables, dae
Can be accened eanily in RDBMS
4

Temin ot RDBNS Columns oy Atibute &

Records
Emp_i E Name Post Salay
tuples Rahul Cleik D0,000
E2
Rows
or Kapil Managen 80, o00
E3 Mukesh clenk 20, o00
E4
Manoj leon Lo, od0
E5
Radha 80, o00
E6
Shweta Manajea
Clik 20, o00

whole Table is called Relahon',


Rouws' called uples Re Covds.
Columns' CUle Callod AHilouheg.
Jhe. Telahon a 4 (n0.06 athibuhes)

Ihe Yelohon = 6 (no. of tuples)


Candinatiy of
Next topic is
File System Vs DBMS
File syshem is
Gke., abasicny
me dium cny o! aTmonging the files in a
shorage
had disk eg. NTEs, EXT
y
Before
File
DBMS
b ased
toadihonal
file syskem was used.
System Wete an eatly aHempt o Compuhen3e Jhe
manul Syskem. Also called Somahme FPs CRle proce sysem)
Vsen USen 2 Usen3
|Roli No)
Stud- fle Sub ile Resutt fle Nam
LCouy Lavecu
Roll No
Name Name mals
CouYse Ld
Credit
DBMS
U
Sen 2
Vsenl
eg- 4 ile syslem. DBMS.
Some impor tant diffeenc b/u Jhem:
Data Tedundoncy and Consiseny:
File Procenj Syslem (FPs) ’ Shing Same daa if. Gomats
and in diff progran'y Canjuage is þossible.
DBMS ’ Conols Kedundanuy in ado i on Swes a
Cot o Stoaye spaca.
it) Conc uvvency !
L mulhple USo1S
accomins tro clata Jhe. Samo me
Can Led toinconsisleny Fps but Jhero ane
Sore prorocols cdegined in DBMS
for
FPs. avoldinN
in conss.
Jhen is Such pobcola in
Secuiby'
L DBNS proiden Secuny
Role ba sed pe1m)ssjor, Ge have in DBMS
A Ccerm Conhoe prorocals
We CAn acce big amont 0f data and ufich
datc as pen youY wi' sh.
All Jhe info. o)l not be Visible to VSeny in D&MS.
File sy stem is handle by opevaing yshem
Which Paicen Secumw at al
iv) Data independence: A fPs does not þende data independeno
utile DBMS onces tuo ty pe, ot Dia in dopencdence
physical data indapendena
data indopendene
v)
Digpeulky in
Acaig data:
DBMS: Random quony
F Ps
Can give instont owtput
Seanch Youvsel 6 (Usen wi! Seaclh mGnualy)
w) Inteçhy Conshraints difhi cutt to apply in Fps
easy to opply
DBMS
What are Data Models in DBMS?

Data models in DBMS help to understand the design at the conceptual, physical, and logical levels as it provides a clear
picture of the data making it easier for developers to create a physical database.

Data models are used to describe how the data is stored, accessed, and updated in a DBMS. A set of symbols and text
is used to represent them so that all the members of an organization can understand how the data is organized. It
provides a set of conceptual tools that are vastly used to represent the description of data.

Types of Data Models in DBMS

(a) Hierarchical Model

The hierarchical data model is one of the oldest data models, developed in the 1950s by IBM. In this data model, the
data is organized in a hierarchical tree-like structure. This data model can be easily visualized because each record in
DBMS has one parent and many children (possibly 0) as shown in the image given below.

(b) Network Model

A network model is nothing but a generalization of the hierarchical data model as this data model allows many to many
relationships therefore in this model a record can also have more than one parent.

The network model in DBMS can be represented as a graph and hence it replaces the hierarchical tree with a graph in
which object types are the nodes and relationships are the edges.
(c) Entity-Relationship Model (ER Model)

An Entity-Relationship model is a high-level data model that describes the structure of the database in a pictorial form
which is known as ER-diagram. In simple words, an ER diagram is used to represent logical structure of the database
easily.

ER model develops a conceptual view of the data hence it can be used as a blueprint to implement the database in the
future.

Developers can easily understand the system just by looking at ER diagram. Let's first have a look at the components
of an ER diagram.

Entity - Anything that has an independent existence about which we collect the data. To learn more about Entity in
DBMS click here.

They are represented as rectangles in the ER diagram. For example - Car, house, employee.

Entity Set - A set of the same type of entities is known as an entity set. For example - Set of students studying in a
college.

Attributes - Properties that define entities are called attributes. They are represented by an ellipse shape.

Relationships - A relationship in DBMS is used to describe the association between entities. They are represented as
diamond or rhombus shapes in the ER diagram.

In the above-represented ER diagram, we have two entities that are Employee and Company, and the relationship
among them. Also, in the above-represented ER diagram, we can see that both the employee and company have some
attributes and the relationship is of "works in" type, which means the employee works in a company.
(d) Relational Model

This is the most widely accepted data model. In this model, the database is represented as a collection of relations in
the form of rows and columns of a two-dimensional table. Each row is known as a tuple (a tuple contains all the data
for an individual record) while each column represents an attribute. For example -

The above table shows a relation "STUDENT" with attributes such as Stu. Id, Name, and Branch which consists of 4
records or tuples.

(e) Object-Oriented Data model

As suggested by its name, the object-oriented data model is a combination of object-oriented programming and
relational data model. In this data model, the data and their relationship are represented in a single structure which
is known as an object.

Since data is stored as objects we can easily store audio, video, images, etc in the database which was very difficult
and inconvenient to do in the relational model. As shown in the image below two objects are connected with each
other through links.

In the above image, we have two objects that are Employee and Department in which all the data is contained in a
single unit (object). They are linked with each other as they share a common attribute i.e. department_id
(f) Object Relational Data Model

Again as suggested by its name, the object-relational data model is an integration of the object-oriented model and
the relational model. Since it inherits properties from both of the models it supports objects, classes, etc like object-
oriented models, and tabular structures like the relational model.
Schona.
o6 Coect
aSeloct Comnicar
olaa
aCCos fer
tool
hendy Dhis
intenaci'
on pla
the
oncoos
opt clone d'Yectly
Con DBs
need
we for pialtesm
example
DBMS
wjh be ony
A (maion) infoahon
to uned
DBMS clisecty lnguoye
Usen Cen Fr ’
tontmanagement.
.claba,
impor Jawa
languaye
cny
(in
Conci
the on auchiechye&
de.
of Databne qpplicai Aexpcundimacine
client
any for
Data to oiee cloest
ibel,
94
local JDBeCinrochi
Arehieie it
Cihical available.
he91e for
DBMS/ a9chitechuve
Arei
techm o Seswer ne.
dalab
Java
is Av
ajsechve e dovelomeat Senu
en(client- ODBC1
trekilec done. se i
DBMS dotcba
og ctiyecHy for Ofhce
Ms
eq. Lwe
Can
use
ce fAient Jhe
3Tie Oot Hen Any
changes Suilabla dclaloou onlyWe
veVS far open
to
a DBMS|tie1
- her darabana aychitecwe
Syslemcho ^ecuvely. ie Dalabone
aachilecve
2Ties
ano inmducicn le store NO-
wed applicahong
todays AP's
for 2
3
ODBC
File
dalabse Same
-’ San and
quicuy Types
aMchilechYe
(a)
1-
tie
Lec-I -a
lec
Ly
Lot
w A
(0) 2)
Seswes
Serven
Sowe
aComecie cient Cnd
Cient
SeweN
oih
Senven Clieat
utich
rovlhen
cemuicat
cala
cat teracli
Comeni
esryishon Deskto
papplicaiony atni
|Applitaion in 1Appl
SeveN
S
DBM Dalaba Use
USe loyen end
no
hen web
clive
cty
aicaon ent
cli
lape
Can
h
side.
ey
ampleg
’ 3-
Tien
Arclilecue aken for
on
Applic
clien
Conlai
Seyen used
chent
L
L
L
enG colvefi.
velayonl
in
dalclane Canephod
Schene, stchne
clala
Ohone
uhia
Sysle
m dechni
dala ancd
name
of orgomized objec inced
held
o
vepvenonlei oG
pant to schema typically
Cyel
Snvolved.
dalabou
Schem
Schema
be Compan
teguivemo
projeck
ARCHITECTU
RE Schome dotonengm
Conshci
tubte Synax
luds
inc
logicad co
not
Cogical
databan ure Cne
Less
clean,
cbstact
aban
pic houwbu'snen
ruler
inkpiy
dal Ihey
DBMS physicad big wwually
iniil JheySueh
SchemaConcepul Cisntin
offers
phys'cal:
MonuE-9 y
Ls Conaphal Cogicad
Concept
(a)
Lec-3
Lec-4’ Lec-2 Lec
Schemna ’
for
Extenal
schema
aMchiechures D3MS
hhat is
ConcoptDBMS File
Quwshion
Aie Sys
Stou
chye ok lem
table
Slore Schema Vs
ue 20 Houo CEPTUAL
CoN
PHYsICAL tencQ Ex DBMS
soye SCHEMA
ScHEMA cro
table
Jhen Jha dhe
iim-acjn.
Anit Schema Lec-y
d wtich Jhyee
data data
above
(ouel
Cin yn
clale
(Etupkat,
çomaion) ER schona
o Ralaliaad Extesna
Can
in Schemos
Amozon, stuce anchece.
tables, whc cismbuta
Conwoli3el
con ke be. .

Pad
is s
tove CPhysiSntesnal
cleau)ue) togicadCaue
schema
Jhen Jhe Qm
ele:) in level)
yied
struchye to
Usig
Y)
6
to
lo
isinkomain
Lha acce
Cant
inteact
skoved ciff. uew
dat
isfer is lno)
do Afendonce (
indepencone
data
and
Usen ca
fenont Wedile.Schema
diyecHy vieos.
mls poic,
(ees
Ahoyh Cevel pasuoord Use
ale
for c
he
Mol
peon
on
sn
manu
physicoll, per exten
vole
Don 2e ot
Jhe w
data View
ord View
(for it
fomm uthee om: manls Shudet
foViecs yne
(heu to
or dau ys login
fepyesent
icd
(acug
Saefor cifforuntTfaculg login sJhat
is
the
Use)
utich mana. Unedin
pafe
knoe schoma kils Role
Selec
avels 9n stoved
is Shou.
toHo0 A shown is
evel
Jhvec Sloved, F8 shudent
coñ GnmaiL
f.
Unive1sil new
Jis
But
made wtonee
Extenal vieuhuder
S we
See
USen
is Take
when
we
No
#Why e
2 solaianhip
a /shems call, lo (reymen.
mauy
telaionlp. tieh Cie)
schema
Extenal
physi
fiw
Concenheel
viesschoma mods
fere to schoma
Physicod
alh
enhien
bu be Rolaicnal is data,dise,chjie le
DBMS)
(Cayen
bluepink daba eh cMow schema
Concephol
in
Tables istorad
ele
). INRo
Jhe decid,
Dnd
ondl
Schoma
ER
,Age. dale
stoyod
isdata male
atmin
Dabon
lelahonal
Moclel dala ia
DB’
Achl
Concopheal
schorna Roll
no)
Moclol o6 schoma inten
(au Admin
palabo
doisner
Bavah
an
deignen
Usen
See
exampe
dabab
an
HowSudont
Wehue
to ER cal bu
physi
she
So :NOTE
e. *
3
O1

Lec o6 Keys n DOMS

athibute o set of atibules


Meys uniquelyleniy any aow (record)
tables.
06 table

elahonship behueon two differonE


establis hing
wl be used in funchond dopendonc 4 Nomaligahon
will Sudy in nexk chaphes
STUDENNT TABIE
RoN NO Name Phone mo. Age city
AJay 1234S 6780 21 Agra
02 Bobby 98315 61234 19 Mawra
03 Kiara Agro
Rahul Delhi
OS
Pooja ao Mumbai
o6 Ajay 19 Bungalove
Ra Ke sh aucalloY

Attributes Roll No. Name phone mo. Age city


Ned o Key n DeMS
LLet us dfscuss difterent dype o Keys:

Employee Table
ID No. Name Adhan no saly phene email Ahibue

ASupen Key
denh6ty Jhe tuple (athhbule orT sek-o( aribuka, )
Uniquely oho deucb)
tilo Super se C fom uhe Keys onu

9t Can acopt Nu values

iv) Nome 3 is not a Supen Key


Addhon no.3
ÀID, Adan mo.3
1 , Adhan no.2 I D Name
Nome, phone , Name,ennoL
exanpba
examploo 1D, phone , 'D, email
Nome, Adhon no, phone9
Name Can ldenhy unique ows

Can icdonhty Lniq OS Supen Key.


Name + emoiL
Candidae Key
Minimal Supe
Supen Keys ae Colled Candida Keys
Adha no.
xID, Name Togehe boh achng an Supen Key but
but we Cant take ib a Candidatb Key becouun
Jhere îs an amnu& 11) stWh is alreod a Conddals
Key
X1D, Adha Not a Cadidat Key
key
tuwo altibuh
Censitut Condidal Koy
Name, phone ne.7 Candidat Koy possibla i

x Name Adhas na, emoil Nok a Ccandidat


ey
9 6 may alse Conlcin NULL value.
NOTE
Supen
Supen Key Can Conlin Tedundank atinule
Candidat Key No edundon- a i u l e
A cardidab Key ane &pen Keys bu
2) Key
A Supen Keys mok Concidab Keys.

Primany Key
1 Now we hove fo llouain 9 Cand'ddat Key s

D Adhan no Na me, phono no emoi l


Cvi teuia> UNIQUE NO NULL VALVES

Primany Key ID
AlOTE
Jhe WILQ be only One Pri mang key in a. table
DBA hauwe to
L |chose Cave(ully| pimay Keys om
set 06 Cardudat Keys
Neven oY
Vexy arely changeo
L Candi' dat
eys wi h NUL Value
Keys NOb a

Pnmay Key.
ALTER NATE KEYS: 4
9n n he Se o Candidat Keys hawe choSen
One Key aD pmmay ey cund e t Candidals Koygs
wi be Coulled alkeinau keys
Supn
Caidal

Prima alternat Loy

L Adhon na Nam phum. n:


emall3
Ohen
Keys for Sel
Keys nouoleolge uniquo Kuy, Composile Key ey
Candi da ey s

Roll No.eis. No. Name Fahen Nam ma

Pimong clteanali Koy


Ley
cho sen
Lec-o4
eign Key and
Tegyenenkal integig
roseign Key
St deals wi% two 0 mote table in a dalabase

establishe Selahon.ship blo tablen ie Gnko Columo 06


one tablo to
anoher
Concept oG Sefeonhad integm
Conp obereisn Key
USERS
usen id Name
oRDERS Books
emai ordon no. wen id Proclucld-id Poddd He
lo Sadio
Prica
s 3 I 123 23
Mchamaeme 7-89 4S6
12 Rin sola e
3 489 48
13 Amalie Ae 6 Lo

Primony PrimaA)
oy Prony

Foveign Key
NOTE: ORDERS Table is taking
i)Jhe usen id a Hibut oG
anoho table.
6eenona from prima Kay o

trle TekenonCo. om Pprmany Kou


Ovelgn Keys always
i Fovehn koy abla regenoncin s abl
Poimouy ay abla TebenonCacd able

Let us study first different types of integrity constraints in RDBMS before


understanding referential integrity
Tapic: lntegnihy C onst saints Relakon
What is Inheaih Conshaints
Jhe data
uYa cy cnd Consislency ct
L used to ensuse acc uYay
in Telaborna doaba se,
Ly set of rules Jhat calcibase is nok bomiHed to Violate

y Conshraints may be applied to


Ls Relahenship v
insenhom ) made
L ensue. Jhat changes ( updote, delehon
dele ,
to Jhe tbasese
daBciba by auhonged usens clo no Tesult
loss daa Consis leny
A blocd must be Ag' or O nly
gocup
b, 6 , H.
b Jhis We haue to detino in a table.

TYpes of integrihy onshraints


) Domcin Conshaint Applisd AHibute.

Conghaint Apnien Athi loul


Enty
Refenenhad Snlegiy Cong aint Applies Reloh anship
Key Conshrcirnts Appties Atibuta

) Domdin Conohaint :
De kines Jhe clomain ot Valid (set of Values ) o6
ahhbuhe
shoud be tve inteçe.
should not e rnegah ve
should no be chavacen.

be numbe Special chavact.


eg. Name hold no
Phone no should not be greata. Jhon
Enkky Sntegiy Conohnt
Telatea to bima, Key ano Jhis ohoint en syre
primay
Pimayalus Coñt be NULL.
St pnmay Koy has a mul valua. Jhon we
ant ldonity those.

5 Retenial Snlegyilg Coohcint:


Speckd 6 elahomhip b/o too table g.
Let us take an eNample :
Employe. Table.
Emp-1D Emp- Name Age Dep. No
Mohan 21 DI

|0 2. Rohan 33 DI
103 Sohan 24 D2

Dohan 22 D3
’Pimay Key Porelgn Key in Rejoneniny table
Deparmonlal Table
Dep No LOcahon No O6 emplo
Humba 200
DI
133
D2 Agra
600
D3 Beryal

in ReterDnced able.
Primay ey
NOte.
L’
We. cant add D5. Jin Dep. No bE Employe. table becane
Jhot athib is detirod a toreign ay kich is taking
Yelerre 6rom Deposmonas Table Dep No
Al values Preront in Tejeenty table m t bo.
pveront in
(Fovein Koy)
Pirauy Kay table Ohenolse NULL' Can bo put in toreign Kay Jabu
Jhe Rulen
from pnmay key thble
6 malchin
) You cañt detete a ecord
records exists elqted table (teterenCad tabl)
value jn
2) You Cant [Change pimay Key
Ye Cord
has Te<aled recordy
fovegn Koy held if
ta bl. Jha
value in
3) You Cañt 9nsert
but you Can put
exis- in primos Kay
( NUL in Foveign Koy tabe.

Ly How you Cn check!


. Foreigo Key
tab le CResenening
table)
tab le)
Paimay key tab e ( Ke7erercod
> nsent dolet
> delels ? updal

KEY CoNSTRAINT:
Candicdct Key
An enhy Set Can houe mUliple Keys be Jhe
but wfich one Key

Primay Key Yelaen -


in
Specilies Jhct
L Key Conshraint
Al ahe Value, of rimany hey
be
unique
mut
Jhe Volue poimay Key
National Institute of Electronics & Information Technology (NIELIT), Gorakhpur
राष्ट्रीय इलेक्ट्रॉनिकी एवं सूचिा प्रौद्योनगकी संस्थाि ,गोरखपुर

Course Name: A Level (1st Sem) Subject : Introduction to DBMS


Let us check another example of foriegn key from internet source
Topic: Keys in RDBMS (Part 4) Date: 27-Mar-2020
-------------------------------------------------------------------------------------------------------------------------------

Foreign Key:

Foreign key is/are column(s)/attribute(s) of a table that point to the primary key
or candidate key of another table. They act as a cross-reference between two
tables.

Foreign key creates relationship between two tables. It helps to maintain data
integrity which is known as “Referential Integrity Constraints”.

The table/relation which is being referenced is called referenced/primary table and


corresponding attribute is called referenced attribute and the relation which refers to
referenced relation is called referencing/related table and corresponding attribute is
called referencing attribute
Let us suppose following tables: Referenced/Primary Table
Primary Key Table1: department_info
dept_id dept_name dept_location dept_budget
101 IT GF-20 500000
102 Electronics GF-23 400000
103 Admin FF-24 350000
104 Accounts FF-24 250000

Foreign Key
Referencing/Related Table
Table2: employee_info
emp_id emp_name emp_dob emp_city dept_id
10001 Rakesh 11-Mar-1990 Gorkahpur 101
10002 Shyam 03-Feb-1980 Lucknow 103
10003 Mahesh Sharma 01-Aug-1991 Gorakhpur 101
10004 Reena 25-Feb-1990 Prayagraj 103
10005 Amit Sharma 08-Jul-1992 Lucknow 104
10006 Rakesh Kumar 04-Apr-1989 Gorakhpur 104

Prepared By
National Institute of Electronics & Information Technology (NIELIT), Gorakhpur
राष्ट्रीय इलेक्ट्रॉनिकी एवं सूचिा प्रौद्योनगकी संस्थाि ,गोरखपुर

dept_id is primary key in department_info table

dept_id is foreign key in employee_info table.

It means that dept_id field of employee_info table can have only those value which
are present in dept_id field of department_info table.

dept_id field in department_info table is for unique identification of the records in


the table.

dept_id field in employee_info table is for knowing which employee is working on


which department.

There are some important differences between primary foreign key

 Primary key cannot be NULL; on the other hand foreign key can be NULL.
 The foreign key field can have only those values which are present in primary
key field of another table.
 The values of Primary key are always unique while foreign key field can have
duplicate values.
 There is one and only one primary key in a table, but we can have more than one
foreign key in a table.

--------------------------------------------------------------------------------------------------------------------

Exercises:

1. Explain another example of foreign key.

Prepared By
MoDULE
Let us
3: FUNGTIONAL DEPENDENCY AND NORMALIZ ATION

Ysh boiefly undenskand Nomalizohon before stuing funcional


dependency.cabase
-A lanGe Tela ion may e, ult in
deçne d as
single
Ly daBa
dat data)
duplicacies C presen ot Cok of Tecnon
whlch ges uls n
Vanoys ty pe, of Anamolie, (proble)
Due to uhich t s no easy to moinlain the. data operahcny and
Likelihood er0YS and in Consislencier incveQses.
So ust is Jhe opt Ccuse ’ We trying to inpose ale
daa n a Single elahon:
Nouo to hardle Jhe prblem We Should noly ze and docompose
Jhe velahons Tedundon data into smallon, Simplen and
Well stuchved Telabong

Notmalizahen is procen
Tenoing sedundonde, fon
and funcioncl dapendone is a tool for
selah oni
Pençerming Toaralgah on. SO let us Shaat funchordl daporde
FUNCTIONAL DEPE NDENCY|
Let us Consicden a
table and R2
RI(a, ) R, (a, )

2 b2
3

d4 b2
e 5 C 3

and We haue to check foy ea h


R1 I6 (a) Jhen -|
(a) we shoud (Sare value) Jhon we Ccn Say
Jhat Jhere is (unchcnal dapencloy
behweon nd . lemernben boR ane thbuteg.
funcheml dopendoney

depencenb
deteminant
dekeamlnes
depenlont an
now check lelak on R2
ivst 0w
(a) ’ Jhivd ow
So
Same Value al Jhe. tie
(b) 2 Se cond 0w

S aye Value ot =b value oG =24


siviny
funchnal dep endens.
Jhus
Lat
<. Cnsides Jhe
Jhee is

R3 (o,f)

a
Js are

4# ypen o6 bunchional dopenoonies :


(a) tiial
selt Study,
(b) non- ial
2
§. let take ne more eample
R4 CA, 8,c, D, E)
which fd is valid ?
A

2 3 4 5
C-3 gies
4 DE= y, S n YooI
45 but C=3
2 c) C’ DE X DE SS
gives

BC> A di kt: vatues

1.e On Same Valuo. aifferent Value


in Jhon dopencdency does not
hold good.
NOTE: check the fivst athibut (detemincat) a han niqe volue, Jhe
iNepechve of t dopendeny cluoays hold
D|E
2 3
A B
3 A ’BC

d 2
C 2 3
A’BD eah One is
3
Void fd.
--
2
A B
Which one is 2 4
2
Vaid fd? 3 5
3
2 2 2
4 2
(a) XYz 44 Z’Y
(a) A>B A4 BC> A
(b) C B 4 4 CA’B

XZ >Y 44 -’Z B’C Aß >Cv


(d) 4A BCA
Till now We haVe Covened fiysh Cancopt /too for solving
Novali 3akan pnldamo. now ndons kand and
le ain mext Concept
BAX D1PferENT TypES oF Quesihy.
Queshon Ty Pe-1:
.
Considen ohe folooing table and (ind alu þoss ible fd.
Rall NO. Course NO. Couvse - fea
5 C1 2000
6
Ca L000
Cs 3000
200 O
200 0
C3
Ang. 4) Roli NO CouYse moX
b) Rol) no.’ ouYSe ee X
c) Course no. ’ Rol) No. X
d) CourSe no ’ Course fee v
e) CouYe fee
f) Counse tee
j) (Roll NO, Couvse no.) ’ Course fee v
b) ( Roil No, CouYSe kee) ourse no.X
1) ( CouYe fee, Cou rse no.) Roll N0. X

Jhe funchonad depondencien ot cbove example.


CouYse no. Ro|) wo.

(ouvse mo.)

Rol vo, Couve no ’ Candi dat Koyg


Quesh on- Type di
. find al Set Super and Candidat Key S.
E.id| E- No. E- Name
A Supon Keys = SK
2222 B c andida! koy CK
3
3333
4 A
Sol,
follousing Jhe.

’ Jhis
Supen keys (SK)
atibute Can uniquely deginc tuple (30w)

©
C E-NOne X Jhis atiout cant uniqueG cdo (inc a tuple.
SE.d, E- No.Sv ’ Jhis athibut Combinahen Can uniqud, degine ahuple
$E-id, E-Nam V
3E-N0., E-Nome?v
Eid, E-N , E-Nome V
ase oil select from set o6 Gupen Key
Candi date Keys CCK)
(a) sEid}
Cb) E- NO.
(c) SE-id, ENO. x ’ These atibuli Combinahen ae
(d) e-id, G.Nome X þimay Koy be Caue
(e) SE.- NoO. ENGMeS X
)
Singe atii is enouh to n
idonh 6y any tuple
(4) SE-id, E- No, E-Nomex
CK
Some impostant poins yegondiny
(a) Minimal set attnbuteg to idonh (y a tuple.
Cb) A)s o cOled minimal Supn Keys
CC) CK Selecled from Supen Keys
cd) CK shold not have any addiionl Yedundont atout
SK Can hcwe..
G
ueshon Type-3 :
find Jhe closuve atnbuten nd also find oho
Candi dat KeyS Jhe. given relakm an d detined funchorad
dopendoncieg
RCA, 8, C,0, E)
A BC

B
E 1 A 3
Soluion: ClosuYe Me thod
Closuye Of A, (A*) {A, B, C, D, E3
(B*) - { B, D}
(c) fc3

(E*) {E, A, B C, D, E S.
Jhe clo suYe ushich Contcin al dhe ath bu ane CK
NOw
CK A, E cancidat Keys.
taike tuoo athbut NOuo
(AB*) {A, B,C, D, E
Ihese. al Conty all Jhe qtib uli
(Ac*) A,C, B, D, E but dhey ne. CCntidat koy becau
(A0*) - SA, D, e, A is Candiddat Koy

(AE) {A, E, B,
(BC)- B , c, D, E, A Candidt Key
(BD) G, D, not a candiat Key
(BE) > B E, A, B, c not a Canti dat Key, E is aledy
cancidat key.
(Co) }C, D, E, A,B,CI’ 3t is Canctitat
(CE) }C, E, A, B, CS ’ E is not a Cancidat Key
(DE) So,D, E,A, B, C3 ’ not a Can c t Ky.
Candicat Keys ee A, E, bc, cD}
4
Let queshon.
taKe On e

. R(A,B, C, D, E, F)
f: $ AA Bc DEF
BC ADEF

So

A, B, C, D, E, F3 V Candidat keys
{B,F3x

chece for paivs


Agt
Acta
ADt
not Condi dat Key : check Youvsel G
AE =
Aet:
Bci - {B, C, A, D, E, c? Coandidat kay
2B, D, E 3

CD' = c, D,E x

Det
Det

Egt = E, F
Candi dat Keys A, Bc?
Qucshon- Type-4:
Jhe. pnme athbute and pme.
quoohon.
quoshon Type. -I:
we
Candidat key Couve no.(
Pime aHsbua - Roll NO, CouYse mo.
Non pime atbut § Caurse feo.
fo quesion ype-2
We
got candidat Koy
pime ahibula E-d, E-No.
Non - i n ahibut

for qus ion type-3 (i)


We. got Condidat Koys {A, ¬, Bc, CD
A, B, C, D, t5
Non- pme catibut
fo quenicn ye-3(0)
We jot Canidat loy an
Pome qthi but.
Non Prime atnbut: : 3P, E, f

Jhose chbue, Of a Telahon ich ne o


Prime ambute
Candi dti Keyg

7elahcn Lskich a
Non. Pime athibue ’ Jhose.
not pat o Conidat Veys.
Queshon Type á (grvedtribie Set of funciona! do perdory)
R (wxy Z)
Xw
Y ’ wxZ.
San; leh w wite doon al fd sefaralety
X W

VX
We can wite above using deconposikon)ule'
Y

b as’Y /d)You cont


wñe
Now -we wiee 6nd whe then any td i_ eduß ev mot.
lot w take

(ind mOYe ire but don cnsiclen X-’w


So ue hcwe only

ond we conclde. Jhat X ’ w is


foom Jhoe Ci)
essenhal fd beCane Xw
we get only x3
Let w che ce ohen athibule
Wzt w, z, x, Y,.
ignoe depenoloas.
{w, z, Y, X ()
We Conc wol Jhat

de dunolon t

Next dependeal, (wZY)


0z - fw, z, X, y O
inove. ( wz YÍ

essenhal fd.
Next do pendony (Y’ w)
3
YOmoe

y* Y, X, Z, w
Yedurlent
ennlia
Simila
enenl

X -> W
Wz is enenlia

hond sido.
Nou (et choce
Wzt w, z
by gnð ný wzZ’Y 3
TopIc NORMAUZATiON
Let us Conside a table

|Roll wo. Ngma Bsac Godo Brnome HoD Nume

PrirKoyosy 2 B 19
ot
CS edundont daa

18 Cs
4 D 21 102 EC PaR ) Yedundont daa.
S
20 l02 PaR
18 \03 ME KLM
Sn Jhe aboue table, we have tried to Stose enhve daa abot Shudent
in a Single relahon wiich Jhere data Tedundany.
what dala Tedunda ny ohen Same daa is SroYed mulli ple imey
unneCemam ly in database abe . Ihis poo bla mases ohen the
tabte not nomalized

Anamalien in bBMS

i) nsekon Anamolie when Cetain dara (abibute)


Cannob be dgetted- insanted into daaloa se
withou the presena o OHhen daa.
New bjanh
eg. Sn above table we
bt to inset bvanch civie' is not possible
unle
We have any Shuclent opBed foy civl- Jhis is
insenhen anamole.
Called
but poacically Bsanch exishene should not be
Jhe
deyendent
capabily hat
On

we
We shouls haue
Stucdenk eyisena
Stove branch infosmahon ivvespeci ve t Jhe fac
Can
Studon dhis CNamoly Came
Jhat tied to Cent Stove entve data n a
we
be Cau se
table.
Singa
Jhenno
branch Jhore
updated shod
Costn,
but
changed at
be his not
and
dopanmentCxyz' Anamoly
include
all poblem
wj bíanc
fatable the
depamer
ME
but HOD ABC inane
sHoD
mpase
Deco
College Jhee
Studont table shoul
have
dolel en XYZ
isHOD atab
le
Shu doleti
only.
mah /infomahen
updohon Some
Leae
the So S
anamoly dat (pi nOme
HOD
mar tohed XYZ > nfo
of data in to
cue
but Som
plqws
dala
unwantecd Jhere Anomaly
CS singk xyZ Nomaligah
table
atmb
tich
ingormahen
doleto exvatable
imp.
(yEEg
Jhis
ArSome
plaos
much
doponhnorl deleon
callod to Jochonye
any sngle
how
to
wants
Crealed Bvanch
’ cacier
dupli
data whe
pla@s fom
be Came shuden
70
also Modiftcalononly honecalled
on
ha Hnes is becee
table.
Singe onwale
Jho this HOD wont
:.
6NO.
Roil, ME
wQME
of
existene So
C do Con
Anamolydele
te
an
Can
4
'ABC' 9shan
all fo
much
fomahennot
have
9
Jhis occu:
ths zchon
X
NOgmali
Suppose
to
inseJhene
fo
Now
gis
updahon Suppose
toduo
tINCONSISTENcy
what
we
ho
aund
Delchon ant
W in S
to
)
(b)
not
assignComposile
Key.
athibuValuesi
tes no.
phone
and is
213) table
16
419, Voy
qtomie Phone
mo no.
qbove 123 12.
mulh-valued 123
Javal2
Ct+
Phone12 13 |2 213
16 primany
2
should
Contan rimulh-
yaluad
athibutes.
CouYse SO
CO)
(DBMS, Called
Couyse
conains
muih-valuad
atibute
C++Ct+fava
JaVa DBMS Dg
Ms
Co DBNS
ctt DBNS Couyse
contain atibues pimcoy
key is
no
Age Combin.
20 23 Age 20 20 20 20
21 22 22 23 23
not Cel 21 22 phne
Jhe |S-
NP!
should
(Table).
Eveytable. VIKasViKasViKasvikasRam
Bunby
Buny ohn beCanb
ViKasRam
BuntyJohn Namo + ob
Name
foRM
: table.
Courseype
elahon eg
Jhe Considen
the 1st
Noymal
fom:to
in
Comveh
example Roll.
No,
albove
Roll
NO. Rol
NO.
t this
NORMAL above
table
02 03 04 Jhe. 2 3 3 4 NO.
Roli
Ly amd
Sn
FiRSTRule: to |st
How soluhon:
in phore t65
Phone2
pble 12213I23
412
r0Lw 213
CoIst
0 butey
4ny
key athi Cveat
2
3
Key degine Phone-I
Composile Jhatmove 2 |12 123 mey
Composite leont
unvquety
tabe ’
Lay at
JavaC++DBMS DMS
and Couse-2
Comig. Couyse
C++ Co
aJav
2)
key Roll
No.
Condidah CouYse-l value
Nul 3
Ct
t ++
athibute C
atibutes.
Age 20
VKon0
blw
Diffonena. ho
21
Key One.
Ase
oig
key
Supen fa
Ram 20 2| 23
NameviKanRam
Candidatt dundant
te have
Vilan
Lam John
Bun
Primoy
Key for
Can Roll
No
Roll
NO,
So|t Sol^
NOhe: 2 3 2 3
2) 2hd
SECONo NORMAL FORM:
hust be in fivst Noumal fom
2) St ha
panhat depenconey
Pothad de pendeny : when Sub se Of a Candidat Key
detemi nes mon- pm ma atibute s

Psime athsbute : athib ute is þait o6 any Of Ihe CK


9- is prime athibute

Non- pnme aibute . Au ohe Yerhaining atbi bute, ane hen

qtibuhes.
Roll NO. CouYse- No. Course - fee
2000
Ca
5
300 O
200 o
C) 200 O
6 C3 3000
whe then Jhe above table is 2rd NE ?
givea
Uho quonh on ,ohen0jse
Sol
Grenevaly fd hven
we have to kind it. (Qwoien type-i)
L We have aleody clone Jhis qulo hnn be fove where
gok funchioral cdope ndonde
CouYse no fee
(Roil No. Couyse no, ) Couvse fee
Now wha Jhe. Candidat keyl
CCouvse mo.T) Course
( Qoll no.) Roll No',Sx
( Couvse feet) S CouYse.
0,Rol w, Coe fee )
and
atibut
prine ?Course
Cou
rse
no
Cou;e
alhsibat/Ro
wo. Roll
N0. do
dono
puial
depenclny
foma!
2N
in
not dat
CondG
Condidat
cleperde. ard
fee
Couvse
fee 2NP
in
nol
dapendaga, mo.
Course
no.
cand
dat
Koy
CoyY
se
is
Ofof
NO.
CouYse Couvse
e Coure
Table
is key
Subsek
Coye
alnout
Pima pauba Course
(ee.
clapendot
Cardidat
Couvse
nu.) iJho
s is
ahibut
in
iNon. is ctibut
Pm ee it
i'doyendont
Courses |s
ubset
Ok
not "able
Jhone again a
elaion Candidat
Key: pimechece is isustich
iself
for no Ceoil
No, i)
givenox
she Non
- se
Y
Cou
hee and
fom
from
s(oh
No hene
Jhe
1)
L L
NA
Sin
)
yourel
(ate
NA
2nvoin
by depencleny)
(Panias tobe. discuss
Solve
( assumdcoill
dopendonay.’
?NE
2 isigiven
AB ahib
pime
non-
follooing
qucohon. E,
D,C, dependeny
9s
in
’X
CD
AB’X CK.
6d. paahal
Candi
dat
key panhal
Subset
D
checu
CLll temove
ACD valuen
Jha Non-
pime
to
Hou
Jhore
L
ohen
Sol^
Lb
ib
be ind Koy
Candidct
Jhe
should all tubl isJhere 2NP
in
mot
sihon!
po
decen lots
athibue checie
in Hhene)
qhnbley
Key. ioy
Key a eA,PA
Candlclct
jo Canclidat o lbe
caue
fa:
dopencloncy
pathal me.pmi
non Candidat
Jhe be. hove chece
N,
P.A Jher
s
mme Can
Key?
Canclida
’9t
You B,DES
A,§ to NE
2 table
Table. NOTE!
nonon nead depenol
fuby
EC’DXo,nt
Cnd dopendent D
c}
E, (no Jhe
Jhe. in
delinolly
be B, BX
A,
Et-e,
key
Candidat
(EC)’ cepenclon
pant
2NE Key A, dapenoloreg
n
Parlial missirg
’Aistable
n
-
Candidatfunchonal
falty BX
Jhe F, au
ahibuti
beshould
be words
Hhey
o
is C, aHibule,
Bime anhal CAGCpE)
R
he
Key
Cord
of
Shoutd
Jhere
2) E, A, wjee
R(
ABCDEF)
E>A EC’
D A’Bwha
ms
podble
Solved o(
ile
o
= Pnme albove. A’B ’ AC
(EC) KHS
able Subset Shep: EC fo Alot
fd' Non- Jhe checu
):Rule in
First but check
i
dapeneerey Jher attibut
pime.
Non-
propehen Pd X
no no
Po
depenler.
silive
tion
cilhmlaub
tan
sihve veTycnsili
X
but
erbul
a
NE
2 pnmadopendony
teansihve Td Td.
no
DAX
3NP
Jhoyh
NO non
in D
andC’
AB’c
r catosbul
prime
Non in
be. Jhee
should
be ->c Comon
CD
AB Above.
toble
is
BC ABcD)
RCABC D
AB
should A>B C’D.
A B AB
CKaA wor
ohen
Sn
Jhen
ikqnd R(ABCD
CD) AB>
D’AB,D
A,
n Table
3NP
Pyble NeA C
SAB
C,
> 27
Rule: CK=
DA NPA Now
deperlon
Panhal 3NE
Key
Candidai 2Ne
aliw hve in
non-prime lloed
dransi Contain
non inallowed
allit
pme i
de)
js not hond,s}
is nok
his shocid C
u a
3NF) not
3NE
be, cetl
shoutd foym ( is
9t
Nosmal
abibut
Prime dopondon
aAudetermino
cae
Specia
(
únc
beshould
XyZ
ccken
codd
o ce
Prblem
BCNF Taole
LHS Boy now
3CNE’ BCNC: fd:
3NP:
&TiI
2NP
:Rule
3NE
BCNE
A N.
DD
D) , B, A, P4
Be
gD,
Bc AB
Aa’CD
fo: Nomal highot Ihe checu R(ABCDE
in is letab ahove Jho
N2
X 3NF
X
X
Now
D
A, PA:
CK!
Sol^.
Nfhot hig fam stornt Aucays
toe Nomnal higho for checu
K(ABcocfaH)

Houto De compose nto 2NF

R(ABcDE)
AB C

Sol CK= ABD


PA= A, 8,
N.PA C, E
not in 2NE)
No AB C ( Jhee is panbal dapeneeng
panhal doperdere, >not in 2NE)
(there.
Jha. above able in 2NE.
deconpOse

Ly R, ( AB C)
L Ra C DE)
> R3 C ABD)
RCABc DG)
oa)
AB
C>D
E{
B
PAA, c? N. PA 8, D,
AC
NOw A’ B

B>E
in 2NA
Jhe. above talsl

yR, ABES
3 K (A BC EF GH I )

AD GH
BD EF

H’J
Hete CK-ABDf
$A, 8,
N.?A: G, E, F, , H, I, 3j
Noo
AB> C
AD> G1h SeDs
BD E
A
H J
(ot w decone

R, AADGa H
AI{
$BOEF

we Can

AD

A BD
o e COmpose mo 3NE

KCA BCDE)
ndi A ’B

C D

AC P. A: A, c}
A’ B

B’ E

Now Lot w

R, (A E) X
in this table.
no tronsive dopondony.

(Ac)
R (A BC
AB’c
B>D
D E CT:d)
P. A- A, 8 Qe, 0,
Nou, bR, (4b c)
bR, C BD)
Ly R ( DE)
RA Bc O EFG H I J)

B (P. d )
(Td)
D’ I J ( T d)

decoyop

( ADE)
( BF)
CFaH)
(D1J)
(0)

Toprc: ER ( Enkhy- Relakonchip) 1~aga1m


ntvoduced by Dr. Peten chen in l476 (You can check the Teseach apen)
2. . An Enhy- Relahbnship modet (ER Model)
descibe, the strucre O6
daabase wih the help of dagam knouon o ER- diagram
9 is a blueprint o a clabase Jhat Can laten be mplermented a
a database
darab ae which
9t is basically iagram ahc epsesentahsn of a

is eny to understand non- techical Use.


euen by
Let uS checK one examplel
Fnane
S.nan)
(Lnane

Teache Teache) S tucdent

DOB Age Couvse.


Phore no
Con you ndestand the logic
. An ER diagrom Cons1shs of
? eniy (enhy set)
Athibute

Reichons hip (Reraionhip set)


Let w wndentnd aboe Cornponenh one by
Jhe Jhat is
An enihy is an object
Enily Jhe valwo o6
disinguishoble fom othen objecs based on

Jhe atibute, Cpropenhen ) it þossevs,


we have Jhree (a bhck, kA) mken pen.
Jhvec manken ane object, but not entihy becaune
Jhey an not
L
be idonhhed. baned on any propeaty (Compang Colouy, pn@)
Nouw Suppose ure hqve Jhvee blace, blu, Yed) manKen pen.
gn Jhis Cane manker is enhy be cane It Can be idonsied
boned n qHibut l Cotbur).
* ypes of enkhes
Non- tangible exíst in
( agicatly
real ovld ).
Tangible
(phys cally extsk in Accont
Teal wotld )
Con, Pen Bank loc Keg.

Now let undesand enhhy set : Collechon of Same type of enhhen

ER Modo
Enhhy Can not be Teprenented in ah ER diagr am inglana da
vectangl in ER diagram
Enhy Set is epresented by
Relahonat Model
Enky cah be repvenented by vow/huple.
Enky Set is Tepveented by table in Yelqhenal model
Student
Rolla Name Age.
one enhly
RollNo Name
18
nohen enil 3
Shudent

19
set of all 20 Jhis is an enh Set
enihes is L8 dont
Caled enit, set H 14 ER Moclef, we
visucl
inset clak cnly
.Shudont table is an enhty set. vepyenenahon. (iogical schuma)
enhy Can nok be. Yepvenentd in
ER diagram.
Ty pes of enhy set
.enhy
Weak enhy
2
naw nde nd Jho,
Aibu teg Second ompono oo ER medal
Athibuton ln an ER diagram is Jhat Componenb
Jhat descibe Jhe
chavacensie, ot enhiey.
ER diagram Atibutes are. Tepve sented an elipse ova shape
Telahonal mode! Abuti ae Tepvercnad Separate Columng.
for each eniy We dyQw a table Telqhonad modol.
fo ach atioub we cdd exha column

Sudenk

phone
no Roiia-naw\nA
D. 0. B
(Roll NO
f-nqme
ame
Student
(mnam
kol Phad mulivqlued
(L-nam
Age
Typan o7 Atibutey
Aribulen
4i) Simple nd Composite Gimpe Oval shape
Simple Connlt e diided 6uyhe repreented y
C omposite atbuli Can be dijded Gurhen in Simple atibute.
Teprenened by Oval Connecteo to anothe oval.
Simple Roil NO.
Compositeberae Addverg.
Co)posi le. ahbutr repyerenled ag Sepanat Columag
9n telahonal model
AHibule
) Single and Mullivalued can have more Jhan ona value.
Can have ’
only one Value
Muhvaluod AthibuA is Tepye senhe d
an
ER Nocel, n
Relqhonal model, mulhvalued
alibut dffenon oble.
Stored ard deived Afmbuti (q. Dist. temain Cdesmat- curet pot
i) Sn GPS.
D.o+8
Age. -. Dlst is an danived atile

KEY ATTRIBUTE -’ Jhe atibue whtch uniqualy iclenihe each enhy in


Jhe enhy set is Coled Key athbure denoledl b,
by (Roll we)
Let now

Relahonship
ndenstn
jn an
Jhe Jhird
ER diaga m.
Componont
Retavionhip'
*Relakonship isis n assou'abon behseon tuoo ov more enkies
Same on difeent enilg set

enhy set >Ge laHonship sek


.> enhy set
Teachen teachey Student Shudont shudent

S
S2 enity
S
S3 Sy

9ently sek
Sek
Genilysek similan type of relahondip
sob
Kelaionship
diarond hapr
Ly Sn ER diagram , Relaionohi p st 0s eptesened using

L Sn relahonad Relahonship set ls Tepvenenbed e he by


model
Separate table by Separat Column C forelgn ay)

Every el ahinship type has thee Conmponane


L Name
L> Degree
Ly Candinalikg
a selahonship: Numben Of enHy set amociated in
the Tela konship Set
l Unany sela konship ’- ohen Jhete is
ohen only one enhy Set
gelahon, the telahunship is Called a
pankcipahng m a
lunwy elakonship
employea |Gngloye Gnpoyee

* tuo wways o& represenhy uny relaionhi

Ly Binaly velabkorhip when Jhere ae two enhy et


Called binasy relahoni p
pornhipaing3 in a felahonhip is

studen t Cou rse


secmd enhy set.
’ Ast enhly set
enhhe set
Ly n- ry delahonship: when hene
Callad
I he e lahonyhip
panlicipakn5
an m- any elahonip.
Teynay Telahoship

Quatenauy
Jhe umbes Of time, an enhhy
CARO1NALITIGS ot an e
Telohons hip set is Knocon ay Candinatd
pankcipak, in
be ot difforant types,
candinclily Can

Can ta ke
0 Cne-to- One : When each enbhy in eah enhy Set
Pant ony Once. in Jhe Telahmship Jhe Candinalit

let assume that a. male Can my one femalk


Can mary male So Jhe Telahanip
and a female
One. to One.
will be

1.
male marjed
to
feale

using Sets, it Con e Teprerenled


A B

B,

One- to - many: Uhe- to- many mappng -9 well uhes


Qach enhy an
onkty Set Can be Ye late to n OYe
Jhor One fe tohonghip
Scienhst Can 'nvent many invenhoy bu Jhe in venhta is
done by mly Specifse scenkst

M
Sciens inven
A
Au
A3
e.le
Many-to-one
-to-
Mony
paut Many but othey
eniyset
Studont patt
onlyon
ploye.Em
- manymany to relaonh'p
Bet,
have
sets One.
qsSume
Enploye
Can OnCe
employee
many Jhon MCourse
when
A2 Ai (enyolad
Au; A represerted
Can be
assim Jhat
Can in
enhheswhen Can
a.
Candinatily enhhes
A3 A2 A
Maniyed Jhe
in pant
take
by be
Studen t
Telahonshipset in
mony Jha 63 B2 takem
B fCouvie
in is One
Can
projects relahonship , more

B enhysetal by by many
M ka enHhy
many ke
and toghon and
only Set
Studen One
þrojec Cndinaig Jhane
@nhhey
take
Can one in intake
Ccun
hs
Course
*
Reallife
eadinallgMax Jhis LyYarhcipaHon
Too Min language
SimplySn
numben Speci7ies
Jhis panhipohe. being
ypes 'database
mit inotans
Candinalilg ’ Conshaint
speciky
ndinaly
ofvaio. type Supena ’A Project of selated
whealhe
of Constxaint
Projeck elahons
hcip Dre
os Telahenship to
elatonsp.iMax.mo.o6 enkby he
ahonConohini. suden relau Jhe Jhis hip Cnohe1
(9} Min erislen
Can
Monp m anCosino dhe
tal
pai has eniy
it Conshain e
interw
tae 4
’min o. enhy
Can hawe m)nimum O6
Panial
pavh, Cant to times rimes t
study Qn
may Speci Jhat
Via
be
N pashclpahg
an eny anhawe. (be depend,
enhhy
a
cny -
hawe Enploee. each
E Gmployee pankipds
enky Delahcnship
and ype.
aied by 5
Couv )n exiStena
min.and inhow
oei - must/co
mekmany enkymax}mu AA
m
Sem,One
relahonhip
ina
Kelahonship how tuo enkies associated oi eadh oke.
lypes ’
|-M

L M- M

1 1
E mployea Wor Ks begonhront

Wuyks f Pepanne
Empkyee |D.jdD. Nam Loe
6_ia ENam Age Munh
A 21
22 E3 D2
C 23
E2 Dy H Delli
E 22 Dy

bata. wie be puk in table acCovcy to ype o6 Yelah onlip


OrQ- ne velahenl,
Tabe Cant be vepealed
woT
wsha be Jhe Primany Koy
No oho Yepeai'ew o D id an
malu E-id
So n |-| relalonlip you Can

Pomay Koy.
’3
How many
Can
taue. E-id as prin ay Key
Suo Tab e Employee. cnd Talole wY.

E-idE-NonnAe |D.id.

Can hae j
Woves table (velaltndip) aliulen
YelahonNp can alho have
(2 One to Many telakanhip
(Date

M
hame Custome aive ovdens Udena.

cily Cost

Cus tone
Ip name lo.oDahe T0-no, de Cosk
A
2
Mum 2 sha, Lo
3 shivt | 2o0
Del

primay Koy in hive table 0-n0. is pimong


Jhose pimay koy
wlic is nany'
explanabon
many o velahonwp.
Same

3 Many to Mony elahernhi p!


M Couse
Shudet Shudy
PK

frRol.C-1d )-fu |C-id| an Gved


RollrAçe
C
C
2

many
to Mang elaicnip we hawe
nd eid
Combinah'on Rol o
Comrposit oy
follouwing Seps ane followeó for an
ER Mode! from pblam
statemnent
9deni sy Jhe pnh Set
2) 9donhty Jhe elovant athibutes.
2) Sdonity Jhe. pima athibu
4) fnd delokonships b/w eniy Set

S) Draw Complet EA Modol.

Pooblemn Stalemont Draw an ER Modo! tor an univensilG databau


ayicahon shee
han
@ A univensihy has mny dopanment;
Each dopanhren t han mulip le ihcto; among
them is ha head Jhe copanhent
An Instucto belongs to only bne. dapanhmenb
CouYse each o
Each deparhment tns mulhple
ushich taught, by a Sing le inguc.
en for mnany Couvses
A studens may
lfeed y df depourenl
We Can idenify follouing eniy set
Step-1
dopanhmant
inocto
Couyse
L studon t

* Universiy is not on enht set


relevon athibwles
Shep-2 1 Sdoniey Jhe
Depantnent (D_ no, locahon )
CourSe CNarna Duraicn pre-reput)
nsh C I- no,, - Nat Reom No, Mob. )
|Roil No, S nome S nil, Bob)
Step3:
Depanent
Cou Se. C. No.

Inshudo ’ I . No.

sudot Roll No,

shep- 4:
from M
Depaven has gnshucor

X 9k is 1 to Many Yelaiowhip fom dopart to tnohel


from
J Depaahod heoda
by
JSnstucha

fom M M
Cowse.
Denavmel

M
from Snshu c taug
by -lCour
M M
fom © shucdent enoll Cowrsa
Jhe Complet
ER diagram

D_name
D. No

JDeparirvw heal
Iname
han
Snshuct Room no
(ouraia Couv.
DoB
envoll

revequis
Shdent S-emei

S.name
Doß.
Topic SQL ( Stzuchred Queny Language)
Eng
Hincli..
USen ysen. ek

ned Languages for Comnnicahon

batabqse SQL for Communicghen.


Languye
Molel and
Hiskoy. Kelahonal
as þapen shored
I470 EF, Codd published Jhet
daa Can be.
tied do implenent Jheoveli colly Yelakonad alpebra t
and took the help o6
felcbe c CYeat
Calculuy
( mathe mah'cad funch on) (sele ct,
insent elc.)
Started, implemonhahon SE QEL
Latan
Langye
Sinple eng4sh Quey
sQL.

’ an be used Speciti colly iide RDBMS.


SQL is domain specific languge
here y C,
C++ jeneial Specifia language.

SQL Comnmends
) DDL CDala. de (inahon lanuaje) ’ Create, alhen, Dop taun cat, Yename
insent, upcdat, clelere
) DML ( Dakau Maniputahon Lengge) Select
(DQL)
ii) DCL C Detcu Conhoe (onguae) 6yant, Revoke.

i) TeL (Tranoachon Conhne lanae) Cormnit, Rollbac k, Sawepoint


) Com haints > Pinay Key, fovelgn Key Check , unique
Nulb.
De Gault

Let s Stucy One by Cne:


Jhe dak Now
(suche ), inseniny
atter CTeainp Jhe table
Jhe dab la we want o have Ceonhol
dale n
having the data wy DCL Commncnd
Data Detina on languaye
Sh deala sth Jhe Schema. CstucYe). N specihcy deaty
wih Shuche. ot table. Analoy ’ pancol box.

* Syntax: CREATE DATABASe <dataoase nane


To Gyet
dato ase I
* Syntax: VSE
<dalabase. mame >
to choose Jha. panhcuan cataba se.
CREATE TABLE ¿tabloname >

type
athiaus 2) type

Noo atten Youw have Cyeue@ Jhe StncuYe in wtich you


Store. dala )-e oho
tabie. You CYe clad. lf yow oant to
cleley Column ele.
chane
Stu c ye
adoling Column
we use ALTER Conanl
to reMOVe Jhe.

ant to vemOve. data fom shucc ’ REMoyE


Ik you
stuchre RENAME
Tk you wamh to enaae -elette yename
To SIo1e dat ivst we hawe o CYeat Jhe Stouchu ye

DDL Comnond do as oi th deiniy he stuche.


we Can not Use DML Commond voihou usiny DOL oody

Stuch e. table' We insent daa. delth data


A6ten CYe ahy
pdat data. cyeay stu he Ctabu wj th Column)
SSudonk nome Aje, addves
DML ’ shat is hucon shat is his
aye wha is his cuolalve all Jho
we inent ini clu Dhe table uny
pML Comrords.
ALTER Common ’ (a) Adding cdumn
(b) Remoye Columr
Remamben
1s
table (shuchu) C) MOdi6y dalaype
rendy ereated . ) Modl6y dasahype length
(e) Add Conghtaint /kermove Conshaint.
(f) Renane. Column/ table name.
We
have shu dent table.
Sudent
St- 1D Name.

checu SQL calatype:


Numenc bit, Smalint int, decimal,
numenc, float, real.

’ Date/Tme Date, Datehme )


Timeslamp, Yean
SQL Data Type chavacha /shiny cha, van chay, text

Nchan NVavchan N texk


unicode choedi/
Shinj
Bin ay Binary Vou binay, mye

Clob Blob, XML, Ison


$ Differene blo chay and vcuchay
stoe charache. on
A. Chan dalaype n SQL used

sting ot blw 4 .and


fixed longh b/a QS chavacters.
QSS
is less Jhan ghe
Jhis Jhe le ngh of shing added
Jhen exha blnk SpaCon n
Speci (ied lenylh
atomaicolly. ustich is 4ee to
Vanchar dalay SQL
yanablk lenh but
Slove. alphonunoia data o
max: Lery is Speci (ied .
Jhe shiy is Shu to,
oddod.
Thon no exha blonk spaton

Self shudy ’ Vs chayacten


stng
4
- 2147y83645
to
o 21445 3649
)
byeo shoraye
Smalint bytr slov aye (-32, 768 o 32 #64 )

tnyint | yt shoray (rl28 to lzs)

Bif int s heye.


Now Coyice Jhe tab le stuclont Cpyeious paye
) we want to add moye C olumn oddven'
ALTER TABE < table name ADD ccolumn nar dalaly ();
Synay :
2) We wount Temove panli culo Colu mn

Synby : ALTEA TABLE < > REMOVE

s) we to Modi (y dataty pa , daiaype lengh.


Syntax : ALTER TABLE < y MoDify <col. nam
3) REMOVE CONSTRANTS A ter J a table is
Yected We We ALTER Jable.
yaùn
i <Column- nome>
Syntax, ALTER TABE < 7 A DD primauy Koy

4) Renamiytable or Column
nome>
ALTER TABLE RENANE To <eo tadgle
to euo col-nom>
ALTER TABLE < Rename colnam7
ghe kable.
Desciho The stucwe of
DESC ’ in data
shuctu rchanye
pChaye in Comnend in SL.
ALTER Cn d UPDATE
Comod in SL.
TRUN CATE and DELETE
Diffeont blus
DML Comrend
GDDL conn
TRUNCAT6
DELETE

singe, mulhpe Removeg all the YeCov d


Remove stucn
Je tabe.
al re Cov do fom the and
table acCovelig to ghe fom Oe daeban
Spe ciied sÙL shalbnel
eiminat Jhe table
Jhe, cu,lo
L Do stucw fon daabau
Stucive.
SQL Queies:
SQL Aggsegote Fundhons :
SQL Agregate funchon s is used to þe fom Jhe. Calculahons on
muliple Single Column table.
S+ Tetusns Vcilue.
singe
CoVNT MAX
Types SUM
Av G1

CoUNT Funchon ! Used to Cont Jhe numbe

datalbase table Can on both


mumee nd non- mumene data dypes
Count funehon Uses Jhe CovNT(*) Jhat reh
Jhe Count of al D0S Specihed table.
Considens duplicak anc Nul.

tke an example product table

Prvduct non Company Quonhy Rate To la


Comp.
Pi Com| 2 20 A
P2 Com 2 3 25 A
Com 30 60-.

PS
Comg 5 So:
Ay
20
P6
A
Com 4 2S A6
P7
Com @2 2
P9 30 Ag
Com 93 25
CheeLCor u Quny-3
output: Guey-I
Examples
Seiect
Croup
productfom |output 9> sele c |tput 6 ouwput a9 Houw
Con 2 Com |
company
mayHouo Select manyHouo Select many
Comg
Company ,
By Whee
hen From
PBoduct
FROM j
A
3 Company CoUNT CouNT
() CoUNT(*)
quny: from at
Procuct
Count*)( >=
; Pro
Company )C 20;
cuet

; isledin
Vhore in

Company
houp by Sele select
|butput
-3
cluct
fompro o table
Haing procuctabla.
Company from
Com 2 (pISTN
Count CT
CoUNT(A)
3 4 CountC*)

a;> Compony
SUM Funcien
Sum funchon used to calclate. Jh. Sm O all
Seleclod
Columns mumoe fetdo only.
Tell me The. cumer o follouiny synlax.
To lal
select Sum CCCos t)
540
-fom
Selec sum ( Cost)
fom procuct )80
Ohere
tool.
Sele ct Com pany, Sum (cost)
Com I
fom proclu ct
where Quoniy 73 Com 2 15

qrupby Compong
o}al
Salacl Conpony Surm (COS t )

fom produel Comt


com 2 I46
by Compong
to tay
Sum (ost ) >a l00,
Having yd to calulat
Ava furnchon: Jhe. Avg (unchion is
Jhe wonge value numeie ty pe. foncl
all null valus
Jhe
aweay
he
fno Lolumn.
to
Wwed
checu
it to 30
Column.
used Cantain
is
an
Moy
funcias
ceytcin cli
un
value
or
CRate
MAX
)
CosT)
Min )
Yat
',')
fom
tabe
a
total
m
tabla.
C (
MIN
Ga m Vals
Funcico’ fom
Av fo
table. minimum
funcien
Sellct Selec
Select maximum
The
MIN
MAX
E
xample
examp
SET OPERATION
he sQL se Opesahon use to Conmb'ne mote SQL

Select stalenonth:

Types Union
i) Unicnall
Inteasect
Minus
i) Union Considen oo tablos fst

-
Table 1 Table 2
Name
Name
Jack Jacyon

Hamy Shephan
Jackson Daic.

Selech
Select *
UNiON Al
VNON
fom Tabe 2 Select * abe2
S-elect

owsput oubyut.
Narme
Jace Ja cu
2 Many 2 Hoy
Jacuyon 3 Jacunun
S tephon Jauon
5 Did Slephon
Saicd.

Union ’ rehm nique va


Yet all
Yeodo
includiny cuplicati,
. what is Union and (
Jon'.
Join in SQL used to Combine dala from miny table,
deda
mathed Condiion Dlw Jhem Jho. dala Cembined
win Jyoin Staenont desull in Meu
Column
Boys
Roll NO, Name Gish
Roll N0. Agd ven
Ram None
Jayont 17 Naina Delh
16
27 Rinki Mubaj
30 Mcyonk
Prakhav I7
7
Jeu pu
Ro'i Bhopal
Sanjay 16
I6
Seema
Mora pelh
Selet Boys. Aim Bys. Age Civb. Aeldyew
fuom Boys
Boys. Roll No z Ci Roll No.
N
ane Ape Addven
Prakha Bhopal
sanj'ay
Union in is ysed to Con bine tho derulh set of two of
Stalemo: Jhe data combined Wsing he wnion
moe select
Slatemot i ito Yerult ino new dishnct 00s

Name
Seloct Nane Fom Boys butput :
Ram
whe Roll No l6
Jayo
Union
Rim
Select m
Wame fom Gvly
Soro
bhe Lol do. >9
4
INTERS ECT
y ued to
Combine tuwo S eleh Stetement. Jhe intenSe ot
openaWan Te rn J he Comon bo h
Sateon b

nanbor of
of daahype
dalahype and Colunn bat be same.

han Jhe dala in


cuplicaa and aranjes
4 scenciy ordor by cejab.

bynay .exampk
Sele ck from tible4 3 Jacws on
Inteaseot
Selec

MINUS
Combin Jhe eslt o seleet statement.
Minus opevalor is wed cisp lay the o wr
PresenE in he but
wthich
aosent Se Cond q uery
It han no
cuplcale, data amoyed asondiy
by detaub.
Synax example
Name
Seleck fom Tablu1
Jacu
MINVs 2

select fom Table 2


ho
quony.manly
hi_hot
hom
Sudent fomShudent)
D;
Cma) Nested )
ManWa Max(manus
Shuclen
13 64 68 79 40
38 lyman
o 2n0 Sudo
Shudent name MAX
todisplauy
maz: Sub-quey
er
display (Selec
toble.
follouwins CouYSe isplay fom (Seleck
Shuclont hom
Guene
sQL C. C3 C2 C3
MAX
(Nanuy)
om
= table.
Stucen)
oquey
manls. Manko
toquey (Many
fom
Name SQL
qu
ey exompla. Manlhs
A B Max
Jho. C G Selectohere
Name
Name SQL
sQL max
ohee
Gonsiden Jhis
is
an Select
Queshon Sele
t CoYed
s
NO.
Shudent oite
Waite
Let
w Roll 1 2 3
Wnte
6
L
92. 93
alog
from
uwhere
;Shudont Shudort
fom
may(Manuy)
Sudont a.Jhon
qvecl
Couvsey
shuclont
manly (Selech 1n
display Max
(seany)
from Jhe
ad
CoUNTC*) Jhe
from
Second
highent <> all
en
to
many
ohene to
disp
lay displauy
toqueny Count
(*)>a;
manly is *)
(Count
queuy
Sate Shclon eyoled CouYse
bygrup
Couvse
)
fom
stuclont
(Select 3 2 2
SQL queny &ouvse
Scove
d C2 by
jrup Shuden Couyse
)
Satea
= haviy
Name manky
Seleck Should
be L
selelet sele
ct
mte uoho output
96.
09, 0ite queny to higho manky
display Couvse sisee
and s udo Sloved ha
mans.
oput should be

CI 90 A
Ce

Synlax:
Select Name from shudont uohe
Course,
man h (IN ) (sele ct May Cmauls) from shudent
fom shdent fruphy Couvse)j
Ci
C2 49
innen quosvehnig 68
Jhvee. 0ws
9. what is
difforene blw IN and sQL
Ay opeva hor allows atibue
Componsun
wih Sinsle valu

IN oponatey allous
Companscn ot atihi
mulhne volue

You might also like