You are on page 1of 22

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

Part-9: Cursors, Triggers, 2-33A to 2-42A


Procedures in SQLPL SQL

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

The generalized syntax of this form is : Cbranch-name


assets

CREATE TABLE relation _name 1 branch

(field1, field2, ..fieldn)


AS SELECT ield1, field2, ..,.fieldn Aoan-branch
FROM relation_name2: paytent-date

Structure of relatians are changed using ALTER verb. customer-name

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

(new fieldl datatype (size), Customer

new field2 datatype


new fieldn datatype(size), ...y
access-date
acount-numbe balance

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

feld2 new datadata type (size), saving-account checking-acoount


emplovee-name
type (size), employee-id
Ctelephone-number

fieldn new data type ; dependent-nane


interest-rate
Overdraft-amount

Pue 2.16. Draw an ER (size)) employment start date


enterprise.
diagram Hospital or Bank
ae specialization, Aggregation, (
of
with showing
length
Fig. 2.16.1. ER diagram
for a banking

Lo relational schem as and SQL DDI.


GeneraliAKTU
zation.2017-18.
Also convert it in

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

PART-6 Answer engine can


tables that the database search
Tables. Viees and Indexes, Queries and Sub 1 Indexes are special lookup
Queries. use to speed up data retrieval.
and WHERE clauses, but it
2 speed up SELECT queries
An index helps toinput, and the INSERT statements.
with the UPDATE
slows down data data.
dropped with no effect on the quickly.
Questions-Answers 3. Indexes can be created or the database more
retrieve data from
4. Indexes are used to speed up searches
Long Answer Type and Medium indexes; they arejust used to
Answer Type Questions 5. The users cannot see the
queries.
Que 2.19. Give the brief 6 Syntax:
explanation of view. CREATE INDEX index
ON TABLE column; TABLE isthe name
Answer that index and
the index is the name given toereated and column is the name of
where
A view isa virtual relation, which that index is
whose contents are derived from already of the table on applied.
which it is of the
existing relations and it does not exist in physical form. that column for maintenance of the integrity
2 The contents of view are determined by indexes are used for the fast performance; it does not
Unique as for the
any relation and it does not form the partexecuting a query based on 7. the table as well
data present invalues table.
of database sehema.
multiple to enter into the
3 Each time a view is referred to, its contents are allow unique index is :
relations on which it is based.
derived from the ereating
Syntax for
INDEX index_name
CREATE UNIQUE
9-24A(CSITSem-5) Relational Data Model & Language 2-25 A (CSTT-Sem-5)
Database Management System
ON TABLE column; total narks of the student and
To remove an index from the data dictionary by using the DROP INDEY So, consider another table 'Marks' containing
apply query considering both tables.
8
command
DROP INDEX index name; sQL code with sub-query :
SELECT a.StudentID, a.Name, b.Total_marks
Que 2.21. Explain sub-query with example. FROM studenta, marks b
ANDb.Total marks >
WHERE a.StudentID = b.StudentID
Answer (SELECT Total marks
1 Asub-query is a SQL query nested inside a larger query. FROM marks
2 Sub-queries must be enclosed within parenthesis. WHERE StudentID = VO02):
The sub-query can be used with the SELECT, INSERT, UPDATE, or Query result :
DELETE statement along with the operators like =, >, <, >=, <=, IN, Total marks
ANY, ALL, BETWEEN. StudentID Name
95
4 Asub-query is usually added within the WHERE clause of another SQL VO01 Abha
SELECT statement Amit 81
VO04
5. A sub-query is also called an inner query while the statement containing
a sub-query is also called an outer query.
6 The inner query executes first before its parent query so that the result
of an inner query can be passed to the outer query. PART-7

Syntax of SQL sub-query :A sub-query with the IN operator, Delete Operations.


Aggregate Functions, Insert, Update and
SELECT column_names
FROM table_namel Questions-Answers
WHERE column name IN (SELECT column name
Answer Type Questions
PROM table_name2 Long Answer Type and Medium
WHERE condition);
Example: in SQL. Explain any one
We have the Que 2.22. Write full relation operation
following two tables 'student' and 'marks' with
StudentID'. common field of them.
OR
Student Explain aggregate function in
sQL.
StudentID Name Marks
VO01 Abha
StudentID Total marks Answer
relation operations like :
VO02
VO01 95 In SQL, there are many full
Albhay Eliminating duplicates
VO03 Anand
VO02 80
Duplicating in union, intersection and
difference
i.
V004 Arnit
VO03 74
ii. Grouping
Now considering table VO04 81 iv. Aggregate function
students who get more marks Student',
we want to
write a query to identify all Aggregate funetion :
but we do not know the marks than
as
the
of V002 student whose that take a collection of clues
Aggregate functions are functions
StudentIDVO02',is 1
input and return a single
value.
2-27A (CSTT-Sem-5)
Relational Data Modell &
2-26A(CSTT-Sem-5) Language Database Management System

built-in aggregate functions : Count : count


e
| All ]expr)
2. SQLoffers five Syntax : count ([ Distinct
number of rows where expr is
not null
Average : avg Purpose : Returns the
|All ] n)
Syntax: avg ( | Distinct Example: "No. of Books"
as
n, 1gnoring null values SQL> select count(title)
Purpose: Returns average value of from book;
query:
Example: Let us consider aSQL from book:
Output :
"Average Price" No. of Books
select avgunit price) as
5
Output : What
clause in SQL works.
Average Price
Explain how the GROUP BY
Que 2.23. HAVING clause ?
359.8 WHERE and
difference between
is the
b. Minimum : min

