DBMS (Unit-2)
DBMS (Unit-2)
UNIT
Relational DataModel
and Language
CONTENTS
2-2A to 2-6A
Part-l : Relational Data Model
Concept, Integrity Constraints,
Entity Integrity, Referential
Integrity, Keys Constraints,
Domain Constraints
.2-6A to 2-10A
Part-2: Relational Algebra
.2-10A to 2-12A
Part-3 : Relational Calculus, Tuple
and Domain Calculus
.2-12A to 2-13A
Part-4: Introduction on SQL:
Characteristics of SQL,
Advantage of SQL
.2-13A to 2-22A
Part-5 : SQL Data Type and Literals,
Types of SQL Commands,
SQL Operators and
their Procedure
.2-22A to 2-25A
Part-6 : Tables, Views and Indexes,
Queries and Sub Queries
Part-7: Aggregate Functions, Insert, 2-25A to 2-29A
Update and Delete Operations
Part-8 : Joins, Unions, .... 2-29A to 2-33A
Intersections, Minus
2-1 A (CSTT-Sem-5)
example
2 LFor : 4 L
3. 2 Answer Que
acoounts The The Each the TheItisthe data
Arelational
Table tables relationships 2.1.What Lang 22A(CSIT-Sem-5)
relationships,
tablerelational Ralotional
and primary Answer
A-4 A-3 A-2 A-1 represent
2.1l has
acen0. C_104C_103C_102C101 eust id Table Bntity
model
multiple mode
Table shows data is Constraints.
Constraints,
Table
2.1 3 among Type DomainConcept,
Data
a uses data isl relational Interity,Model
showsdetailssimple modelcollection a
2.1.2 those semantics
columnscollection Questions-Answers
and
balance
4000 3000 2000 1000 2.1.1
Akash
: Alok AmitAjay name C whichrelational for
Account of data.
commercial Medium Referential PART-1
model
Customer : bank and of
accounts and
conceptual
table each tables of
customers,database. consistency ? Relational
Chennai
Explain Answer C'onstraints
Integrity
Kolkata
MumbaiDelhic_city table column data lntegrity,
belong to
represent
processing tools
has
Type
Table
to constraints. for with Data
which a Keys
unique describing Questions Model
2.1.2 both example.
customer. applications.
shows data &
name. Language
and data,
4 3. 2 1. 3 2 1 5 3
Types Answer Que2.2. 4 Management
Database
System
1 i. i. an The
CHECK: DEFAULT: UNIQUE: NULL: ed/
NOTupdatof Constraints
d el ete d A (acc_no) A-1 The 1000. 7Thecust_id The
colurmn This there The cannot unique Ifvalues.
aUNIQUE column ByWhen NULL a value.NOT whole constraint belongsTable Table Table
col umn
update/delete/insert
record constraints
A-2 C_101
constraint DEFAULT is specifying weNULL 2. 2.1.2, 2.1.1,
of no have cannot in to
purpose enforce is Explain to 1.3,
a do a belongs is C_104C_103C_102C_101 cust id
table. value constraint
has not from rule the i.e., i.e.,named i.e.,
duplicate a haveNULL table,
aconstraint : oflimits constraints cust Table
isconstraint
used provided unique provide constraints a that to
depositor accounts,customer
it into table. the Ajay
NULL to is whose 2.1.3
for values enforces constraint, takes valu e a the used cust
constraint, makes table. table, and A-4 A-3 A-2 A-1 acc
no.
specifying whiprovides le and whose
in a
values. NULL for is data for
to
cust_id shows livestable, Depositor :
sure or its shows
inserting a table. a itcolumn we a maintainoptimizationtype that shows in
default particular
value types. cust is
range means make that that Delhi.
of C_101
_id account the table
a or a
ofrecordvalue set by the data is
account
values that sure column column
default. C_102 and customer (CSTT-Sem-5)2-3 A
of data that
purposes. A-1
into toparticular columns that account has
for a while does integrity can and number
columna
a a be a
identified
particular table. to
particularinserting not likewise. balance
column duringinserted/ number
(acc_no)
when have hold
of by
24A(CSIT-Sem-5) Relational Data Model &
A When this constraint is being set on acolumn, it
specified column must have the value faling in theensures that.
Language Database Management Systen
2-5A (CSTT-Sem-5)
i r the
attribute, then
specified range. bIfarelation has a null value in the primary keybe maintained.
& Key eonstraints : uniqueness property of the primary key cannot
primary key cannot be
i Primary key : Example : In the Table 2.4.1 SID is primary key and
A Primary key uniquely identifies each record in a null.
table Table 2.4.1
b It must have unique values and
cannot contain null.
Ë Foreign key: SID Name Class (semester) Age
& Foreign keys are the 19
columns of a table that points to the 8001 Ankit
primary key of another table. 18
b 8002 Srishti
They act as a cross-reference between tables.
22
6 Domain constraints : 8003 Somvir 4
19
Bach table has certain set of columns and Sourabh 6
same type of data based on its data type. each column allows a
The column does not accept values of ii. Referential integrity
constraint :
any other data type. Table 2.4.2 refers to the
Que 23. Explain This rule states that if a foreign key in foreign key in
integrity primary key of Table 2.4.3, then every value of the
constraints. Table 2.4.2 must be null or be
available in Table 2.4.3.
Answer Foreign Key
L
Integrity constraints provide a way of ensuring that Table 2.42.
the database by
authorized users do not result inchanges
a
made to
loss of data ENO NAME Age DNe
2.
consistency. 1 Ankit 19 10
Aform of integrityconstraint with ER
& key models is : 2 Srishti 18 11
Not Allowed, as DNO 14 is not
declarations :
entity set.
certain attributes form acandidate key for
the
3
Somvir 22 14
defined as a primary key of Table 2.4.3,
Sourabh 19 10
4
and in Table 2.4.2, DNO is a foreign
form of arelationship : mapping cardinalities 1-1, 1-many and key defined
3
An
Tmany-many.
integrity constraint can be any arbitrary
4
database predicate applied to the Relationship
Integrity constraints are used to Table 2.4.3.
data in a relational ensure accuracy and
database. consistency of DNO D. Location
Que 24. Explain the 10 Rohtak
following constraints :
Entity integrity constraint 11 Bhiwani
i 12 Hansi
Referential integrity constraint
üi. Domain constraint
Answer Primary Key
Entity integrity
eonstraint :
This rule states iii. Domain constraints :
that no attribute of attribute can
value. primary key will contain a null a. Domain const raints specify that what set of values anvalue from the
take, value of each attribute X must be an atomic
domain ofX.
A 2-6A
Example : (CSTT-Sem-5)
2 3 2 1
Answer is
BasicL
2.5WhatQueis not
operation
Project : difference,
d operation
Select : The and ItThe Long
relational producesconsists allowed string,
in The
gument Ihe The TheSelect The operations relational the
Answer 8004 8003 8002 8001 SID data
argument
project predicate select of here
correspondingtime,
date,
operation cartesian type
algebra a a
relation operation innew algebra
set Type because
of
relational associated
peration appears the SourabhSomvirSrishti Ankit Name
relation relation
operations Questions-Answers currency
is product Relational
Algebra.
relational is and
with denotedoperations a Age domain.
selects procedural PART-2
as as algebra Medium
certain is is and is with
in a a an (semester)Class ete.
parenthesis by
asubscript tuples algebra
rename. result. that Relational
domains
unary integer An
butes sigma are take
that
query Discuss ?Answer
6th 4th 1st
attribute
1st
eration to(o). as are one attribute. includes
satisfies
o. follows select, language.
after or Data
left Type
two its value
out. the basic sinteger, Model
that a project,
: relations Questions
o. given must
A 22 18 19Age
returns operations.
predicate. union, be &
as Language
character,
available
input
1t5 Set
5. 4 3.
Management
Database
System
e. C. b. a
h. f.
Registered Student
Course
(code,
Use code)
(ssn,title) Que2.6.
b. a a a.
b C Set C. b
d. operation
Rename :Cartesian
and Name
SSNs The List List
(registered
registered
courses). List
relational
stems The andSSNs r difference
The
that Projection In
(ssn, The
new The thereturns Given The product toThe but The
analysis titles the the the combine project
name
analysis of of of same rename not
cartesianexpression are set
students title codes rename rename
Consider names a
and students students codes of name, the of product difference
in in
of algebra operation
courses of relation relational relations one
s. operation is
alysis of of of denoted
students registered of address,
given operationresult operatorinformation
operation product relation
r-s
algorithms.
algorithms. who who andcourses the
to courses operationtounder operation
for of
algebra
are the answer following the r, produces duplicate
by
of are PrA1, expression is and
operation, :
who which for major) can can but pi
original a from
registeredtitles courses.
rithms.registered in
P(E) denoted r, (I).
xA2, benew be
expression : are
denoted
are which the is a
which relations ....usedname.used relation not rows
of no E written any
egistered attributes
An by denoted
courses
student nofolowing: to under
to rho two in by are
for for at
student
(E) obtain
rename E,
both as another. ()eliminated.
containing
both least : the (p). relations.
rË by
they is of allows (CSIT-Sem-5) 2-7A
for X a
databasedatabase
registered. is one original new a namea rgcross
both registered relationr us
registered. The those to
relation x. (x),
student relation find
databasesystemssystems cartesian
allows tuples
to tuples
to. wit
is as get us in
C.
1 f&g. h. b. Answer Li(CSIT-Sem-5)
stof
j. i. 2-8A
2 The algebra?
Answer 2.7.
Que
pane TFeode Kie Feode List
additional
intersection
Natural operation: Set eode,
function
ssD A=pl Tpame
) Tesn A=ge Ro Taane,
attributes. operation (Student
Student) (A
D
(Student
(Student titl(Reode
e (Course) (Course
(Registered) of
arguments,
that denoted
The certain The tuples Seti
tintersection (Registered)
Tgsn /esn /
What(Registered) (Student Student coursescourses
appear natural natural join thatoperations (Course)
Teode -
selections
by ba
operation is
ba ba(Registered) -Tode ba
performs the written are are Registered Registered Registered) in in
join
in join rns=r-(r-s) Registered
ba
both join is
in ba which
operation and is both of the Registered Registered which
relation symbol denoted
a : as relational
a binarya : of additional (Student)
selection cartesian its b-a balo,jitle
ba
(Registered)
Course) Da all all
by major (o,ile
schemas forms argument (o,tle ECMP'
operation
. algebra ECMP = Da a students
forcing and ,
product
a
='Analysis (o,;tle
=Database =Course) Relational
and
cartesian returnsa
'Analysis
equality that relations. are operationsStudent) = major
finally Database AKTU
into : are
allows relation of of students
product
removesthose on one is The Systems'
Algorithms' Algorithms' registered. Data
2015-16,
operation. us set in System'
to intersection that Model
attributes
duplicate of relational are
its combine contains Course) Marks
registered. Language
&
two It Course) Course)Course)
u 10
3. 2 1.
V.
4. Management
Dat3.abase
System
V. 1 vii. vi. iv. iii. i . i. student (id, Que2.8.
vi. . Answer subject(code, enrolled
lecturer)code)name)
(id, using b. a In
only The operation
Who What
WhatWhat Who Who Which works follows:asThe
Assignment Division :
Inameoode relation, For
lecturerOcode Tcode
ThecturerOcodeTnameCeode the
following: if division
ecturer°R this teaches are
i .=,(S]
like
division
[S] i. For tis relation both
enrolledin)) Oname areteaches
areteaches relation r+s=Ip-s in
query
subjects the Give every II
of r
we = = the the assignment R-=t
S] operation,
le=cture wil = = cs3020 theoperation operation tupl e r). g two sis +
Hector(studentb namesnames cs1500atcs1500 names al
es150oo(studentD =call cslwe1500 es1500 least is (r)-Ils conditions a
schema
following t, relation
Slecturer have (Subjvect)
(studentbenrolledin)
the code m Hector
or ? of in can in division
to of oftwo a : be s,
subject = students
students cs3020 students : The th ere
AR.codec relatecs3020
different taking programming (1gr) written on
hold operator
enrolledin)) relation enrolledin) ? queries assignment is schema:
>S. subject
(subject) , in a
code in in ?
enrolled x tu ple
both
cs1500 s) terms
- R is
pS) R to subjects in
language. t, -S.
denot ed
AKTU of inr
(ame U anditself. es in
the operation,IR_S, A
S. fundamental by 2-9 A
(C To 2019-20, 1500 or ? cs3020
cs307 relational ))s satisfying tuple (CSTT-Sem-5)
the
eodedisambiguate and ist
= ? ?
denoted in
symbol
ess07student Marks cs both r
1 operation *
200 algebra by of
sif E
the 07 ? , the and (+).
2. 1 4.
Tuple 3 2. 1
Important 3 2
What
Answer1 characteristics. Que2.9.
aboutitsresults.
for ItThe retrieval. obtain
the languages.
relational
Relational (CSTT-Sem-5)
In In The query.
variables.
In these
formulas
Relational vii. 2-10 A
describes
obtaining Relationalrelational
TRC relational a Relational is Long
relational relational tuple
characteristics amelOcode
enrolledin)
is Relational 00(studentb
a calculus consisting What
that the
non-procedural calculus
calculus Ans
desiredCaleuluscaleulus,calculus, relation
formation. calculus caleulus, Explain wer
is is Type
based of is is relational Caleulus, l500 ea
information output al
(TRC) user a a a
query
is of there numbernon-proce Questions-Answers
calculus tuple and
query ist is on
Studentbd
used
relational
available
: predicate
not Medium PART-3
is system
of and
OR Tuple
language. to no
variables calculus
procedure
without
giving concerned
procedure dural and
measurethe description domain
where domain and Relational
without calculus. calculus query Answer enrolledin)
name O
and AKTU ? Domain
with
queries Describe
calculus.
ga an
language.
of relational Type
knowing the selectivepower : expression 2019-20, Data
specific how
are Calculus
itsQuestions Model
the toexpressea
evaluate Marks
involving calculus important
method &
to Language
of a as 07 code m
?
4 3 2 1.
Domain 5. 4 3
Management
Database
System
C. a C b d C.
b a Anwhere
formula An
domain, b. a A That
3or a. notation A
Following DRC Formulae terisused tuple query
An variable.
domain cdomain x x Xyy T,atom expression Relational If If An
PP IfIfP, is0c,operator 0y, X, uses relation, P,Pz P, P,IfP is,
P, atomn ...., yycompose in rather atom in
is where a (s) is are
variable t[A] it
is
Xy domain and
and a areconstant that where ..., DRC
is T, is a to th e TRC
formula (<, then a formula, isbuilt is
P, a the inthan P, a denote used set PO) l| is
formula.
x can
is S, x are has of the Calculus formula is
are rules and *,>Er, atoms. -, variables 3s are formula. using said expressed
in a be=, domain one , DRCvalues to of
then domain
the *, y Erformulae, then that al
formula, to compared.
>,are of todenote tuples
build represent is containing
(P,(s)) the be
so domain ). where the
variables so tuple
isP variable, domain of for that(DRC) atoms a as
up The following the an are free the t :
then r and tis such
the is formentire take : then ¬ value
of
attributes a domain a P and variable in
the 0 variable relation or free that
so formula is domain : on
ser(P,(s) soand the relation of
are formns tuple. predicate
attribute a variabl values tuple are tuple
P,
comparison xand
(P). following unless
: on : P, r. (CSTT-Sem-5)
2-11 A
v andconstant. n variable t
0 from v it onPis
P, for attributes
is are P,
must y a represents Pa rules: is
attribute
P, which
operator an also s, quantified true
comparison P
A have attributesformulae. and for
P, and a
Py
r A t.
and isanda the is and
x,, by and The
a
4 3. 2. 1. 4. 3. 2. 1.
Answer
SQL.ofQue (CSIT-Sem-5)
2-12 A
b. .
It
Charaeteristies SQL:of Theabase It ItSQL 2.10. Long Introduction d.
can
datmanagement is
that that two stands
a BxIf
nlikpre operforEach SQL usesSQL
SQL usage Data be Answer
statements a retrieve, Data Write (P,(x)) P,
free is can can major and used
non-procedural (x)
for
ertaiinnsyntax
arequest orm be be for of on is
fin short Type
and a
data
Structured SQL:Characteristics
is a
ion ncatiusedtioenspecigoriefsying
extremelyManiinpsertul,atusedDefi formula
defining x
delete to to stored Questions-Answers
note V(P,())
iacmucanlmiaberng anpard stoed syntway ax and
best flexible . ereate,
Language the
writ econlumnoptimize bythat Language access
and of lthaenguage on Medium PART-4 in
SQL
securi SQL. are x,
tyrelationalinQuery
where
languaingaesor, the suithe tedgivtoes update and modicommands fy structure that Relational
and variety be RDBMS the Explain Answer also
can of
:
rtheerquese t. them. user manipdatula(aDtML)e : (DandDL)constraints.database.ofLanguage.
finished of is before in
are data, be
SQL, formulae. isx
the a DMLdelete DIDL
used various Type Advantage aData
tages ways. inno : domain
a provides modifying for Questions Model
ability database. prdattohedatavi, desabase
of
singleneecdxectoution, to characteristics variable,
line.sart to data retrieval of &
SQL. structure SQL. Languape
in
P The S check
commathat nis,dsobjcoemmacts. nds
to the and then
3. 1 4 3 2. 1
5
SQL1
AnswerQue Disadvantages Advant a ges Managenent
Answer
SQL: DatabaseSystem
of
given other of SQL,it. not No isand
lengthn.char Cost: users
Partial CompleInteractive x complex Portable
Standardi
anyplatformsedUPDATE, doneFaster
supports 2.12. Long SQL coding
required.
(n) to whi ch effic ientinly,
:A Answer Dat a the
uncomfort
control:
Someable applicatplatform
queries io ns : etc
What interface of
worldcwianItde makes skillsalmost query
fixed
following SQL Type database. versions language are AIl
are SQL can be
language: used Operat
processiionsng
length T'ype Due (Operat i ng
as used to it basic For : no
the Operators and : be per a time.
and to arewhile SQL : all
datatypes different received : user-fri
in its endiy and data
keywords
character Questions-Answers Literals, hidden costly like :
Medium dealing
PART-5 Easy Systprograms
em, Due also need/requirement/use.has users.
and and in to
retrieval,insertion,Large to the
: business a
string theirTypes hence,difficult
with seconds.learn document
etc). inatisyntactical
datatypes Answer
the PCs, language.
on suchlarge amount
as
with rules, and Also, deletion, of
Procedure. SQLof programmers interface
database. server,
it SELECT, data
user used Type understand, rulesnumber can (CSTT-Sem-5)
2-13A
complete it is
specified in Commands, laptops
beprovides are
manipulation
Questions that em INSERT
ofretrieved
not lines
SQL?
maximum
control cannot makes bedded
answersindependent compl
a ex of
isacCess uniform INTO. code quícklofy
not few with in data
to is
Database Management System
Balational Data Model & Language 2-15 A(CSTT-Sem-5)
-14A(CSITSem5)
string with user specifod Que 2.14. What are the different types of SQL
commands?
2 TArChar in) Avariable length character
mau length n machine Answer
subset ef the integers that is
intAn integer which is a fnite Different types of SQL commands are :
degendent integer
machine independent subset of
L Insert :
small int :A smal integer is a
This command is used to insert tuples in a table.
defined precision. It This command adds a single tuple at a time in a table.
mumeriej:AEned peint number withuser the right of the decimal
b
are to
ists ofp igits and d ef thep igits Syntax :
Insert intotable_name (attribute, , attribute,) values (values list):
peünt and double precision floating
mlor dble precision:Floating
depemdemt precision 2 Update :
nbens ih machime This command is used to mnake changes in the values of attributes
precision of at least n digits.
Boat in:A Snatingpeint mumber with month (two digit)
of the table.
(four digit),
date :A alendir date cumtaiming a year b It use set and where clause.
nd day i igt af the mnth
and seconds. Syntax :
&sine:The time f the day in hours, minutes Update table_name set attribute _narme= new_value where condition;
used in SQL?
ur 2iL What are the types of literal 3 Delete:
Thiscommand is used to remove tuples.
Ansmer b. Tuples can be deleted from only one table at a time.
The four ind f ita aes uppoted in SQL are: Syntax
L Charter string: Delete from table_name where condition;
Caratertrings ane writen as asequence ofcharacters enciosed 4 Belect : This command is used to retrieve a subset of tuples from one
ngegte or more table,
2e ge gute charater is regresented withán acharacter strin
Syntax :
y egutes For etamgle, Comter Engg, Structured
y lngg Belect attribute,, .,attribute, from table name where condition;
6. Alter table :
2 Bsring:
in
4 Aering is wrieseter asa seguenee of s and ls enclosed This commandis used to rmake changes in the structure of a table.
the b. This command is used :
Seadeil digts ened is singe qutes ard preceded by to add an attribute
Freangle, 1011011,EY, BY,XAT,KT to drop an attribute
W torename an attribute
geddocimal number
to sdd and drop a constraint
Hyntax s
Alter table table name sdd column nane datatyp,
Biterals Alter table table name drop eolumn column name,
Ayyete ere lierse ars written as ezat igedinteget Alter table table iame drop constraint eonstraint name,
Write ashort note on BQL DDL commands.
Relational Data Model &Language 2-17A (CSTT-Sem-5)
2-16 A (CSTT-Sem-5) Database Management System
Answer Answer
sOL DDLis used to define relation of a system. The general syntax of Relational schemas :
assets)
SQL sentence is: branch (branch-name, branch-city,
customer-street, customer-city, customer-id)
VERB (parameter 1, parameter2; .... parametern) customer (customer-name,
The relations are created using CREATE verb. account (account-number, balance)
b.
1. CREATE TABLE: This command is used to create a new relation loan (loan-number,amount)
telephone-number, start- date,
andthe corresponding syntax is: employee (employee-id, employee-name,
CREATE TABLE relation_name
employment length, dependent-name)
payment-amount, payment-date)
(field1 datatype (size), field2 datatype (size),., fieldn datatype payment (payment-number,
(size): saving-acco unt (interest-rate)
2 CREATE TABLE.. AS SELECT ... : This type of create command checking-account (overdraft-amount)
is used to create the structure of a new table from the structure of
existing table. branch-city
customer-street
payment-number payment-amount
1
ALTERTABLE.ADD._
into an existing table. The
:This is usedto add some extra
columns
Customer-id
customer-city
loan-number.
amount
generalized format is :
ALTERTABLE
ADD
relation nane borrower
Loar
loan
pavment
paynent
2
ALTERTABLE .
width as well as dataMODIFY
(size);
.: This form is
used to change the
Aggregation
cust-banke type
acount
Generalizatie
Syntax is: type of existing relations. The Specialization
generalizea manager
ALTERTABLE
MODIFY relation name
(fieldl new
employee
worker
works-t
Marks 10
Database Management System 2-19 A (CSIT-Sem-5)
2-18 A (CSTT-Sem-5) Relational Data Model &Language
Unary operators (B)
sQL DDL of ER diagram : varchar (40), +, - Denotes a positive or negative expression
create table branch (branch-city
branch-name varchar (40) primary key, Binary operators (B)
assets number (20));
Multiplication
create table customer (customer-id number (5)primary key,
customner-name varchar (40), Division
customer-street varchar (20), Addition
customer-city varchar (30) );
Subtraction
create table loan (loan-number number (6) primary key,
amount number (10)); Fig. 2.17.1. Arithmetic operators.
(employee-id number(5) primary key, used to compare one expression
create table employee
employee-name varchar (40), 2 Comparison operators : These are are given below:
comparison operators
telephone number (10), with another. The
Definition
number Operator
start-date date, Equality
employment number (4), =
length Inequality
dependent varchar (10)); Greater than
name
Less than
create table payment (payment number (6), <
number Greater than or equal to
payment number (10),
amount <=
Less than or equal to
payment-date date); operators.
create table account number (12) primary key, Fig. 2.17.2. Comparison produce asingle
(account logical operator is used to
number Logical operators : A conditions.
3. the twoseparate
create table
balance number (10)); result from combining
Definition
saving-account
create table (interest-rate number (3); Operator
both component
conditions
checking-account Returns true if returns false.
(overdraft number (15)); AND
are true;
otherwise
component condition
amount either
Que 2.17. Returns true if returnsfalse
Deseribe the operators and its types in SQL. OR
is true
otherwise
condition isfalse;
Answer Returns true ifthe
NOT otherwise returns false.
Operatorss and conditions are used to
subtraction or comparison on the dataperform
items inoperations
an SQL
Such as addition,
Different types of SQL statement. Logical operators. separate
operators are : Fig.2.17.3. results of two
1.
Arithmetic combine the
tooperators
: oppeerators
expressions add, subtract,Arithmetic operators are used in SQL 4. Set operators : Set
expression ismultiply,
The result this
of divide and negate data values. queries into a single result.
a
number value.
2-20 A (CSIT-Sem-5) Relational|Data Model & Database Management System 2-21 A(CSTT-Sem-5)
Definition
Language
Operator Que2.18.
What are the relational algebra operations supported
UNION Returns all distinct rows from both queries Write the SQL statement for each operation.
in SQL? W
INTERSECT Returns common rows selected by both queries AKTU2016-17, Marks 7.5|
MINUS Returns alldistinct rows that are in the first
query, but not in second one.
Answer
2-6A. Unit-2
Fig. 2.17.4. Set operators. Basic relational algebra operations : Refer Q. 2.5, Page
5. Operator precedence : algebra operations :
sOL statement for relational
a Precedence defines the order that the DBMS uses when evaluating : Consider the loan relation,
the different operators in the same expression. 1. Select operation
amount)
loan (loan_number, branch_name,
b The DBMS evaluates operators with the highest precedence first 12000, then we
before evaluating the operators of lower precedence. Operators Find all the tuples in which the amount is more than
of equal precedence are evaluated from the left to right. write
Operator Definition Oamount >12000 (loan)
the customer names
Prefix for host variable 2 Project operation :We write the query to list all
and their cities as :
Variable separator (customer)
1eustomer name, customer_city
Surrounds subqueries 3. Set differen ce operation : We
can find all customers of the bank
writing:
Surrounds a literal who have an account but not a loan by
(borrower)
Surrounds a table or column alias or literal text customer _name (depositor) - qustomer name
tables :
Overrides the normal operator precedence 4. Cartesian product : We have the following two
+, Unary operators SOFTWARE PACKAGES
PERSONNEL
*,/ Multiplication and division
Id Name
+
Addition and subtraction J
101 Jai
Character concatenation J
NOT 103 Suraj
Reverses the result of an expression
AND 104 XX
True if both conditions are true
105 BB
OR True if either conditions are true
UNION 106 CC
Returns all data from both queries
software
INTERSECT Returns only rows that match both queries coperation between[personnel x
MINUS
We want to manipulate the x
Returns only row that do not match both packages].
queries
Fig. 2.17.5. Operator
precedence.
2-22A(CSTT Sem-5) Relational Data Model &Language DatabaseManagement System 2-23 A (CSTT-Sem-5)
Pa PName be used like any other relation that is, it can be queried,
4 Aview can deleted from and joined with other relations or views.
101 Jai inserted into,
relation and such views are
101
Views can be based on more than one
Jai 5
known as complex
views.
J table that is derived from other
103
Suraj Aviewin SQL terminology is a single or previously defined
103
J. 6
tables. These other tables can be base tables
Suraj J. views.
104 XX Syntax for creating view:
104
CREATE VIEW view_name
AS SELECT * FROM table_name
105 BB
J, WHERE Category IN (attribute1', 'attribute2"):
105 BB create a view consisting of attributes
For example : Command toandP_ID
Category, Price of the BOOK relation, Pname
106 CC Book_ title, relation can be specifed as
J and State of the PUBLISHER
106 CC
J, CREATE VIEW BOOK 3
5 Rename : Price, BOOKP_ ID,Pname, State
AS SELECT BOOK title,Category,
Cansider the Book relation with attributes Title, FROM BOOK, PUBLISHER
Price. The rename operator is used on Book Author, Year and
relation as follows : WHERE BOOKP _ID = PUBLISHER.P_ID;
Pemhonme, Ama Pyear, Bpricel (Book)
Here both the relation name and the
attribute names are renamed. Que 2.20. Describe indexes in SQL
Billu Computer 8000 ii. Richt outer join : The right outer join operation returns
matching rows from the tables being joined, and also non
Jai IT 5000 matching rows from the right table in the result and places
null values in the attributes that comes from the left table.
Select Employee.Emp Name, Employee_ Salary.Salary from Employee For example :
inner join Employee_Salary on Employee. Emp_Name =
Employee_Salary.Emp_Name; Select Employee.Emp Name, City, Salary from Employee
right outer join
Result : The result of preceding query with selected fields of
Table 2.25.1 and Table 2.25.2. Employee_Salary on Employee.Emp_Name =
Employee_Salary. Emp_Name;
Emp_Name Salary Result : The result of preceding query with selected fields of
Table 2.25.1 and Table 2.25.2.
Hari 10000
Om 7000 Emp_Name City Salary
Pune 10000
Jai 5000 Hari
Mumbai 7000
2 Outer join : Om
5000
An outer join is an extended form of the inner join. Jai Solapur
b null 8000
It returns both matehing and non-matching rows for the tables Billu
that are being joined.
left
Types of outer join are as follows : cross join, naturaljoin,
i
Que 2.26. Write difference between example.
Left outer join : The left outer join returns matching row suitable
from the tables being joined and also
non-matching row outer join and right outer join with AKTU2018-19,Marks 07
from the left table in the result and places
attributes that comes fromn the right table. null values in e
For example :
Select Employee. Emp Name, Salary Answer ofrows
from Employee left outer join Cross join : product of number
whichisthe rows inthesecondtable
on Employee_Salary
Employee.Emp_Name = Employee
1
Cross join set
produces aresult the number of This kind of result is
by
the first table multipliedalong
Result : The result of
2.25.2.
Salary.Emp_Names
Table 2.25.1 and Table preceding query with selected fields of
in
if no where clause is used
with cross
join.
innerjoin.
known as Cartesian product. functionslikean
2. crossjoin, it
If where clause is used with
2-33 A (CSTT-Sem-5)
Database Management System
2-32 A (CSTT-Sem-5) Relational Data Model &Language Result :
Marks
For example : RollNo Name
Beers Select * From Beers 70
Name Manf Cross Join Likes 2
50
Name Manf Drinker Beer 2-29A,
Beer 1 XYZ 3
Q. 2.25. Page
Beer 2 ABC Beer 1 XYZ Kanika Beer 1 and right outer join : Refer
Beer 1 XYZ Aditya Beer 1 Left outer join
Beer 3 ABC Beer 1 XYZ Mahesh Beer 3 Unit-2. operations.
Describe the SQL set
Beer 2 ABC Kanika Beer1 Que 2.27.
Likes Beer 2 ABC Aditya Beer 1
Drinker Beer Beer 2 ABC Mahesh Beer 3 Answer more
operations are: output of two or
Kanika Beer 1 Beer 3 ABC Kanika Beer 1 The SQL set clause merges the
operation : Union and column.
Aditya Beer 2 Beer 3 ABC Aditya Beer 1 1.
Union single set ofrows
Beer 3 ABC Mahesh Beer 3 queries into a
Mahesh| Beer 3 Records
Common onlyin
Natural join : Records
records
1 query one
Natural join joins two tables based on same attribute name and data only in in both
types. query one queries
2 The resulting table will cont ain all the
keep only one copy of each attributes of both the table but clause.
3 common column.
In natural join, if there is no Outputofunion query two + A
Fig. 2.27.1. records only in
rows based on the common condition specifies then it returns the query one + queries.
column. only in common in both produced
For example : Output = Record only rows
Student (Roll Consider the
No, Name) following two relations : ofrecords which is
single set operation:The intersect
clauseoutputs operation returns
intersect
Marks (Roll _No, Marks) Intersect intersected i.e., the queries.
These two relations 2 queries ofboth
are shown in Table
2.26.1 and 2.26.2. by both the from the output
Table 2.26.1. The Student common records
relation. Common
Student records
Roll No in both
1 Name queries
A
2
B intersect clause queries.
Output of common in both rows
Fig.2.27.2.
3
outputs
C records which are Minus
Table 2.26.2. The Marks single set of alsocalledas
relation. Output = A operation: Theexcept second table.
Marks 3. Theexcept first table
but not in
Roll No that are in
Marks
2 70 Records
only in
3 50 query one
4 85
(Minus)clause.
Consider the query: Outputofexcept
Select * from Student natural join Marks ; Fig.2.27.3.
2-34 A (CSTT-Sem-5) Relational Data Model & Language Database Management System 2-35 A (CSTT-Sem-5)
InSQL:
Book.1Titlefrom Book inner join Issue
ON Book.ISBN =Issue.ISBN
author of all books Select
ii. List the title and which are
student name started
iv. List the title of all
with a'.
books issued on or before
issued by a asR =20/09/2012:
where R.date>algebra:
V. List the name of student w will read
who the 20/book
09/2012,of iv, In
relational
(GAuthor ="Sanjeev" and Student.
Roll No = QRoll No (Student TRall No, Author
named 'Sanjeev'.
AKTU2017-18, Marksauth10or IName
Ofssue.ISBN= Book.ISBN
Po (Book
Issue)
In SQL:
Answer
from Student innerjoin
Select Student.Name Book ON
i In relational algebra : Book.Author from Issue inner join
(Select Issue.Roll No, as Q)
TRall No, Nane (OBraneh ="0SE (Student) Issue.ISBN = Book.ISBN
= Q.Roll No
In SQL: ON Student.Roll No
"Sanjeev";
Select Rol No, Name from Students where Q.Author =
RA, B, C), SD, E, F).
where Branch ="CSE"; Que 2.32. Suppose there
are two relations
i In relational algebra : the following RAs :
Write TRCand SQL for
TNeme Opublisher ="BPB and Student Roll
No= P.Roll No (Student 4
i. I(R) Marks 07
Puhlisber 0lssue. ISBN =Book.ISBN Pp (Book Da Issue)) (TRoll No, ii. OB=45 (R) AKTU 2018-19,
In SQL: ii. I, plGc =p(R xS))
Select Student.name from
Student inner
(Select Book.Publisher, Issue.Roll No join Answer
TtlerelOdate
ational>= algebra : name, employeeswho works the same city and
Manages((person
names of allemployees wholive
in
Findsthe
2/09/o19 (Book ba Issue)) ii.
name of all their
Finds the
same street
managers.
as do
On the
2-40 A(CSTT-Sem-5) Relational1 Data Model1&
ii. Find the name street address and
employees who work for ABC bank
cities of Languofageall
residence
and earn more Database Managernent System 2-41 A (CSTT-Sem-5)
per annum.
iv. Find the name of all employee who earn more
thhan 7,000 where company_name-ABC Bank'
W.company_name='AW.BCWorks
person_name 7 To
EXEC, SQL statement as :
iv. Select person Bank' and W.salary> 7000 EXECSQL <embedded SQL
statement> END.EXEC
_name from language can be used within
embedded SQL
where salary > all 8 Variable of the host preceded by a colon (:)to distinguish them
(select sal aryfrom Works statements, but they must be
from SQL variables.
where company_nane=XYZ)
select Dynamie SQL: construct and
where person_name
from Works component of SQL allows programs to
sal 1. The dynamie SQL
ary>(select
where company_nameXYZ) max( salary) from
Works
submit SQL queries at run time. strings at run
programs can create SQL queries as or have them
V 2. Using dynamic SQL executed immediately
Update Works time and can either have
them
set salary=salary* 1.07 prepared for subsequent use. subsequent uses of
where company 3. Preparing a dynamie
SQL statement compiles it, and
version.
vi. name'ABC Bank
Delete from Works the prepared statement use
standards for
the compiled
embedding dynamic SQL calls in
a host
4 SQL defines following example,
language, such as C, as in the
3 2. 5 4 1.
disadvantages.
2 Answer
2 1
Disadvantages Advantages1 3 Que (CSTT-Sem-5)
2-42 A
Following procedures. be
reduce
workThey connection,theThey on statements
They A PLSQLis the char where char
MySQL Stored
administrator
procedures procedureThey which All procedure stored A 2.35. EXEC EXEC
sent
lengthy the Java, power account[
may inadd resultincreases can SQL SQL sqlprog
account_number
does procedures other again statements PHP Deseribe
to of beprocedure in of a
which execute prepare
questions
QUESTIONS
IMPORTANT
be VERY are statements is
the thenprocedures invoked canblock-structured
SQL 10]
of code and being in etc. =
RSITY
ON. asked not should languages
feasible procedures performance
the processing = "update
provide reusability, again traffic becan with
"A-101";
can of thought
through proceduresdynprog dynprog
in decide compiled called a PL/SQLisbe
are for cause viabetween
are procedural =
your such in block stored account
?";
the a the
very particular an in as already frequentlyPL/SQL: speed triggers, of language using from
ONALS similar
a application. version
improvement are as in
functionality upperPL/SQL:
lot C/C++ the nothing in
important. and
passed a the set
of fed
database function statements. PLSQL account; :sqlprog; : Relational
of decreases other database that balance
memory
application.bound and to into
how the in to
but enables
Java. an procedures, or a
of as procedure
the and
of Oracle with =
These
as functions database application aseries Data
debugging usage.
to the the the catalogue.
method. balance
well developers its
how engine
application,application. traffic. of Model
uestions is
advantages
as many The and ordeclarative *
and
delivered. 1.05
the in applications
all &
database methods need a to Language
stored stored at combine
since single
not If once SQL and
a
Management
Database
System
Ans.Q.11. Ans Q.Ans Q.9. Ans. Q.8. Ans. Q.7. Ans.
Define
join.
Q.6. Ans. Q.5. Ans. Q.4. Ans. Q.3. Ans. Q. Ans. Q.
10. iv. iii. constraint
i . Domain iii. i.
iv.Integrity 1.
i. constraint i. 2.
the
ReferWhat RefersQL?What ReferExplain Explain Refer What Refer
Refer example. Refer calculus.
Explain ReferExplain ReferWhat ReferReferReferRefer
Referential Refer
EntityExplain Explain
difference
Q.are
Q. are Q. Q. Q. is Q. Q. Q. Q.are Q. Q.Q. Q. Q.
Write
2.14. 2.18. 2.34.
2.23. howembedded 2.29.trigger 2.25. aggregate2.22. 2.9. tuple 2.7. 2.4(ii). the
2.4iü).2.4(i). 2.3. integrity constraints 2.2.
the the the
different th e Explain integrityfollowing
between the
relational
SQL ? relationaladditional
GROUP Explain constraint
SQL function
statement different and
types WHERE and constraint constraints
algebra BY calculusoperations its
different in
of clause dynamic types types.
and SQL.
SQL for
operation and :
commands each HAVING works SQL types of in
join relational 243 A
operation. domain
in in with
of
supported clause?SQL. detail. trigger (CSTT-Sem-5)
? example. relational algebra
What
with
in is ?