Complete Unit 2 PDF Dbms
Complete Unit 2 PDF Dbms
UNIT-2
TOPICS
E.F. Codd proposed the relational Model to model data in the form of relations or tables.
After designing the conceptual model of the Database using ER diagram, we need to convert
the conceptual model into a relational model which can be implemented using
any RDBMS language like Oracle SQL, MySQL, etc. So we will see what the Relational
Model is.
The relational model for database management is an approach to logically represent and
manage the data stored in a database. In this model, the data is organized into a collection
of two-dimensional inter-related tables, also known as relations. Each relation is a
collection of columns and rows, where the column represents the attributes of an entity and
the rows (or tuples) represents the records.
The use of tables to store the data provided a straightforward, efficient, and flexible way to
store and access structured information. Because of this simplicity, this data model provides
easy data sorting and data access. Hence, it is used widely around the world for data storage
and processing.
Consider a case where you wish to store the name, the CGPA attained, and the roll number
of all the students of a particular class. This structured data can be easily stored in a table as
described below:
Any given row of the relation indicates a student i.e., the row of the table describes a real-
world entity.
The columns of the table indicate the attributes related to the entity. In this case, the roll
number, CGPA, and the name of the student.
For complete DBMS subject tutorials visit : ns lectures youtube channel
NOTE: A database implemented and organized in terms of the relational model is known as a
relational database management system (RDBMS). Hence, the relational model describes
how data is stored in relational databases.
1. Domain constraints:
each table has certain set of columns and each column allows a same type of
data, based on its data type. The column does not accept values of any other data
For complete DBMS subject tutorials visit : ns lectures youtube channel
type.
Domain constraints are user defined data type and we can define them like this:
Example:
Example:
);
`std_rollno`: Serves as the primary key, ensuring each student has a unique roll
number and null values are not allowed.
`std_age`: Validates that the student's age falls within the range of 19 to 24 years
(inclusive).
`std_city`: Represents the city of the student, with a default value of 'hyderabad' if not
specified.
Data Integrity: Domain constraints ensure that the data stored in a column follows the
specified data type and range. This helps maintain the accuracy and reliability of the data
by preventing incorrect or inconsistent values from being entered.
Data Validation: Domain constraints provide a way to validate data at the column level.
They ensure that only valid and acceptable values are entered into the database, helping
to enforce business rules and prevent data entry errors.
2. Key constraints:
There are three primary types of key constraints commonly used in database
management systems (DBMS): primary key, unique key, and foreign key constraints.
Let's explore each type with examples:
a) Primary Key Constraint:
Primary key uniquely identifies each record in a table. It must have unique values and
cannot contain nulls. In the below example the student_id field is marked as primary
key, that means the student_id field cannot have duplicate and null values.
Example:
CREATE TABLE Students (
student_id INT PRIMARY KEY,
student_name VARCHAR(50),
student_email VARCHAR(100)
);
In the example above, the `student_id` column is defined as the primary key for the
`Students` table. It guarantees the uniqueness of each `student_id` value, allowing us to
identify each student uniquely.
b) Foreign key Constraint:
Foreign keys are the columns of a table that points to the primary key of another table.
They act as a cross-reference between tables.
Example:
cse_student_name VARCHAR(50),
);
A unique key constraint ensures that the values in a specific column or a combination of
columns are unique across all rows in a table. It allows for the insertion of NULL values
but restricts the duplication of non-NULL values. Here's an example:
CREATE TABLE Employees (
employee_id INT,
employee_email VARCHAR(100) UNIQUE,
employee_phone VARCHAR(15) UNIQUE
);
In the example above, both `employee_email` and `employee_phone` columns have
unique key constraints applied to them. It guarantees that each email and phone
number in the table will be unique.
Advantages of Key Constraints:
Uniqueness: Key constraints, such as primary keys and unique keys, enforce the
uniqueness of values within a column or a combination of columns. This ensures that
each record in the table can be uniquely identified, preventing duplicate entries and
maintaining data integrity.
Example:
Data Consistency: Entity integrity constraints prevent NULL values in the primary key
column, ensuring that every row in the table has a valid and non-null identifier. This
maintains data consistency and helps avoid data anomalies that can arise from missing
or incomplete identifiers.
Example:
Let’s take an example: Here we have an entity set Employee with the attributes Name,
Age, Emp_Id and Salary. When we convert this ER diagram to table, the entity set
becomes table so we have a table named “Employee” as shown in the following diagram.
The attributes of the entity set becomes the attributes of the table.
Let’s take an example. As you can see we have a composite attribute Name and this
composite attribute has two simple attributes First_N and Last_N. While converting this
ER to table we have not used the composite attribute itself in the table instead we have
used the simple attributes of this composite attribute as table’s attributes.
For complete DBMS subject tutorials visit : ns lectures youtube channel
In the following example, we have two entity sets Employee and Department. These
entity sets are associated to each other using the Works relationship set. To convert this
relationship set Works to the table, we take the primary attributes of each entity set,
these are Emp_Id and Dept_Id and all the attributes of the relationship set and form a
table.
For complete DBMS subject tutorials visit : ns lectures youtube channel
Syntax:
Example:
Let's assume the "student" table has the following structure and contains 7 records:
For complete DBMS subject tutorials visit : ns lectures youtube channel
4. SELECT * FROM students WHERE age > 12 AND age < 29;
The "ORDER BY" clause is used to sort the result set of a query in a specified order. It
allows you to arrange the retrieved rows in ascending (default) or descending order
based on one or more columns.
Syntax:
FROM table
"column1, column2, ..." represents the columns you want to retrieve from the table.
"table" refers to the name of the table from which you want to retrieve the data.
"column1 [ASC|DESC], column2 [ASC|DESC], ..." specifies the columns by which you
want to sort the result set. You can add "ASC" for ascending order (default) or "DESC"
for descending order after each column.
2. WHERE:
The "WHERE" clause is used to filter the result set based on specific conditions. It
allows you to retrieve only the rows that satisfy the given condition(s).
Syntax:
SELECT column1, column2, ...
FROM table
WHERE condition;
For complete DBMS subject tutorials visit : ns lectures youtube channel
"column1, column2, ..." represents the columns you want to retrieve from the table.
"table" refers to the name of the table from which you want to retrieve the data.
"condition" specifies the filtering condition(s) that the rows must meet. For
example, "column_name = value" or "column_name > value".
By using the "ORDER BY" clause, you can control the order in which the rows are
displayed in the result set. The "WHERE" clause allows you to filter the rows
based on specific conditions, so only the relevant data is retrieved.
These clauses are commonly used together in SQL queries to retrieve, sort, and filter
data from a database table.
For complete DBMS subject tutorials visit : ns lectures youtube channel
Types of Keys
o Keys play an important role in the relational database.
o It is used to uniquely identify any record or row of data from the table. It is also
used to establish and identify relationships between tables.
For example, ID is used as a key in the Student table because it is unique for each
student. In the PERSON table, passport_number, license_number, SSN are keys since
they are unique for each person.
Types of keys:
For complete DBMS subject tutorials visit : ns lectures youtube channel
1. Primary key
o It is the first key used to identify one and only one instance of an entity uniquely.
An entity can contain multiple keys, as we saw in the PERSON table. The key
which is most suitable from those lists becomes a primary key.
o In the EMPLOYEE table, ID can be the primary key since it is unique for each
employee. In the EMPLOYEE table, we can even select License_Number and
Passport_Number as primary keys since they are also unique.
o For each entity, the primary key selection is based on requirements and
developers.
2. Candidate key
o A candidate key is an attribute or set of attributes that can uniquely identify a
tuple( here values may or may not be null ).
o Except for the primary key, the remaining attributes are considered a candidate
key. The candidate keys are as strong as the primary key.
For example: In the EMPLOYEE table, id is best suited for the primary key. The rest of
the attributes, like SSN, Passport_Number, License_Number, etc., are considered a
candidate key.
For complete DBMS subject tutorials visit : ns lectures youtube channel
3. Super Key
Super key is an attribute set that can uniquely identify a tuple. A super key is a superset
of a candidate key.
4. Foreign key
o Foreign keys are the column of the table used to point to the primary key of
another table.
o Every employee works in a specific department in a company, and employee and
department are two different entities. So we can't store the department's
information in the employee table. That's why we link these two tables through the
primary key of one table.
o We add the primary key of the DEPARTMENT table, Department_Id, as a new
attribute in the EMPLOYEE table.
o In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are
related.
5. Alternate key
There may be one or more attributes or a combination of attributes that uniquely identify
each tuple in a relation. These attributes or combinations of the attributes are called the
For complete DBMS subject tutorials visit : ns lectures youtube channel
candidate keys. One key is chosen as the primary key from these candidate keys, and
the remaining candidate key, if it exists, is termed the alternate key. In other words, the
total number of the alternate keys is the total number of candidate keys minus the
primary key. The alternate key may or may not exist. If there is only one candidate key in
a relation, it does not have an alternate key.
For example, employee relation has two attributes, Employee_Id and PAN_No, that act
as candidate keys. In this relation, Employee_Id is chosen as the primary key, so the
other candidate key, PAN_No, acts as the Alternate key.
6. Composite key
Whenever a primary key consists of more than one attribute, it is known as a composite
key. This key is also known as Concatenated Key.
Views in SQL
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in
a real table in the database. We can create a view by selecting fields from one or more
tables present in the database. A View can either have all the rows of a table or specific
rows based on certain condition.
Views act as a proxy or virtual table created from the original table. Views simplify SQL
queries and allow secure access to underlying tables. Views in DBMS can be visualized
as virtual tables that are formed by original tables from the database.
For complete DBMS subject tutorials visit : ns lectures youtube channel
Sample Table
For creating a view (simple and complex views), and updating and deleting the views we
will take some sample data and tables that store the data.
Let's take an employee table that stores data of employees in a particular company:
Employee Table:
This table contains details of employees in a particular company and has data fields such
as EmpID, EmpName, Address, Contact. We have added 6 records of employees for our
purpose.
EmpRole Table:
This table contains details of employees' roles in a particular company and has data
fields as EmpID, Role, Dept. We have stored all the records particular to the EmpID of
each employee.
1 Intern Engineering
2 Trainee IT
3 Executive HR
4 SDE-1 Engineering
5 SDE-2 Engineering
The view can be created by using the CREATE VIEW statement, Views can be simple or
complex depending on their usage.
Syntax:
Here, viewName is the Name for the View we set, tableName is the Name of the table
and condition is the Condition by which we select rows.
Simple view is the view that is made from a single table, It takes only one table and just
the conditions, It also does not take any inbuilt SQL functions
like AVG(), MIN(), MAX() etc, or GROUP BY clause.
While creating a simple view, we are not creating an actual table, we are just projecting
the data from the original table to create a view table.
Example 1: In this example, we are creating a view table from Employee Table for
getting the EmpID and EmpName. So the query will be:
Now to see the data in the EmpView1 view created by us, We have to simply use the
SELECT statement.
Output:
The view table EmpView1 that we have created from Employee Table contains EmpID
and EmpName as its data fields.
EmpID EmpName
1 Alex
2 Adolf
3 Aryan
4 Bhuvan
For complete DBMS subject tutorials visit : ns lectures youtube channel
EmpID EmpName
5 Carol
6 Steve
Example 2: In this example, we are creating a view table from EmpRole Table for getting
the EmpID and Dept for employees having EmpIDs less than 4. So the query will be:
Now to see the data in the EmpView2 view created by us, We have to simply use the
SELECT statement.
Output:
The view table EmpView2 that we have created from EmpRole Table
contains EmpID and Dept as its data fields.
EmpID Dept
1 Engineering
2 IT
3 HR
The complex view is the view that is made from multiple tables, It takes multiple tables in
which data is accessed using joins or cross products, It contains inbuilt SQL functions
like AVG(), MIN(), MAX() etc, or GROUP BY clause. So, whenever we need to access
data from multiple tables we can make use of Complex Views.
Example:
In this example, we are creating a view table using Employee Table and EmpDept table
for getting the EmpName from the Employee table and Dept from EmpDept. So the query
will be:
Now to see the data in the EmpView1 view created by us, We have to simply use the
SELECT statement.
Output:
The view table CompView that we have created from Employee Table
and EmpRole Table contains EmpName and Dept as its data fields. We have used the
cross-join to get our necessary data.
EmpName Dept
Alex Engineering
Adolf IT
Aryan HR
Bhuvan Engineering
Carol Engineering
Steve Engineering
Syntax:
Example:
Output:
Now SQL Editor will give us an error saying the table does not exist as the table is now
been deleted.
For updating the views we can use CREATE OR REPLACE VIEW statement, new
columns will replace or get added to the view.
Syntax:
For Updating a view CREATE OR REPLACE statement is used. Here, viewName is the
Name of the view we want to update, tableName is the Name of the table
and condition is the Condition by which we select rows.
Example:
let's take the above created simple view EmpView1 and we want to one more column of
address to our EmpView1 from Employee Table.
Now to see the data in the EmpView1 view created by us, We have to simply use the
SELECT statement.
Output:
The data fields of view table EmpView1 have been updated to EmpID, EmpName, and
Address.
1 Alex London
For complete DBMS subject tutorials visit : ns lectures youtube channel
3 Aryan Delhi
4 Bhuvan Hyderabad
6 Steve California
Reloskon Aqeba n obaboc roreernn
databoe merqertn
Reliono Ageba nentol ontop
S aunde onanipslate
and Yectriee odata
h holps s
Gt Optraions
onsiss
relakon dabobál
opaiedo elbis(toblet).
+hot Con be
to (odd,
vokodad b
Releons gcbvo wo the
P r o a d r y o
s he
yoult. t
obtaln
to
Step y e proos
qives
eovetien Jundeim
prowde P r o v d e
here is
Agebra mainy
m a l n l
puve matkermaiy
D,Lenak
relehen dstabalalg, T s p v
Alaebn:T
Rlaona
i n . R.laome
yusoyd UStYs
lis
Eg opraans
t l
m d h
ernachca
e n a h o
Stored ln tabk.
Prowde
ta
Fo nernpulak
in
eletiom Wgebra
elabma ebra
G ) opevaiong
operctors
arvio ypes
Relaioralopenstos
Jons a )
Se-operationj
produet(x)
Coytes'on Union (u)
opratont inneY
a)terdediom (n)
Pelationa!
n
nary'
U stDfon -)
a) p r o j e t ( Joturl jan*Y |Letoutrjo)
Rene P) e t oin[8) |ight aster Jam
EAprjoinC=) ||tuu outy'jon
har yelaion Oprration
here clause )n
SQL (Relation)
y tox -
bxomple Shudib Selecondihion
rolno
Soi Studunt
Shiva 2 bLomple: (on-2a)
3
Nagenda
.1 olno age
Si
2 output nam
19
t u m Ghudek shiva
wrt ollno =a9 dipo
enire
( Studbht
omplea: aqe= 12
Saj A
nam
om voro ag
outpt
Sa
displosy
dupliates
pojocim fT) elet pece6Jurnny
is u t d o
The projecfim Opcyaken youo
he othev (oumd tlous
hule disaveinq
d orn a tablewbo
cxtae eintomaim
tprovej
yntox T AraAnRelahom)
xompe
GHudant)
Stdant nanas
xermpe
name
a odpu
Sai
shiya
19
23
Shiva
onendraa
gnd ra1
8
hose is19
neme
(Studart:)
T (aqe 39)
nom
Shiwa 19
nome
S
3 Renarme
he
Lles nd (urnn.
0taknama
DC dab4)
Cshuadaenthi)
abax 6eutabk.nomns
xenarMi
.
St dant
SyntaEe
nome myna
(ucokuL
4aha nem) umo nom
1uwtalurinnorne lumn noma
Nom
axteSian Poduet()
ation USed in
Pwdud Ope
DgMS he Catesan wS
ornbin all poss:b pairs
clathon aebra
am wo talles (ontans Qve poss:b
reulty in ne
bchwen
rus
p r o d u t
(ombinatien (voss
s drobed he
(avtegan pvodut
The
Symbol(x
lin
Synta
X p o j e E
Shdsnt
P o j e t
(urnni toblas
hwo. tablay naend a 2
Sel oprvohont USedo rmoripulafe
opevatons az
Yolakno bles
ombire
E oYous
and
SeDterena-)
irerseetim (o) vaheves the rrus
r us
v i v s the
Uoin (u). etrieve
onu tohl tho
(ombine he
ioterSe ciro aperacim
unom
optratim nus
borwean
The
tbleydtoody tme
(onno ave pYejnt- in
y0som
wo
all
drieve
tLu. TE that are Another
rbot
yes T t h
Prelentin both tobly
evnb duplkokrns
Y e m o v e
any
acoost in
tableh norund
S thle b t avs
table
h shn the Secoad
u B4 e A-
cmp_A1,3
A nB$
A-
0tpet
Prmet
n o
ole rollno
Sa
Soi 12
ame
Sai 12
tudant - prj«
30
Yemash
Shiva yamuh
14
agnd 0
Suryh Nom
rh sa ramyh 3
Suavsh
ol
ame no
So
JoinS )
Monag erent
DBMS n operahoy
vema dbabase
in elachna
gebva o (onbin nutp
USed
(onm
atin bute anehin.
oble oed
(oumn
elatednovnahro
cdriem
Join opevadi onj loS.o
Spetke (olorans
materg Val
Onn'
have matehinq
inne juin etum g }he wS
jin (enditiro ,
Yelton
9- , !=, 4, 7,=, 7
veotion1
yelienrtea1aHeNtlumna
(oumo(oummn
dono Dom
PTHL
stno
nom
Soj
Soi ATML
CsE Shvo
Cva
Shiva2
dportrotat
ouput daphno Dnorn
Sh dpno id
Sa CsE
deposnut"
Soi ATML
Shiva
Si
ui n Cherrshen
6tomp pu
dupaytmand Dnorn
Shudes nom daptno
nom daptno ALHL
nom
daptno ATML
Sa
Sa
ssva
Shiva
tabkond
ute joins alt
turnj
join 6thcY
e
Jdrm
S antron nut Valus
h r e u l t - will
matth.
matr
wth
/ype
Kh
t nus
nws
usmn t h Ycum o lt
all
tumy
jm rturn babley and
A l e t orutr
let 16 ad b emakkn
ondthe
ond nahksng n bsth
1 - , * b k
for th
whe
heYe
valu leuded mh ln spech
meth io ypech
bab le
ighe
Sytox Plam
|Sytex Pln
Peletiroa
na(Janneno,ltin L C
o lolamn m
Cann
depestrn
Daorna
n a m
ATHL
Sai
Sva
3nsmdaptro oce
apavtrnan
ATML
So
dpenobd
3 NUL UL
porrntE
Snomlaptro no
pno
Sa
NUL i NULL
epoan Snodooe
Sai A
Dnone
(AiL
pt d
ka 3 NULL
NUL NUIL
(CsE
Keladiona Culat
USe d in DeMs
Relsiona0 Co. sis a yo nguage
a
rrr
toSpechy what sala we JantJo vchicwe
Yelahons databojos
proaduro Qw
arq uag e
is a
o whot todo, ond st hauw to do it,
wok
not dascibe abaut h the un w oY
wiu
elehiona Cula o
T-ple laionCIudusTR
onasn .latton. (LsDPpe)
rrws or reord
Tuple relaHonad Caadus Tp)_Tupls ou auo kran
(ondibmo
s ple Glat
hve appdbed t»
(ondken that i
(rrden(+) uplas
Shadests
tamp rade
a m L
frernash
Suruh
han 0 we (on
o,
we Conb
okty
Gadenks.ohose ape
othe (:+his
nd Caldus
t pleyeleon
AND S. Age7 2o
GHudenks(S)
w e are Seleebi
ryprats tuplerfa , p s (mus or tebl
Stdant Shruld&qrahdtha
radt
oleirnk CSadsDRC)
om
properie
(mas
ttibuti on)
means
ke
:ke uple Rlahorel
CLealus S
Docnan Ralekirne
wL Seler
m
exre we
(nhon,
balee
enq uae
Used appl
CtdureK
o n eiary on
(armny tnskad Speying
Conndtons
splu)
FC, 3 , - . .
ln)
C, Cj (3.
.
Syntax
ornd+ton
onp aden
Ag
Irad
A
S
A
Sova
myh
Suveah
ojesh srase qade ae
eant
Oont
A OR S.
SGrads =
Grdds=
(s)bwo S.Gvade
lamu
.Nameu dant
Condr nt h , h
dt
A
oems lumn. m
Oupot NamL
S
Ssva
Ouctpuk ame
Srub
For complete DBMS subject tutorials visit : ns lectures youtube channel
UNIT-2
IMPORTANT QUESTIONS
1. Explain Relational Model.
2. Database languages( DDL, DML, DQL, TCL, DCL)
3. Integrity Constraints ( Entity integrity constraints, Referential Integrity Constraints,
Key constraints, Domain Constraints ).
4. Various Types of Keys ( primary key , foreign key, super key, candidate key,
alternate key, composite key ).
5. Inclusion dependence.
6. Querying in relational data ( hint : using select command)
7. Logical database design ( converting ER diagrams to tables with and without key
constraints).
8. Views? Creating views from single and multiple tables, updating and deleting
views?
9. How to Drop tables and views using sql?
10. What is relational algebra and what are its properties?
11. Fundamental operations in relational algebra and explain with examples?
(selection, projection, Cartesian product, set operations, join operations)
12. What is relational calculus ? explain tuple relational calculus and domain relational
calculus with an examples?