Syntax : min ( [ Distinct | All ] expr) expression


Answer
(like SUM)
Returns minimum value of GROUPBY: aggregate functions
Purpose: added to SQL because time they are called,
GROUPBY was every
Example : 1 aggregate of all column values possible to find the sum
return the it is not
"Minimum Price" GROUP BY function
SQL> select min(unit_price) as and without the group ofcolumn values.
individual
from book; for each BYfunction is : GROUP BYcolumn
syntax for the GROUP
Output : 2 The SUM(column) FROM table
Minimum Price SELECTcolumns,
250 Example :
:
This "Sales" Table Amount
Maximum :max
Company
Syntax : Lmax ([ Distinct | All] expr) 5500

Purpose :Returns maximum value of expression TCS


4500
Example : IBM
7100
SQL> select max(unit price) as "Maximum Price" TCS
from book;
Output : Sales
Maximum Price
And this SQL: SUM(Amount)FROM
450
SELECTCompany,
GROUP BY Company
d. Sum: sumn result :
Syntax : sum ([ Distinct | All ]n) Return following Amount
Purpose : Returns sum of values of n Company 12600
Example : TCS 4500
SQL> select sum(unit price) as "Total" IBM
from book;
Output :
Total
1799
Database Management System
2-29 A(CSTT-Sem-5)
Belational Data Model &
Language Syntax: Update table_name set column name = new_value
condition:
Dfereme HAVTNG PART-8
WHERE Joins, Unions, Intersections, Minus
used fr
HAVING clauseiis used to filter
WHSRE case is 0n
upsin SL
t appies Questions-Answers
Sheing s nd
beforeHAVING clause is used after Long Answer Type and Medium Answer Type Questions
WHERE ciase is sed GROUPBY clause
GROLP BY ciause
can cnly be
be used HAVINGclausequery ie., ifusedme
WHERE cise ca NSERT.ith SBLBCT Discuss join and types with suitable example.
SSLECT. INSERT Quo 2.25.
ciause.want te perform
POATE nd DELETE UPDATE and DELETE clause it AKTU 2017-18, Marks 10
wil returns an error. types ofjoin.
Define join.Explain different
aggregate function AKTU 2019-20, Marks 07
catnnt se
funnshe nggregate We can use clause.
WHEREciaSeHAVING
We
Answer based ona
et naHAVTNGcause combine rows from two or more tables,
Aioin clause is used to them.
modifed in SQL related column between
database is operations are :
Gue 234 Epain bowa Various types of join
Epiain diatahase modiicatim L Inner join : matching rows from the tables that are
Inner join returns the
beingjoined.
Answer
contents of the database are : following two relations :
Dfm agetsthat mdiythe Forexample : Consider
L Diete Employee (Emp_Name, City)
delete all or specific rowsfrom Department,Salary)
The ietie sgeratin is sed te Employee_Salary(Emp_Name, 2.25.1 and 2.25.2.
database
attributes tworelations are shown in Table
Ditemmand do not deiete values of particular These Employeerelation.
Table. 2.25.1. The
Aelete emmand ogerates only on relation or table.
Syutax Employee
deliete Srsm tabie ame City
EmpName
wen sssditis Pune
2 nsets Hari Mumbai
itet mand sed to insert data into a relation/table. Om Nashik
ofthe
The atriteaues or itserted tuples must be membersrelation Suraj
atrit edomai geied in the same order inthe Solapur
e Jai
bystaxiet ints ale saevaus(attribtel attribute,
attribte2
2 Eylaes:yata dis adto uyate &value in a tuple.
Database Management System
2-30 A (CSTT-Sem-5) Relational Data Model &Language 2-31 A(CSTT-Sem-5)
Table. 2.25.2. The Employee_Salary relation. Emp_Name
Hari
Salary
Employee Salary 10000
Om
Emp Name Department Salary 7000
10000 Jai 5000
Hari Computer
Om T 7000 Suraj null

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)

Output = Records only in query one. [AS datatype )


[START WITH value ]
PART-9 |INCREMENT BY value ]
Cursors, Triggers, Procedures in sQLIPL SQL. IMINVALUE value NO MINVALUE]
IMAXVALUE value | NO MAXVALUE)
[CYCLE | NO CYCLE ]
Questions-Answers [CACHE value | NO CACHE ):
Procedures:
Long Answer Type and Medium Answer Type Questions a specification.
1 Aprocedure is a sub-program that performs
2 A procedure has two parts :
Specification :The procedure specification begins with the keyword
Que 2.28. Explain cursors, sequences and procedures usedin SQL. or parameter list.
procedure and ends with the procedure name
begins with the keyword is and ends
Answer ii. Body : The procedure body
Cursors : with the keyword end.
1 Acursor is a temporary work area created in
the systemn memory when Syntax : To create a procedure, list] is
a SQL statement is executed. <proc name> [parameter
create or replace procedure
2 A cursor contains information on a select statement and the rows of <local declaration >
data accessed by it.
3. A cursor can hold more begin
than one row, but can process only one row at a (executable statements)
time.
lexception] (exception handlers)
4 The set of rows the cursor holds is
called the active set.
5. There are two types of cursors : end;
Implicit cursors : Syntax:To execute a procedure,
(parameters);
These are created by default when exec < proce_name >
INSERT, and
DML
UPDATE, DELETE statementsstatements ike, Explain different trigger with example.
They are also created when a are executed. Que 2.29. What is trigger ?
just one row is executed. SELECT statement that returns AKTU 2017-18, Marks 10
b. Explicit cursors : OR
3.5
They nust be created when AKTU 2019 20, Marks
we are
statement that returns more than executing a
SELECT Describe the following terms trigger.
one row.
When we fetcha row the
TOW current row position moves to Answer
next
Sequences : Triggers : executed automatically
(code segment) that is
Sequences are frequently used in 1 Atrigger is a procedure occur in a table/view of a database.
require each row in atable tocontainna databases
unique because When some specific
events
maintaining integrity in a database.
an easy way to generate them. value and many applications mainly used for auditing changes
Syntax :
sequences provide 2 Triggers are
TTiggers are also used for enforcing business rules,
replicating data.
CREATE SEQUENCE (schema. in the database and
Jsequence_name Following are different types
oftriggers :
Database Managernent Systern
Relational Data Model. & 2-37 A (CS/IT-Sem-5)
2-36 A (CSTT-Sem-5) Language CLR triggers are useful if heavy
computation is required in the
Language (DML) triggers :
C
trigger or a reference to object outside SQL is required.
1 Data Manipulation executed when aDML operation like INSERT,
triggers are View. Que 2.30. Consider the following
DML fired on a Table or relational database employee
UPDATE OR DELETE is (employee_name, street, city
DML triggers are of two
types:
company_nanme, salary) company
works (employee_name,
AFTER triggers : (employee_name, manager_name). (company_name, city) manage
the DML statemont
1. AFTERtriggers are executed after to the database Give an expression in SQL to express each of the following queries :
completes but before it is committed Cindthe names and cities of residence of all emplovees who
its actions and
2 AFTERtriggers if required can rollback
it.
work for XYZ bank.
which invoked
source DML statement ii. Find the names, street address, and cities of residence of all
employee who works for XYZ Bank and earn more than
ii. INSTEAD OF triggers : Rs. 10,000 per annum.
which get
1 INSTEAD OF triggers are the triggers DML (i.e.. 44: Rind the names of all employees in this database who live in the
automatically in place of triggering
executed action. same city as the company for which they work.
INSERT, UPDATE and DELETE)
record and we have a AKTU2016-17, Marks 10
2 It means if we are inserting a INSERT
INSTEAD OF trigger for INSERT then instead of gets
whatever action is defined in the trigger that Answer
executed. Select E.employee_name, city
2 DataDefinition Language (DDL) triggers : from employee E, works W
statements like CREATE,
DDL triggers are executed when a DDL where W. company_name = XYZ Bank' and
ALTER, DROP, GRANT, DENY, REVOKE, and UPDATE W.employee_name = E.employee_name
STATISTICS statements are executed.
Select * from employee
DDL triggers can be DATABASE scoped or SERVER scoped. The
DDL triggers with server level scope gets fired in response to a where employee_nane in
DDL statement with server scope like CREATE DATABASE, Works
CREATELOGIN, GRANT _SERVER, ALTER DATABASE, ALTER select employee_name rom
LOGIN etc. where company_name-XYZ Bank and salary>10000
address, city
Where as DATABASE scoped DDL triggers fire in response to select E. employee_name, street
DDL statement with DATABASE SCOPE like CREATE TABLE,
CREATE PROCEDURE, CREATE FUNCTION, ALTER TABLE, from Employee as E, Works as W
employee_name=W.person_name and
ALTERPROCEDURE, ALTER FUNCTION etc. where E. W.salary>10000
LOGON triggers : W.company_name = XYZ Bank' and
LOGON triggers get executed automatically in response to a ii. Select E. employee _name
LOGON event. Works as W, Company as C
They get executed only atter the successful authentication but from Emnployee as E,
name=W.person_name and E.city=C.city
b
before the user session is established. Where E. employee
eauthentication fails the LAOGON triggers will name=C.company_name
not be fred. and W.company primary key is
CLR triggers : relation. The
4
Consider the following (ISBN, Title,
CLR triggers are based on the Sql CLR Que 2.31. Name, Branch), Book Write the
a.
No, issue).
b We can write DML and
DDL
,triggers by using the supported .NET Rollno, ISBN, Student(Roll
(Roll No,
ISBN, date of
following:
CLR languages like C#, VB.NET ete. Author, Publisher) Issue
andSQL of
the Students.
Branch
query in relational algebra Name of All CSE
and.
i. List the Roll Number
2-38A(CSTT-Sem-5) Relational Data Model & Managementt System 2-39 A(CSTT Sem-5)

ii Find the name of


publication BPB.
students who have
issued a Lbookanguag ot Database

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

Issue.ISBN =Book.ISBN as P) from Issue inner join Book on i. II (R):


ON Student.Roll No=P. TRC: (s.A, s.B |R(s)
Roll No
where P.Publisher ="BPB"; SQL: Select A, B from R;
i In
relational algebra :
Ts Tie, SAuthor Og
i. GR= 45 (R) :
TRC : (s |R(s) As.B = 45)
Ps (Book ba Name like('a 67) (7TName, Book. Author, Book.Title OBook ISBN =TISBN = 45 ;
SQL:Select * from Rwhere B
Issue); (Tyame ISBN Ogtudent.Roll
No = (Student ba
Issue.Roll No PT ii. I pGc= p(R xS)) : =plA) AtF] = qlF] AplC] =qlD))
In SQL: SD;
TRC : (t|Bper Bqes(t[A| innerjoin S ON R.C=
Select S.title, SQL:Select A, Ffrom R DATABASE. Give an
(Select T.Name,S.Author from following
relational
Que 2.33.Consider the: followingqueries.
Underline records
StudentStudent.Name,.RollIssue.Book.
ON
No=ISBN
Authorfrom, Bookk.Title from Book inner
Student inner Issue
r join
jjoin(Select
expression in SQL
for egch
street,city) salary)
ON
Book.ISBN =TISBNIssue.asRS)oll No as T)
are primary key name,
Company name,
Employee(person
where
iv. In S.Name like 'a%'; Works(person name,
name, city)
name) bank
Company(Company manager for theABC

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'

employee of XYZ. thhan every vi. Select E.person_name


from Employee as E, Works as W, Company as C
V. Give all employees of corporation ABC a 7%
vi. Delete all tuples in the works relation for salary raise. where E.person_name=W.person_name and E.city=C.city
vii. Find the name of all employees in this employeeswhoof ABC.
the same city as the company for whichDATABASE
and W.company_name=C.company_name
they work. live in
SQL in detail.
Que 2.34. Explain embedded SQL and dynamic
AKTU 2019-20, Marks 07
AKTU2016-17, Marks 10
Answer
Select person_name from Works Answer
Where company_name=ABC Bank Embedded SQL:
variety of
Select El.person_name defines embeddings of SQL in a COBOL.
1. The SQL standard Pascal, PLI, Fortran, C and
From Employee as El, Employee as E2, programming languages such as
as a host
Where El.person_name=M.person_nameManages queries are embedded is referred to
as M
2. Alanguage in which SQLstructures permitted in the host language
and E2.person_name=M.manager_name language and the SQL
constitute embedded SQL.
SQL
and language can use the embedded
ü El.street=E2.street and El.city=E2.city
Select* from 3. Programs written in the host stored in a database.
employee syntax to access and update data database
where person_name in processing is performed by the
4. In embedded SQL, all query
(select person_name from Works system. one tuple
made available to the program
where company_name= 'ABC 5 The result of the query is then
Bank' and
select E.person_name, street, salary>7000 at a time.
completely present at compile time
city from Employee as E, 6 Embedded SQL statements must be preprocessor.
SQL
Works as W and compiled by the embedded the
where requests to the preprocessor, we use
and E.person_name
= identify embedded SQL

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 ?

You might also like