Vous êtes sur la page 1sur 85

DATABASE MANAGEMENT SYSTEMS

Relational model (ER-model, relational algebra, tuple calculus), Database design (integrity
constraints, normal Iorms), Query languages (SOL), File structures (sequential Iiles,
indexing, B trees), Transactions and concurrency control;





CONTENTS

TOPICS PAGE NO:
1) ER DIAGRAMS 01-14
2)FD NORM 15-44
3)SQL 45-77
4)R.A.&R.C 78-83
5)TRANSACTION CONCURRENCY 84-99

















Authorised By
SANTOSH BHARADWA1 REDDY
Email: helpmatlabcodes.com
Engineeringpapers.blogspot.com
More Papers and Presentations available on above site



































CSE & IT DBMS
TOPIC-1 : ER-DIAGRAMS

Points to emphasize
O ow to use Entity-Relationship)ER) modeling in database design.
O The basic concepts associated with the Entity-Relationship (ER) model.
O A diagrammatic technique Ior displaying an ER model Using an uniIied Model Language (UML).
O ow to identiIy and resolve problems with ER models called connection traps.
O ow to build an ER model Irom a requirements speciIication.

What To Model?

Static InIormation
Data Entities
AssociationsRelationships among entities
Dynamic InIormation
Process Operations/transactions
Integrity constraints Business rules/regulations and
Data meanings

What is data model?
A collection oI tools Ior describing
Data
Data relationships
Data semantics
Data constraints

System model tools:
Data Ilow diagrams (DFD)
ierarchical input process and output(IPO)
State transition diagrams (STD)
Entity relationship (ER) diagrams

Entity-Relationship model (ER Model)

A data model in which inIormation stored in the database is viewed as sets oI entities and sets oI
relationships among entities and it is diagram-based representation oI domain knowledge, data properties etc.
but it is more intuitive and less mechanical

Components of E R model

a. Entity b. Relationship c. Attribute.


(cont......)























Entity
Something that exists and can be distinguished Irom other entities.
Examples: Student entities with unique roll numbers
Account entities with unique account numbers
Entity set
A set oI entities oI the same type.

O Example: All the student entities in a college
O Entity sets need not be disjoint. Example: a person entity could be in
both the customer and employee sets

Types of entities
Entities with physical existence
Example: student, customer, book etc

Entities with conceptual existence
Example: sale, university, course etc

Relationship
An association among two or more entities

Example: the relationship between a Faculty and Student i.e Iaculty take
Course oI student

Relationship set

A set oI relationships oI the same type

Attribute
A character oI an entity
O Example: A student entity might have attribute such as: Roll number,
name, age, address etc
O As all entities in an entity set have the same attributes, entity sets also
have attributes - oI the contained entities. The value oI the attributes
can be diIIerent Ior each entity in the set.

Domain of Attribute

A set oI possible values Ior an attribute (the type oI the attribute).
Examples: The domain oI student name might be strings oI some Iixed length.
The domain oI roll number might be 10 digit positive integers or alphanumeric



(contd....)















Relationship degrees

The number oI entity types associated with that relationship.


Unary Binary



Types of relationships

Connectivity

One to One


one to many

employee
Supervis
ee
Project
Employee
Work
Supplier
Part
Suppl
yyyy
Department
Employee
Work
Department
Work
Employee
Work
Department
Work

Employee


many - to - many


Multiplicity
Multiplicity constrains the way that entities are related it is a representation oI the policies
or (business rules) established by the user or enterprise. Multiplicity actually consists oI two separate
constraints.

Cardinality - which describes the maximum number oI possible relationship occurrences Ior
an entity participating in a given relationship type i.e ow many relationship instances is an entity
permitted to be linked to

Participation - which determines whether all or only some entity occurrences participate in
a relationship i.e ow is an entity linked the relationship


Total participation (indicated by double line): every entity in the entity set
participates in at least one
relationship in the relationship set


(contd....)


























Project Employee
Task-assignment
Start-date

Partial Participation: Some entities may not participate in any relationship in the relationship set.

Note: Cardinality limits can also express participation constraints


Participation Cardinality


Types of attributes
1. Simple and composite
2. Single valued and multi-valued
3. Stored and derived attributes.

Simple: Position salary attribute oI Iaculty
Composite: Address attribute composed oI street, city, and postcode attributes


Composite name address
Attributes

First name middle name last name street city state postal-code

Componcit
Attributes street-number street-name apartment-
number



Single-Valued: Department No Attribute oI Department
Multi-valued: TelephoneNo attribute oI Iaculty
Stored: Date oI birth attribute oI student
Derived: Agge attribute is derived Irom date oI birth




Weak and a strong entity set


A strong entity set has a primary hey. All tuples in the set are distinguished by that key. A weak
entity set han no primary key unless attributes oI strong entity set on which it depends are induced.
Tuples in a weak entity set are partitioned according to their relationship with tuples in a strong
entity set. Tuples within each parttion are distinguishable by a discriminator, which is a set oI
attributes.





(contd...)



E1 E2
R









An entity set is that does not have a primary key is reIerred to as a weak entity set. The existence oI
a weak entity set depends on the existence oI identifying entity set . weak entity must relate to the
identiIying entity set via a total, one-to many relationship set Irom the identiIying to the weak entity
set. IdentiIying relationship depicted using a double diamond.
The discriminator (or partial key) oI a weak entity set is the set oI attributes that distinguishes
among all the entities oI a weak entity set. The primary key oI a weak entity set is Iormed by the
primary key oI the strong entity set on which the weak entity set is existence dependent, plus the
weak entity set`s discriminator.


We depict a weak entity set by double rectangles.
We underline the discriminator oI a weak entity set with a dashed line.
Payment-number-discriminator oI the payment entity set
Primary key Ior payment (loan-number, payment-number)

Note: the primary key oI the strong entity set is not explicitly stored with the weak entity set, since it
is implicit in the identiIying relationship.

II loan-number were explicitly stored, payment could be made a strong entity, but then the
relationship between payment and loan would be duplicated by an implicit relationship deIined by
the attribute loan-number common to payment and loan.

Reasons to have weak entities

- we want to avoid the data duplication and consequentpossible inconsistencies caused by
duplicating the key oI the strong entity
- Weak entities reIlect the logical structure oI an entity being dependent on another entity
- Weak entities can be deleted automatically when their strong entity is deleted.
- Weak entities can be stored physically with their strong entities.
Examples
In a university, a course is a strong entity and a course-offering can be modeled as a weak entity. The
discriminator oI course-offering would be semester (including year) and section number (iI there is
more than one section). II we would model course-number as an attribute. Then the relationship with
course would be implicit in the course-number attribute



(contd...)


Loan-number amount
Payment-amount
Payment-date
Payment-number

payment

loan
Loan-payment








Existence Dependencies
II the existence oI entity x depends on the existence oI entity y, then x is said to be existence
dependent on y. y is a dominant entity. X is a subordinate entity. II y entity is deleted, then all its
associated x entities must be deleted.

ER diagram symbols









Keys

A super key oI an entity set is a set oI one or more attributes whose values uniquely determine each
entity and a key is a minimal super key no subset key: no subset oI columns can determine entity.


A candidate key oI an entity set is a minimal super key
Student roll no is candidate key oI student table, Book Accno is candidate key oI Book
table. Although several candidate keys may exist, one oI the candidate keys is selected to be the


Primary key

The combination oI primary keys oI the participating entity sets Iorms a super key oI a relationship
Set. (customer-id,account number) is the super key oI depositor
NOTE: this means a pair oI entity sets can have at most one relationship set in a particular
relationship
Set.
E.g. iI we wish to track all access-dates to each account by each customer,we cannot assume
relationship Ior each access. We can usemultivalued attribute though

Must consider the mapping cardinality oI the relationship when deciding, what are the candidate
keys

Need to consider semantics oI relationship set in selecting the primary key in case oI more than one
Candidate key

(contd...)
Super keys
Candidate keys





Aggregation

Aggregation is an abstraction through which relationships are treated as higher-level entities. Thus
The relationship between entities A and B is treated as iI it were an entity C. Some examples oI this
Are: a.Employees work Ior projects. An employee working Ior a particular project uses various
machinery.
b .ManuIacturers have tie-ups with distributors to distribute products. Each tie-up has speciIied Ior it
the set oI products which are to be distributed.




name
datalink
employee
employee
Works in
name
datalink
employee
employee
Works in

&tility of E-R Model
O It maps well to the relational mode. The constructs used in ER model can easily be
transIormed into relational tables.
O It is simple and easy to understand with a minimum oI training. ThereIore, the model
can be used by the database designer to communicate the design to the end user.
O In addition, the model can be used as a design plan by the database developer to
implement a data model in a speciIic database management soItware.
E-R Design Decisions
The use oI an attribute or entity set to represent an object.
Whether a real-world concept is best expressed by an entity set or relationship set.

(contd....)














Authorised By
SANTOSH BHARADWA1 REDDY
Email: helpmatlabcodes.com
Engineeringpapers.blogspot.com
More Papers and Presentations available on above site






































The use oI a ternary oI a relationship versus a pair oI binary relationships.
The use oI a strong or weak entity set.
The use oI specialization/generalization-contributes to modularity in the design.
The use oI aggregation-can treat the aggregate entity set as a single unit without concern Ior the
details oI its internal structure.

Tools to create E-R Diagrams
Several omputer Assisted Software Engineering (ASE) Tools exist to help create E-R Diagrams
and the resulting physical database elements. Products include:
- IEW
- IEF
- DEFT
- ER-WIN
- Visio

Exercise
1. Create an ER diagram Ior each oI the Iollowing descriptions:

(a) Each company operates Iour departments, and each department belongs to one company.
(b) Each department in part (a) employs one or more employees, and each employee works
Ior one department.
(c) Each oI the employees in part (b) may or may not have one or more dependants, and each
dependant belongs to one employee.
(d) Each employee in part (c) may or may not have an employment history.





(contd.)






























(e) represent all the ER diagrams described in (a),(b),(c),and(d) as a single ER diagram.



2. You are requested to create a conceptual data model oI the data requirements
Ior a company that specializes in IT training. The company has 30 instructors
and can handle up to 100 trainees per training session. The company oIIers
Iive advanced technology courses, each oI which is taught by a teaching team
oI two or more instructors. Each instructor is assigned to maximum oI two
teaching team oI two teaching teams or may be assigned to do research. Each
trainee undertakes one advanced technology course per training session.



(a) IdentiIy the main entity types Ior company.
(b) IdentiIy the main relationship types and speciIy the multiplicity
Ior each relationship. State any assumptions you make about the
data.
(c) Using your answer Ior (a) and (b), draw a single ER diagram to
represent the data requirements Ior the company.






Company
Employment
istory
Dependent
Employee
Department


(contd...)








Authorised By
SANTOSH BHARADWA1 REDDY
Email: helpmatlabcodes.com
Engineeringpapers.blogspot.com
More Papers and Presentations available on above site








Answer:




3. Consider a database used to record the marks that students get in diIIerent
exams oI diIIerent course oIIerings. Construct an E-R diagram that models
exams as entities, and uses a ternary relationship, Ior the above database.
Research Instructor Teaching
Team
Advanced
Course
Training
Session
Trainee

Answer:



4. A university registar`s oIIice maintains data about the Iollowing entities: (a) courses including
number, title, credits, and prerequisites; (b) course oIIerings, including course number, year,
semester, section number, instructor(s), timings and classroom; (c) students including student-id,
name, and program; and (d) instructors including identiIication number, name department, and title.
Further, the enrollment oI students in courses and grades awarded to students in each course they are
enrolled Ior must be appropriately modeled. Construct an
E-R diagram Ior the registar`s oIIice. Document all assumptions that you make about the mapping
constraint.

Convert ER diagram into equivalent relational tables





(contd..)

























Answer: In the answer given here, the main, entity sets are student, course, course oIIering and
instructor. The entity course oIIering is a weak entity dependent on course. The assumptions made
are :


a. A class meets only at one particular place and time. This E-R diagram cannot
model a class meeting at diIIerent places at diIIerent times.
b. There is no guarantee that the database does not have two classes meeting at the
same place and time.


&niversity registrar`s table:

Student (student-id , name, program)
Course (courseno, title, syllabus, cedits)
Course-Offering(courseno, scno, year, semester, time, room)
Instructor (instructor-id, name, dept, title)
Enrols (student-id, courseno, scno, semester, year, grade)
Teaches (course no, scno, semester, year, instructor-id)
Requires (maincourse, prerequisite)



5. Construct an E-R diagram Ior a car-insurance company whose customers own one or more cars
each. Each car has associated with it zero to any number oI recorded accidents. Convert ER-diagram
into equivalent Relational tables.

Answer:



(contd..)

Car insurance Tables:
Person (driver-id, name, address)
Car (license, year, model)
Accident (report-number, date, location)
Participated (driver-id, license, report-number, damage-amount)


6. Consider an E-R diagram Ior a hospital with a set oI patients and a set oI medical doctors.
Associate with each patient a log oI the various tests and examinations conducted. Convert ER
diagram into equivalent relational tables.

Answer:

Hospital tables:
Patients (patient-id, name, insurance, date-admitted, date-checked-out)
Doctors (doctor-id, name, specialization)
Test (testid, testname, date, time, result)
Doctor-patient (patient-id, doctor-id)
Test-log (test-id, patient-id)
Perfomed-by (test-id, doctor-id)


Objective type questions
1. A constraint showing the maximum number oI entities that can occur
on a side oI a relationship is called the
a. Degree b. Maximum Cardinality c. Instance d. None oI the
above.

2. A special type oI weak entity is called a(n)

a. Strong entity b. ID-Dependent entity c. Binary entity d. None oI
the above

3. The number oI entities participating in the relationship is known as
the
a. Maximum Cardinality b. Composite IdentiIiers
c. Degree d. None oI the above

4. A relation ship among entities oI the same class is called a
a. Binary Relationship b. Weak Relationship
c. Recursive relationship d. None oI the above
(contd..)
5. An M:N relationship is decomposed into
a. two 1:1 relationships b. a 1:1 relationship and a 1:M
relationship
c. two 1:N relationships d. None oI the above

6. SELECT * FROM CUSTOMER A, CUSTOMER B WERE
A. customer Number B. customer Number; is an example oI a

a. Many-to-Many relationship b. Non recursive
relationship
c. Recursive relationship d. None oI the
above

7. Descriptive attributes are used to
a. Record inIormation about participating entities
b. Record information about relationships
c. Record inIormation about data
d. Record inIormation about attributes

8. The relationship between the owner entity set and the weak entity
set
a. many to many b. one to many c. many to one d.
one to many
9. Role names or role indicators are necessary Ior
a. many to many relationships b. recursive
relationships
c. aggregation/Generalization relationships d. None of the
above

10.Cardinality ratios are used in
a. unary relationship b. binary relationship
c. Ternary relationship d. None oI the above

11.All 1-N relationships in E-R model is implemented in relational
model as

a. Relation corresponding to 1 side is modiIied to include
Foreign key oI the
relation on the N` side.
b. Relation corresponding to N` side is modified to include
Foreign key to the relation on 1 side.
c. Primary keys are added on both sides.
d. Foreign key are added on both sides.


12.E-R model is used in
a. Logical design b. Conceptual design c. Physical design d.
Both a&b

13.Participation constraints cannot be represented Ior
a. Unary relationships b. Binary relationships
c. Ternary relationships d. None oI the above

14.A minimum cardinality oI Zero speciIies
a. No participation b. Partial participation
c. Total participation d. Zero participation

15.What rule or constraint governing the department and employee
relationship (in general) is expressed as one department can have
a maximum oI 100 employees ?
a. Existence dependency b. Overlap constraint
c. Covering constraint d. Cardinality rule

16.What is not true about weak entity ?
a. They do not have key attributes
b. B. They are the examples oI existence dependency
c. Every existence dependency results in a weak
entity
d. Weak entity will have always discriminator
attributes

17.Derived attribute is a attribute that represents a value that is
derivable Irom
a. Only from a single attribute in an entity
b. It can be derived from two or more attributes in an
entity
c. It can be derived from a different entity
d. None oI the above

18.A Ian trap may exist in ER model. II
a. Two or more one to one relationships Ian out Irom the same
entity
b. Two or more one to many relationships fan out from the
same entity

c. Two or more many to one relationships Ian out Irom the same
entity
d. Two or more many to many relationships Ian out Irom the
same entity

19.A chasm trap may exit in ER model, iI
a. One or more relationships with maximum cardinality oI N
b. One or more relationships with maximum cardinality oI N
c. One or more relationships with maximum cardinality oI N
d. One or more relationships with maximum cardinality of N

20.For which one oI the Iollowing entity needs mandatory
participation in the relationship ?
a. Strong entities that participate in 1:1 relationship
a. Strong entity on N` side relationship in 1:N relationship
b. Weak entity in identifying relationship
c. Strong entity in identiIying relationship
-
















(contd...)
TOPIC-2 F&NCTIONAL DEPENDENCIES & NORMALIZATION

Points to emphasize:

O Various design steps
O The problems associated with redundant data.
O The identiIication oI various types oI update anomalies such as insertion,
deletion, and modiIication anomalies.
O ow to recognize the appropriateness or quality oI the design oI
relations.
O The concept oI Iunctional dependency, the main tool Ior measuring the
appropriateness oI attribute groupings in relations.

O ow Iunctional dependencies can be used to group attributes into
relations that are in a known normal Iorm.
O The purpose oI normalization.
O ow to undertake the process oI normalization.
O ow to identiIy the most commonly used normal Iorm a namely Iirst
(1NF), second (2NF), and third (3NF) normal Iorms, and Boyce-Codd
normal Iorm (BCNF).
O ow to identiIy Iourth (4NF) and IiIth (5NF) normal Iorms.

Database design Steps:


1. Requirement speciIication
Entities, attributes, associations, constraints, security, perIormance,
various types oI retrieval and manipulation requests & their Irequencies.

2. Sernantic modeling
- Structural modeling: Model data entities, their
attributes and association among entities.
- Constraint speciIication : Model security and
integrity constraints
- Operations: SpeciIy MeaningIul operations
associated with entities/ objects and their
associations



(contd.)
3. DBMS speciIic logical design
- Use data model (relational, object oriented
etc) oI a DBMS to speciIy the structural
properties and constraints.
- Determine the structural properties, constrains
and operations which are not captured by the
data model and are to be implemented in
application programs
Requirement SpeciIication
Semantic Modeling
Physical Design(DBMS speciIic) Database implementation
Monitoring and ModiIication
Logical Design (DBMS speciIic)

4. DBMS speciIic physical design
-Determine the access methods, data clustering
and partitioning strategies
- Data distribution and replication in distributed
systems.

A relation has the Iollowing properties:
- as a name that is distinct Irom all other relation names in the relational
schema;
- Each cell contains exactly one atomic (single) value;
- Each attribute has a distinct name;
- The values oI an attribute are all Irom the same domain;
- Each tuple is distinct; there are no duplicate tuples;
- The order oI attributes has no signiIicance;
- The order oI tuples has no signiIicance, theoretically, (owever, in
practice, the order may aIIect the eIIiciency oI accessing tuples)

Attribute Iields or
Characteristics
Relation Name





Record
Occurrence


The problem in
relational model is to
place the proper
attributes into a relation and oI grouping attributes in diIIerent relations. This
problem can be solved by the Iollowing two methods

1. By intuition and semantic relatedness, but problems are.
a. No semantic distinction between the two attributes Ex T(a,b)
b. Duplication oI attribute values c. Semantic ambiguity
c. Storage anomalies
2. Relational normalization using the notion oI Iunctional dependency





(contd..)


Roll No Sname Saddress Age Branch
101 Sree yd 19 CSE
102 Ram Vzg 18 IT
.
..
110 Kavitha yd 19 CSE
Student

Three relational goals Ior relational databases

1. Avoid redundancies and resulting update, insertion, and deletion
anomalies, by decomposing schemes as necessary
2. Ensure that all decompositions are lossless-join.
3. Ensure that all decompositions are dependency preserving.

owever, all three may not be achievable at the same time in all cases, in which
case some compromise is needed. One thing we never compromise, however is
lossless-join, since that involves the destruction oI inIormation. We may have to
accept some redundancy to preserve dependencies, or we may have to give up
dependency preservation in order to eliminate all redundancies.

The types oI update anomalies that may occur on a relation that has
redundant data.
A major aim oI relational database design is to group attributes into relations so as
to minimize inIormation redundancy and thereby reduce the storage space
required by the base relations. Another serious diIIiculty using relations that have
redundant inIormation is the problem oI update anomalies. These can be classiIied
as insertion, deletion, or modiIication anomalies. The process oI Normalization
can reduce all these anomalies.

Update anomalies

Insertion anomalies: An independent piece oI inIormation cannot be recorded
into a relation unless an irrelevant inIormation must be inserted together at the
same time.
Modification anomalies: The update oI a piece oI inIormation must occur at
multiple locations, not required by the reIerential integrity rule.
Deletion anomalies: The deletion oI a piece oI inIormation unintentionally
removes other inIormation.
Table 1
Fno Fname QualiIication DeptName ODName Strength
101 Sree Ph.D IT Sree 90
102 Ram Ph.D IOT Sree 90
103 Rajesh M.Tech CSE Gopal 60
104 Murali M.Tech IT Sree 90
105 Sultan M.Tech ECE Sultan 120
106 Sangeetha M.Tech ECE Sultan 120
107 Kumar M.Tech CSE Gopal 60
108 Rajini M.Tech ECE Sultan 120
109 Priya M.Tech ECE Gopal 120
110 Sunitha B.Tech CSE Gopal 60
? ? ? EIE ? 60


(Contd.)





Purpose oI normalizing data:

When we design a database Ior a relational system, the objective in developing a
logical data model is to create an accurate representation oI the data, its
relationships and constraints. To achieve this objective, we must identiIy a suitable
set oI relations. A technique that we can use to help identiIy such relations is called
normalization. Normalization is a technique Ioe producing a set oI relations with
desirable properties, given the data requirements oI an enterprise. Normalization
supports database designers by presenting a series oI tests which can be applied to
individual relations so that a relational schema can be normalized to a speciIic Iorm
to prevent the possible occurrence update anomalies. Normalization can be
achieved with the help oI keys and functional dependencies.
Keys
1. A key is a group oI one or more attributes that uniquely identiIies a row.
2. A key Iunctionally determines the other attribute in a row, thus it is always a
determinant.
3. Since relations cannot have duplicate rows, there is always one key (the
composite oI all attribute in a relation).
primary key
Super-Key: A et oI one or more attribute, which, when taken collectively,
allows us to identiIy uniquely an entity or table.

Candidate key: Any subset oI the attributes oI a super key that I also a super
key, but not reducible.

Primary key: A column or a set oI columns used to uniquely identiIy a
particular row. The relationship between the primary key and the ret oI the data
I one-to-one. Every table must have a primary key. Arbitrarily elected Irom the
et oI candidate keys, as needed Ior indexing

Foreign key: An attribute or set oI attributes within one relation that matches
the candidate key oI some (possibly the same) relation.

The concept oI Iunctional dependency.

Functional dependency describes the relationship between attributes in a
relation. For example, iI A and B are attributes oI relation R, B I Iunctionally
dependent in A( denoted A B), iI each value oI A in R is associated with
exactly one value oI B in R.

Super keys
Candidate keys




(contd...)
Functional dependency is a property oI the meaning or semantics oI the
attributes in a relation. The semantics indicate how the attributes relate to one
another and speciIy the Iunctional dependencies between attributes. When a
Iunctional dependency is present, the dependency is speciIied as a constraint
between the attribute.

Given a table T with at least two attributes A and B, we say that A -~ B (A
Iunctionally determines B, or B is Iunctionally dependent on A) iII it is the
intent oI the designer that Ior any set oI rows that might exist in the table, two
rows r1 and r2 in T, iI r1(A) r2(A) then r1(B) r2(B). consider your intution
iI two rows with same empid diIIerent empphone, assume data corrupted,
but iI same empphone and diIIerent empid say 'Oh, so employees can share a
phone. Then we say empphone -/-~empid

Ok have when one attribute A Iunctionally determines another B. Now sets oI
attributes: X A1 A2 . Ak, and Y B1 B2 . Bm. Say X -~ Y iII it is the
intention oI the designer that two rows cannot simultaneously agree on X and
disagree on Y. But note that Ior a set X, agrees iI and only iI agrees on ALL
column value, disagrees iI on ANY column value.

Properties oI FDs
1. X is called the determinant oI Y.
2. X is may or may not be the key attribute oI R.
3. A FD changes with its real word meaning
Name address?
4. X and Y may be composite.
5. X and Y could be mutually dependent on each other
usband -- ~ WiIe, WiIe -- ~usband
6. The same Y value may occur in multiple tuples
Course # -- ~ Text

Pictorially FD can be represented
Assumes A - > B

A`s B`s








II t and u agree here then they must
agree here


A FD tells us about any two tuples t and u in relation R


(contd...)
Armstrong inference rules are


Sound
Produce only Iunctional dependencies in the closure
Additional Inference Rules:

Armstrong`s inIerence rules may be augmented with the Iollowing ones,
without aIIecting the power.


O Decomposition:
X1,..Xm}-Y1,..Yn,Z}
Implies X1..Xm}-Y1,.Yn}
And X1,..Xm}-Z

Number Name, Age}
Implies Number Name


O Union:
X1,.Xm}- Y1,.Yn}
And X1,.Xm} Z
Implies X1,.Xm} Y1,.YmZ}



How to find out closure of attributes

R (A,B,C,D,EF)
F: AB-C, BC-AD, D-E, CE B
ow to compute closure oI A,B}, i.e., A,B}?

1. Start with X A,B}
2. Add C to X due to AB C;X A,B,C}
3. Add A,D to X due to BC AD; X A,B,C,D}
X
Z X
Y Y
X
Y
X
Y
Z
X Z

4. Add E to X due to D E; X A,B,C,D,E}
5. No more attributes can be added to X
6. A,B} A,B,C,D,E}


(contd...)
Equivalence of sets of functional dependencies

Two sets oI Iunctional dependencies E and F are equivalent iI E* F*. hence
equivalence means that every FD in E can be inIerred Irom F, and every FD in F
can be inIerred Irom E, that is, E is equivalent to F iI both the conditions E covers F
and F covers E hold.

Minimal sets of functional dependencies

A set oI Iunctional dependencies F is minimal iI it satisIies the Iollowing conditions
1. Every dependency in F has a single attribute Ior its right hand side.
2. We cannot replace any dependency X A in F with dependency Y A,
where Y is a proper subset oI X, and still have a set oI dependencies that
is equivalent to F.
3. We cannot remove any dependency Irom F and still have a set oI
dependencies that is equivalent to F.
Minimal set oI dependencies in a standard or canonical Iorm with no redundancies.

Normalization

- Process oI grouping attributes into well structured relations.
InIormally, a well structured relation is one that contains a minimum
amount oI redundancy and allows users to insert, delete and modiIy
tuples in the relation without errors or inconsistencies resulting Irom
these operations.
- Based on an analysis oI functional dependencies and keys; a process Ior
converting complex data structures into samples, stable data structures.

Normalization and Database Design

- E-R Diagram provides macro view, determines entities
- Normalization provides macro view oI entities
- Focuses on characteristics oI speciIic entities
- May yield additional entities.

'Extra check: No attribute that is not a (primary/Ioreign) key should be repeated in
the database '

Essence of Normalization

1. ust as a paragraph should have a single theme, a
Relation (table) should have a single theme.

2. When relations have more than one theme, they are
vulnerable to modiIication anomalies.
3. When a relation has more than one theme, break it
Into two (or more) relations, each having a single
theme.

(contd..)
Functional dependency and the process of normalization
Normalization is a Iormal technique Ior analyzing relations based on
their primary key (or candidate keys in the case oI BCNF) and
Iunctional dependencies. Normalization is oIten perIormed as a series oI
tests on a relation to determine whether it satisIies or violates the
requirements oI a given normal Iorm. Three normal Iorms were initially
proposed, which are called Iirst (1NF), second (2NF) and third (3NF)
normal Iorm. Subsequently, a stronger deIinition oI third normal Irom
was introduced and is reIerred to as Boycd-Codd normal Iorm (BCNF).
All oI these normal Iorms are based on the Iunctional dependencies
among the attributes oI a relation.

Steps in Normalization

UNNORMALIZED
RELATION (nonNF)
NORMALIZED
RELATION (1NF)
SECOND NORMAL
FORM (2NF
TIRD NORMAL
FORM(3NF)
BOYCE-CODD NOR -
MAL FORM(BCNF)
FOURT NORMAL
FORM (4NF)
FIFT NORMAL
FORM (5NF)
DOMAIN KEY NOR -
MAL FORM (DKNF)
Remove repeating
groups
Remove partial
dependencies
Remove transitive
dependencies
Remove overlapping
candidate keys
Remove multi-valued
dependencies
Remove 'non-implied
join-dependencies
NOTE : For most database design tasks, normalization up to 3NF is suIIicient. BCNF is
said to be stronger than 3NF (in some design situations). Some database books
suggest normalization up to 4NF as ideal. The higher normal Iorms (IiIth and
domain/key) are oI theoretical interest but not particularly applicable to the design
process, reaching 4NF in the goal.









(contd...)
First thru fifth normal forms

First normal form: nay table oI data that meets the deIinition oI a relation.

1. The cells oI the table must have single value
2. Neither repeating groups nor arrays are allowed as values
3. All entries in any column (attribute) must be oI the same kind.
4. each column must have a unique name, but the order oI the
columns in the table is insigniIicant.
5. No two in a table may be identical and the order oI rows is in
signiIicant.

Table 2

Rno Sname Courses Registered
101 Sree DBMS
CN
OS
CO
102 Ram DBMS
CN
103 Deepthi OS
TOC

Table 2 is not in 1 NF

Table 3
Rno Sname CoursesRegistered
101 Sree DBMS
101 Sree CN
101 Sree OS
101 Sree CO
102 Ram DBMS
102 Ram CN
103 Deepthi CS
103 Deepthi TOC
Table 3 is 1 NF

Second normal form (2NF) : Deals with partial dependencies


1. Anomalies can occur when attributes are dependent on only part oI a multi
attribute key.
2. A relation is in second normal Iorm when all non-key attributes are
dependent on the whole key.
3. That is, no attribute is dependent on only a part oI the key.
4. Any relation having a key with a single attribute is in second normal Iorm.
(contd.)
Third normal form (3NF): Deals with transitive dependencies

1. Anomalies can occur when a relation contains one or more transitive
dependencies.
2. A transitive dependency exists when A -- ~ B-- ~C and NOT B-- ~A.
3. A relation is in 3NF when it is in 2NF and has a no transitive
dependencies.
4. A relation is in 3NF when 'All non-key attributes are dependent on the
key, the whole key and nothing but the key

&pdate anomalies occur in an 3NF relation R if

1. R has multiple candidate keys,
2. Those candidate keys are composite, and
3. The candidate keys are overlapped.

Boyce-Codd Normal (BCNF): Takes care oI all candidate keys

1. Anomalies can occur in relation in 3NF iI there are determinants in the
relation that are not candidate keys.
2. A relation is in BCNF iI every determinant is a candidate key.
3. To test whether relation is in BCNF, we identiIy all the determinants and
make sure that they are candidate keys.

BCNF is based on Iunctional dependencies that take into account all candidate
keys in a relation, however BCNF also has additional constraints compared with
the general deIinition oI 3NF given above.

Example: The Iollowing non-BCNF scheme cannot be decomposed into BCNF
in a way that preserves dependencies: S(,K,L) with dependencies K - ~L,L -
~K. this is not BCNF, since the candidate keys are K and L, but K depends
only on L. (L is thereIore a determinant, but not a candidate key.). There are
three possible decompositions into two schemes oI two attributes each oI which
only one is lossless-join: (,L) and (K,L). This does not allow the dependency to
K -~ L to be tested without a join.

Multi-valued Dependency (MVD) Represents a dependency between
attributes (Ior example, A, B, and C) in a relation, such that Ior each value oI A
there is a set oI values Ior B and a set oI values Ior C. owever, the set oI
values Ior B and C are independent oI each other.


A multi-valued dependency can de deIined as being trivial or nontrivial. A
MVD A ~ B in relation R is deIined as being trivial iI (a) B is a subset oI A
or (b)
A U B R. A MVD is deIined as being nontrivial iI neither (a)nor(b) are
satisIied. A trivial MVD does not speciIy a constraint on a relation, while a
nontrivial MVD does speciIy a constraint.



(contd..)
Fourth normal form (4NF): Deals with multi valued dependencies.

1. Multivalued dependencies can occur in relation in BCNF.
2. A multivalued dependency (MVD) occurs when a single attributes, say
A, multidetermines two other independent attributes, say B and C. That
is,
A -- ~~ B and A -- ~~C.
3. X -- ~~ Y, ie X multi determines Y, when Ior each value oI X we can
have more than one value oI Y.

A relation is in 4NF when it is in BCNF and has no multi valued
dependencies.

Fourth normal Iorm(4NF) is a stronger normal Iorm than BCNF as it prevents
relations Irom containing nontrivial MVDs. And hence data redundancy. The
normalization oI BCNF relations to 4NF involves the removal oI the MVD Irom
the relation by placing the attribute(s) in a new relation along with a copy oI the
determinant(s).

Lossless-join dependency: A property oI decomposition, which ensures that no
spurious tuples are generated when relations are reunited through a natural join
operation. In splitting relations by projection, we are very explicit about the
method oI decomposition. In particular, we are careIul to use projections that
can be reversed by joining the resulting relations, so that the original relation is
reconstructed. Such decomposition is called a lossless-join (also called a
nonloss or nonadditive) decomposition, because it preserves all the data in the
original relation and does not result in the creation oI additional spurious tuples.
owever, there are cases were we require to perIorm a lossless-join decompose
oI a relation into more than two relations. These are the Iocus oI the lossless-
join dependency and IiIth normal Iorm (5NF). FiIth normal Iorm (5NF) (also
called project-join normal Iorm (PNF)) speciIies that a 5NF relation has no join
dependency.

Fifth normal form (5NF): Deals with join dependencies.

1. Deals with obscure join dependencies.
2. The consequences (iI any) oI such dependencies are known.


Domain/Key normal form (KD/NF)

1. A relation in DK/NF has no modiIication anomalies, and conversely
2. DK/NF is the ultimate normal Iorm; there is no higher normal Iorm
related to modiIication anomalies.
3. DeIn: A relation is in Dk/NF iI any constraint on the relation is a logical
consequence oI the deIinition oI keys and domain.
4. Constraint is any rule governing state values oI attributes that is precise
enough to be ascertained whether or not it is true.
5. E.g. edit rules, intra-relation and inter-relation constraints, Iunctional and
multi-valued dependencies.
(contd...)
6. Not including constraints on changes in data values or time-dependent
constraints.
7. Key the unique identiIier oI a tuple.
8. Domain: physical and a logical description oI an attributes allowed
values.
9. Physical description is the Iormat oI an attribute.
10.Logical description is a Iurther restriction oI the values the domain is
allowed.
11.ogical onsequence. Iind a constraint on keys and/or domains which, iI
it is enIorced, means that the desired constraint is also enIorced.
12.Bottom line on DK/NF: II every table has a single theme, then all
Iunctional dependencies will be logical consequences oI keys. All data
value constrains can them be expressed as domain constraints.
13.Practical consequence: Since keys are enIorced by the DBMS and
domains are enIorced by edit checks on data input, all modiIication
anomalies can be avoided by just these two simple measures.

Example 1: The table below lists customer/car hire data. Each customer may
hire cars Irom various outlets throughout Glasgow. A car is registered at a
particular outlet an can be hired out to a customer on a given date.

carReg
make Model custNo custName hireDate outlet
No
outlet Loc
M565 OGD Ford Escort C100 Smith, 14/5/98 01 Bearsden
M565 OGD Ford Escort C201 en,P 15/5/98 01 Bearsden
N734 TPR Nissan Sunny C100 Smith, 16/5/98 01 Bearsden
M134 BRP Ford Escort C313 Blatt,O 14/5/98 02 Kelvinbridge
M134 BRP Ford Escort C100 Smith, 20/5/98 02 Kelvinbridge
M611 OPQ Nissan Sunny C295 Pen, T 20/5/98 02 Kelvinbridge

IdentiIying the Iunctional dependencies represented by the data shown in the
table. State any assumptions you make about the data. Using the Iunctional
dependencies identiIied, describe and illustrate the process oI normalization by
converting table 1 to Third Normal Form (3NF) relations. IdentiIy the primary
and Ioreign keys in your 3NF relations.

















(contd..)
carReg
hireDate Make Model custNo custName outletNo outletLoc


2NF

carReg make model outletNo outletLoc


carReg
iredate custNo custName

Fd3Id4Id5 violates 3NF

3NF/BCNF
PK

FK FK PK
carReg hireDate custNo



model make
















Example 2: The table shown below displays the details oI the roles played by
actors/actress in Iilms.

FilmNo ITitle dingo Director actorNo aName Role Time
onscreen
F1100 appy
Days
D101


D101

D101
im Alan


im Alan

im Alan
A1020


A1222

A1020
Shella Toner


Peter watt

Shella Toner
ean Slimson


Tom kinder

Silva Simpson
15.45


25.38

22.56
F1109 Snake
bite
D076

D076
Sue Ramsay

Sue Ramsay
A1567

A1222
Steven
McDonald
Peter watt
Tim Rosey

Archie Bold
19.56

10.44

Describe why the table shown below is not in Iirst normal Iorm(1NF).


The table contains a repeating group; the details oI actors/actresses are repeated Ior
each Iilm. As a consequence, there are multiple values at the intersection oI certain
rows and columns. IdentiIy the Iunctional dependencies represented by the table
shown above. Using the Iunctional dependencies identiIied, described and illustrate
the process oI normalization by converting the table shown above to Boyce-Codd
Normal Form(BCNF). IdentiIy the primary and Ioreign key in your BCNF relations.
The process oI normalization is shown in Iigure below.










carReg hireDate custNo
model make
model make
















Objective type questions

1.




The diagram represents what inIerence rule
a) Inclusion rule b) Transitive rule c) Augmentation rule d) union
rule

2. Suppose that we have a relation schema R(A,B,C) representing a
relationship between two entity sets with keys A and B respectively and
suppose that R has the FDs A B abd B A. what FDs imply about the
relationship.
a) one to many b) one to one c) many to one d) many to many

3. Relation R ABCD with AB as primary key. Mentioned FD so that R in 1
NF but not in 2NF.
a) AB C b) AB D c) A C d) A B

4. Relation R ABCD with AB as primary key. Mentioned FD so that R in 2
NF but not in 3NF.

a) D C b)AB C c) AB D d) A B

5. R ABCD with FD B C; iI A is a candidate key Ior , under what
conditions R to be in BCNF?

a) B is not a key Ior R b) B is a key for R c) C is a key Ior R d)
BC is a key.

6. A relation R(ABCDE) and the set oI FDs on R is F AB CD, ABC E,C
A}. Find the number oI candidate key.

a) 1 b) 2 c) 3 d) 4 e) none
7. R(ABCDE) and F A B, BCD, DE4 } Find the no.oI redundant Fds in
F.
a)1 b)2 c)3 d)4 e)none
(contd.)
8. A relation R


P Q R S


P1
Q1
Q2
Q3
R1
R2


S1
P2 Q1 R2
R3
S1
S2
P3 Q4 R4 S1
S2
i) What is the normal Iorm oI the above relation
a) 1NF b) 2NF c) 3NF d)none

ii) II the above relation is converted to BCNF what will be the
no.oI rows in the resulting relation.
a) 10 b) 12 c) 14 d) 16 e) none
9. Decomposition rule is

a) XZ YZ , X Y b) XY, YZ,XYZ
c) XYZ[ XY, XZ d)XY, WYZ,WXZ e)none
10.A relation R(ABCDEFG) with Fd set F ABCDE, C D, EAB}. What
is the normal Iorm oI the above relation.

a) 1NF b)2NF c)3NF d)BCNF e)none
11. A relation R(ABCDEFG) with Fd set F ABC, AB DE, DEF, FA}.
Find the number oI candidate keys.
a) 2 b) 3 c)4 d) 5 e) none
12. A relation R having Iive attributes (ABCDE), with the Iollowing instance
(a,2,3,4,5),(2,a,3,4,5),(a,2,3,6,5),(a,2,3,6,6)}. Which o the Iollowing FDs or
MVDs cannot be inIerred Irom the above instance.
a) ABC b) BC D c) C DE d)CDE


13. Every binary relation is in ----------normal Iorm
a)BCNF b) 3 NF c) 4NF d)P1NF e)none

14.Consider a schema R (ABCDE) with dependencies ABC,BCD, DEA}.
ow many no.oI non prime attributes are there in the above relation R.
a)0 b)2 c)1 d)4 e)none

15.A relation R(ABC having the tuples(1,2,3)(4,2,3) and (5,3,3). Which oI the
Iollowing dependencies can you inIer does not hold over the relation R.

a) A B b) BC A c) BC d) ACB e)none




(contd.)
16.A relation R(ABCDE) and Iunctional dependency set FABCDE,
CD,EA} and is decomposed into BCNF. Which oI the Iollowing best
combinations can be achieved.
I. Loss less II. Lossy
III. Not dependency preservary IV. Dependency preserving
a) I&II b)I&IV c)II&III d)II&IV e)none

17.Consider the set oI Fractional Dependency
F PQR, PQ, SPQ, ST}
G PQR, SPT} which oI the Iollowing is true.
a) F covers G b) G covers F c) F and G are required
d)cannot say e) none

18.F XYZ, YXZ, ZX}. how many no.oI minimal and canonical covers
are possible respectively.
a) M.C 2, C.C 1 b) M,C ~ 1, C.C 2
c) M.C 2, C.C 2 d) M,C 1, C.C 2

19.A relation R(ABCDE) with the Fd set F ABCD, BC D, DB}
a. is the above relation can be decomposed into 2NF without violating
dependency preservation.
b. Is the above relation can be decomposed into 3NF without violating
dependency preservation. y yes x no
a) I is y, II is y b) I is y, II is x c) I is x, II is y d) I is x, II is x
e) none
20.A relation R(ABCDEFGI) with Iunctional dependency set
FABC,ADE, B F, F G, D I}, and the decomposition oI R is
R1(ABCD) R2(DE) R3(BF), R4(FG), R5(DI)} which oI the Iollowing is
true.
I. Loss less II. Lossy
III. Not dependency preservary IV. Dependency preserving

a)I&II b)I&IV c)II&III d)II&IV e)none

21.R(ABCD) is a relation. Which oI the Iollowing doesn`t have either loss less
join or dependency preserving BCNF decompositions.
a)A B. BCD b) AB C. C D
c) ABC. C D d) ABCD. C A e) none

22.A relation R (ABCDEF) with Fd set FAC. BD. CE.DE.EA.
FB}
Find the no oI candidate keys
a) 2 b) 4 c) 6 d) 9 e) none

23.The Iollowing Iour tuples in a relation R with three attributes ABC: (1,2,3),
(4,2,3), (5,3,3), (5,3,4). Which oI the Iollowing Iunctional and multi valued
dependencies can you inIer does not hold over relation R.
a) A B b)BC A c) B C d) B C e) none

24. A relation R (ABCDEF) with Fd set F ABC DE, BCD, EF} and is
properly decomposed into BCNF. Then Iind the no oI Ioreign keys in
decomposed relations.
a) 3 b) 4 c) 2 d) 1 e) none

25.Consider two dependency sets F and G
F A B, ABC, D AC, D E} G A BC, D AB}
a) F covers G only b) G covers F only c) F&G are
equal d) can`t say e) none.

26.A relation R(ABCDE) and the dependency set F ABCD, CDE, AF}.
Find the normal Iorm oI above relation.
a) 2NF b) 1 NF c) 3NF d) BCNF e) none

27.A relation R (ABCDE) and the dependency set F AB, BCD, D E}.
Can you decompose above relation into BCNF without violating
dependency preservation.
a) yes b) no c) can`t say d) none

28.What is the normal Iorm oI above relation?
a) 1NF b) 2 NF c) 3NF d) BNF e) none


29.The relation R (ABCDEF) with the set Fds
F ACE, BD, CAD, BDEF}.
Find the closure oI AB
a) ABCE b)ACED c) ABCD d)ABCDE
e)none
30.Consider the relation scheme R (ABCDE) and the Fds AB, CD, AE} is
the decomposition oI R into (ABC) (BCD), (CDE) IS
I. Loss less II. Lossy

III. Depending preserving IV. not Dependency
preserving
a) I&III b) I&IV c)II&III d)none

31.A relation scheme R is in BCNF and at least one oI its key consists oI a
single attribute. What is the normal Iorm oI the relation.
a) BCNF b) 4NF c) 5NF d) can`t say e) none

32.Given the Iollowing relation instance







Which oI the Iollowing Iunctional dependencies are satisIied by the instance.
a) XY Z and ZY b) XZ X and YZ
c) XY Z and ZX c) XY Y andYZ
33. R (ABCDEFG) with Fds F AC, BD, EF, G, CG}.
(i) ow many y no.oI candidate keys are there?
a) 1 b)2 c) 3 d) 4 e) none
(ii) What is the normal Iorm oI the above relation?
a) 1NF b)2NF c) 3NF d) BCNF e) none
34. A relation R(AB) and primary keys is A and B is a Ioreign key deIining the
same relation R which oI the Iollowing row sequence can be inserted into
R.
a) (a1,a2)(a2,a3)(a3,a4)(a4,a5) b) (a1,null)(a2,a1)(a4,a3)(a3,a2)
c) (a1, null)(a2,a1)(a3,a2)(a4,a5) d) (a1,null)(a1,a2)(a2,a3)(a3,a2)
e) none of the above can` be inserted.
35. A relation R(ABCDE) with Id set F ABC, CDE, DE} and the
decomposition p R1 (ABCD), R2(DE)}

I. Loss less II. Lossy
III. Dependency presssury IV. not Depending presence
a) I&III b) I&IV c) II&III d) II&IV
e)none

Problems
1. T1 T2 T3
Row
1
2
3
4
5
6

X Y Z
1
1
4
3
4
5
6
2
3
3
3
2
A B
X1 Y1
X2 Y2
X3 Y1
X4 Y1
X5 Y2
X6 Y2
A B
X1 Y1
X2 Y4
X1 Y1
X3 Y2
X2 Y4
X4 Y3
A B
X1 Y1
X2 Y4
X1 Y1
X3 Y2
X2 Y4
X4 Y4

2. List the Iunctional dependencies satisIied by the relation.





3. Suppose that we have the Iollowing three tuples in a legal instance oI a
relation schema`s with three attributes ABC are


r1
r2
r3

Can you identiIy any dependencies that hold ones S`.





(contd...

4. Consider the relation

Tuple
1
2
3
4
5
6

Which one oI the Iollowing dependencies may hold in the above relation?
(i) A B
(ii) B C
(iii) C B
(iv) B A
(v) C A

5. List the Iunctional dependencies Ior the relation given below.






6. Consider a relation ABCDEFG and FDs are
AB
BCDE
A B C
a1 b1 c1
a1 b1 c2
a2 b1 c1
a2 b1
c3
A B C
1 2 3
4 2 3
5 3 3
A B C
10 b1 c1
10 b2 c2
11 b4 c1
12 b3
c4
13 b1 c1
14 b3 c4
A B C D
a1 b1 c1 d1
a1 b1 c2 d2
a2 b1 c1 d3
a2 b1 c3 d4

AEG G
Compute AC

7. Compute B Ior the relation R(ABCDE) and FDs are
A BC
CD E
B D
E A

8. Compute a relation with R(ABCDEF) and FDs are
AB C
BC AD
D E
CF B
Find AB





(contd...)
9. R(ABCDEFG) and FDs are
A BC
CD E
E C
D AE
AB BD
D BC
Find BCD implies Irom above original set

10.Consider the Iollowing two sets oI FDs
F AC, ACD, EAD, E }
G A CD, E A }
Find the equivalent oI two sets oI FDs

11. Consider two sets oI FDs on the attributes ABCDE
F BCD, ADE, BA }
G B CDE, B ABC, AD E }
Find whether them are equivalent or not

12.II R (ABCDE) and
FDs ABC, CDE, EC, DAE, ABBD, DBC} Iind keys

13.Consider a relation with Iive attributes ABCDE and FDs
AB
BCE
EDA List all keys Ior R


14.R(ABCDE) & FDs are ABC
CDE
DEB List all keys Ior R

15. R(ABCDEFGI) & FDs are
ABC
ADE
BF
FG
DI List all keys Ior R

16.R(ABCDEFGI) & FDs are
ABC
BDEF
ADG
AI
List all keys Ior R




(contd..)
17.R(ABCD) & FDs are
ABC
CD
DA
Find all keys Ior R. What are the super
keys
18.II R ABCDE & Fds are
ABC
CDE
BD
Find all candidate keys.

19.R(ABCDEFGI) & FDs are
ABDE
AB G
B F
C
C I
G List all keys Ior R
20.Find the irreducible set Irom the Iollowing FDs
1. A B
2. C B
3. D ABC
4. AC D

21.Consider Universal table with attributes ABC and FD set

1. AB C
2. C B
3. A B
Find the irreducible set
22. FDs are ABD AC
C BE
AD BF
B E Find the minimal set
23. FDs are A BC
ABE CDG
C GD
D G
E F Find the minimal set
24. FDs are BCD A
BC E
A F
F G
C D
A G Find the minimal set



(contd...)
25. Consider universal relation R ABCDEFGI and the set oI FDs
F AB C
A DE
B F
F G
D I
What is the key Ior R. Decompose R into 2NF
26. Consider the relation Ior published books
A B C D E
F
Book(Booktitle, Authorname, Booktype, Listprice,
AuthoraIIliation, Publisher)
FDs
Booktitle Publisher, Booktype
Booktype Listprice
Authorname AuthoraIIliation
Find the keys and normalize into 2NF.
27. Consider a relation R ABCDE. Primary key is AC is the key and
additional FDs are
BE
CD
AB Normalize up to 2NF

28. Consider R A B C D E F G I
FDs are AB C

BD EF
AD G
A I
Find the keys and normalize table up to 2
NF
29. (a) Give a set oI FDs Ior the relation schema R (A,B,C,D) with primary
key AB under which R is 1NF but not in 2 NF.
(b) Find FDs such that R is in 2 NF but not in 3 NF.
30. Consider a relation with Iive attributes ABCDE, FDs are AB, BCE,
EDA. Find keys also Iind whether it is in 3NF or BCNF.
31. Suppose you are given a relation R with Iour attributes ABCD. For each
oI the Iollowing sets oI FDs, assuming those are the only dependencies
that hold Ior R, do the Iollowing.
a) IdentiIy the candidate keys
b) IdentiIy the best normal Iorm that R satisIies (1NF, 2NF, 3NF or
BCNF)
c) II R is not in BCNF, decompose into a set oI BCNF relations that
preserve the dependencies.
1. C D, C A, B C
2. B C, D A
3. ABC D, D A
4. A B, BC D, A C
5. AB C, AB D, C A, D--. B.

(Contd.)

32. Consider R(ABCDEFG)
FDs are
AB CEFG
A D
F G
FB
BC ADEFG
FBS ADE Normalize the table up to BCNF

33. R ABCEDFG and
FDs 1. BCD A
2. BC E
3. A F
4. F G
5. C D
6. A G
PerIorm decomposition up to 3 NF and BCNF.
34. R ABCDEFG and
FDs:
1. A BC
2. ABE CDG
3. C GD

4. D G
5. E F Decompose up toBCNF

35. Suppose you are given a relation R(ABCD) Ior ------ oI the Iollowing
sets oI FDs, assuming they are the only assuming they are the only
dependencies that hold Ior R, do the Iollowing.
a) IdentiIy the candidate keys.
b) State whether or not the proposed decomposition oI R into
smaller relations is a good decomposition brieIly explains why or
why not?
1. BC, D A, decompose in to BC & AD
2. AB C, C A, C D; decompose into ACD,BC
3. A BC, C AD, decompose into ABC,Ad
4. A B, B C,C D; decompose into AB& ACD
5. A B, B C, C D; decompose into AB, AD &CD.
36. R ABCDE; FDs ABCDE, A C, DE. Find R satisIies what NF
and decompose up to BCNF.
37. R ABCDE and FDs ACDE, A C, CD. decompose up to BCNF

38. R ABCDEF and FDs ABCDEF, B CD, CD, EF,EB.
decompose up to BCNF
39. R ABCDE & FDs ABCDE, C A, DE. decompose up to BCNF
40. R ABCD & FDs AB, B C, CD. decompose up to BCNF
41. R ABCDE & FDs ABCD, C A, AC. decompose up to BCNF

(contd.)

TOPIC - 3 : SQL

What is SQL ?
O Structured query language
O A declarative query language.
O Its prototype, SEQUEL, was developed at IBM Research.
O Standard in 1986 (SQL1 or SQL-86) and 1992 (SQL2 or SQL-92).
O Consists DDL,DML, and DCL.
O Basic elements ---- statements/commands.
O Many other Iunctions: deIining views, indexes, embedded in a host
language, etc..
O Available in almost all commercial DBMS
O SQL is case intensive.

DDL is Data DeIinition Languages statements. Some examples:
OCREATE to create objects in the database
OALTER alters the structure oI the database.
ODROP delete objects Irom the database
ORUNCATE remove all records Irom a table, including all spaces allocated
Ior the records are removed.

OCOMMENT add comments to the data dictionary.
OGRANT gives user`s access privileges to database
OREVOKES withdraw access privileges given with the GRANT command.

DML is Data Manipulation Languages statements. Some examples:
O SELECT retrieve data Irom the database
O INSERT insert data into a table
O UPDATE updates existing data with in a table.
O DELETE deletes all records Irom a table, the space Ior the records
remain
O CALL call a PL/SQL or ava subprogram
OEXPLAIN PLAN explain access path to data
OLOCK TABLE control concurrency

DCL is Data Control Languages statements. Some examples:
OCOMMIT save work done
OSAVEPOINT identiIy a point in a transaction to which you can later roll
back
OROLLBACK restore database to original since the last COMMIT
OSET TRANSCATION change transaction option like what rollback
segment to use

SQL DML SELECT
SELECT |DISTINCT ,ALL| *, |column expression |AS newname|| |.|}
FROM table-name |alias| |.| -SpeciIies the table or tables to be used
| WERE condition| -Filters the rows subject to some condition
|GROUP BY column list| -Forms groups oI rows with the same column value
|AVING condition| -Filters the groups subject to some condition.
|ORDER BY column list| -SpeciIies the order oI the output.
(contd..)
Conceptual order oI evaluation oI a select statement

O First the Cartesian product oI all tables in the FROM clause is Iormed.
O From this, rows not satisIying the WERE condition are eliminated.
O The remaining rows are grouped in accordance with the GROUP BY clause.
O Groups not satisIying the AVING clause are then eliminated.
O The expressions oI the Select clause target list are evaluated.
O II the key word DISTINCT is present, duplicate rows are now eliminated.
O The UNION, INTERSECT, EXCEPT is taken aIter each subquery is
evaluated.
O Finally, the set oI all selected rows is stored iI an ORDER BY is present.

Simple SELECT
O SELECT attributes (or calculations:,-,/,*) FROM relation
O SELECT DISTINCT attributes FROM relation
O SELECT attributes (or* wild card) FROM relation WERE condition

Example

O SELECT stuname FROM student;
O SELECT stuid, stuname, credits FROM student;
O SELECT stuid, stuname, credits10 FROM student;
O SELECT DISTINCT major FROM student;
O SELECT * FROM student;
O SELECT stuname, major, credits FROM student, WERE stuid S114`;
O SELECT * FROM Iaculty WERE dept MIS`;

SELECT - WHERE condition AND OR
O NOT IN
O NOT IN BETWEEN
O IS NULL IS NOT NULL
O SOME ALL
O NOT BETWEEN
O LIKE ` multiple characters
O LIKE ` single character
O Evaluation rule: leIt to right, brackets, NOT beIore AND&OR, AND beIore
OR

Example
O SELECT * FROM Iaculty WERE dept MIS` AND rank Iull
proIessor`
O SELECT * FROM Iaculty WERE dept MIS` OR rank Iull proIessor`
O SELECT * FROM Iaculty WERE dept MIS` NOT rank Iull
proIessor`,
O SELECT * FROM class WERE room LIKE bs`;
O SELECT * FROM class WERE room NOT LIKE bus`;
O SELECT productid, productname FROM inventory WERE onhand
BETWEEN 50 and 100.




(contd..)
O SELECT customerid, discountrate FROM sales WERE discountrate LIKE
20#` ESCAPE #`;
O SELECT companyid, companyname FROM company WERE company
BETWEEN G` AND K`;
O SELECT productid, productname FROM inventory WERE onhand NOT
BETWEEN 50 and 100
O SELECT companyid, companyname FROM company WERE
companyname NOT BETWEEN G` AND K`
O SELECT Iacname FROM Iaculty WERE dept IN (MIS,`ACT);
O SELECT Iacname FROM Iaculty WERE rank NOT IN
(assistant`,`lecturer`);
O SELECT customername FROM customer WERE emailed IS NOT NULL
O SELECT customername FROM customer WERE creditlimit ISNULL


SELECT - aggregate function
O COUNT
O COUNT(*)
O SUM
O AVG
O MIN
O MAX

Example
O SELECT COUNT(*) FROM student
O SELECT COUNT(major) FROM student
O SELECT COUNT(DISTINC major) FROM student; SELECT
COUNT(stuid),SUM(credits), AVG(credits), MAX(credits), MIN(credits)
FROM students
SELECT - GRO&P
O GROUP BY
O AVING

Example
O SELECT major, AVG(credits)FROM student GROUP BY major
O SELECT course#, COUNT(stuid)FROM enrollment GROUP BY course#
O SELECT major, AVG(credits)FROM student GROUP BY major

AVING COUNT (*) ~2.






(contd..)



O SELECT course#, COUNT(stuid)FROM enrollment GROUP BY
course# AVING COUNT(*)~2
O SELECT major, AVG(credits)FROM student WERE major IN
(mis`,`act`)GROUP BY major AVING COUNT(*)~2;

SELECT - ORDER BY
O ORDER BY
O ORDER BY. DESC Example
O SELECT Iacname, rank FROM Iaculty ORDER BY Iacname
O SELECT Iacname, rank FROM Iaculty ORDER BY rank DESc,
Iacname

SELECT 1OIN Tables:

O Multiple tables in FROM clause
O Must have OIN conditions!!!

Example
O SELECT stuname, grade FROM student, enrollment WERE student.stuid
enrollment.stuid;

List course#, stuname and major for faculty number is equal to 114
O SELECT enrollment, course#, stuname, major FROM class, enrollment,
student WERE class,course# enrollment.course# AND enrollment.stuid
student.stuid AND Iacid F114`
ORDER BY enrollment.course#

O&TER 1OINS
O RIGHT 1OIN
O LEFT 1OIN
O F&LL 1OIN
O Appending () to the optional column (null) in the join condition (oracle)

ist the faculty member who does not reach any class
O SELECT I.Iacid, I.Iname FROM class c, Iaculty I WERE c.Iacid ()
I.Iacid AND c.course# is null ORDER BY I.Iacname;(right outer join
using ON)


(contd..)
a) Gets the supplier`s number and name where supplier
name is TAPI
b) Get the supplier numbers and suppliers name who
are located in the same city asTAPI
c) Gets the suppliers number oI TAPI and city oI TAPI

25. Table P(P#, WEIGT,COLOUR, COST, SELLING PRICE)
P#: Partno, P: parts then
SELECT P#, COST FROM P WERE COST ANY (SELECT
COST FROM P);
a) get the partno, Irom parts whose cost is minimum oI all
b) get the part numbers from parts whose costs is less than the
current maximum cost

c) get the part number whose cost is maximum
d) get the part numbers Irom parts whose cost is greater than any
cost oI party.
26. S(S#,SNAME, SCITY, TURNOVER),
SP(S#,P#,QTY)
To get the names oI suppliers who supply part2
I. SELECT S.SNMAE FROM S WERE S.S# IN
(SELECT SP.S# FROM SP WERE SP.P# 2)
II. SELECT S.SNMAE FROM S WERE 2
IN(SELECT P# FROM SP WERE S.S# S#)
a) I is true, II is Ialse b)I is Ialse,II is true c)I is true, II is true d)I is Ialse, II is
true
27. SELECT SNAME FROM S WERE EXISTS(SELECT * FROM
SP WERE SP.P# S.S#) it retrieves
a) the supplier name who supplied all the parts
b) the supplier name who supplied nothing
c) the supplier name who have supplied exactly one part
d) the supplier name of suppliers who supply at
least one part
28. SELECT SNAME FROM S WERE 2~ ALL(SELECT P# FROM
SP WERE S# S.S#) it retrieves
a) get the supplier names oI suppliers who support part 2
b) get the suppliers names oI suppliers who supply at least 2
parts
c) get the suppliers names oI suppliers who do not supply a part
2
d) get the suppliers names oI suppliers who supply exactly 2
parts
29. SELECT SNAME FROM S FIRST WERE 2 (SELECT
COUNT(CITY) FROM S WERE CITY FIRST.CITY)
a) get the names oI suppliers who supply Irom a city
where there is at least two more suppliers.
b) Get the names of suppliers who supply from a city
where there is atleast one more supplier.
c) Get the names oI suppliers who supply Irom a city
where there is more than two suppliers
d) Get the names oI suppliers who supply Irom a city
where there is atmost two suppliers.

(contd....)
30. The SQL expression
SELECT DISTINCT T.branchname FROM branch T, branch S
WERE T.assets~s.assets AND S.branchcity 'YD Find the
names oI
a) All branches that have greater assets than some branch located in
HYD.
b) All branches that have greater assets than all branch located in YD.
c) The branches that has the greatest asset in YD

d) All branches that has greater asset than any branch located in YD.

31. Which oI the Iollowing is/are correct?
I. an SQL query automatically eliminates duplicates
II. an SQL query will not work iI there are no indexes on the
relations.
III.SQL permits attribute names to be repeated in the same
relation.
a) II, III b) II c)III, I d) none

32. choose the incorrect statement(s)
I. Procedural data manipulation language(DML) requires
users to speciIy what data is needed and how to get it.
II. Procedural DML requires users to speciIy what data is
needed without speciIying how to get it.
III. Non procedural DML requires the user to speciIy what
data is needed without speciIying how to get it
a) I, II, III b) I, II c) III d)II

33. Consider the set oI relations
EMP(Empno, Deptno, Ename, Salary)
DEPT(Deptno, Deptname, Location)
SQL : Select Deptno, Count(*) Irom EMP, DEPT Where
EMP.Deptno DEPT.Deptno And Salary ~ 100000
a) it counts the departments where the employees salary greater
than 100000
b) it counts for each department, the number of employees with
a salary greater than Rs.100000
c) it gives the employees details in each dept who got sal~100000
d) none

34. Consider a bank database with only one relation
Transaction(transno, acctno, date, amount)
The amount attribute value is positive Ior deposits and negative Ior
withdraws
Create view TP (acctno, date, amount) as select T1.acctno,T1.date,
T2.amount
From Transaction T1, Transaction T2 Where T1.acctnoT2.acctno
And T2.date T1.date
It deIine an SQL view TP containing the inIormation (acctno,
T1.date, T2.amount)Ior every pair oI transactions T1,T2 such that T1
and T2are
Transactions on the same account and the date oI T2 is the date oI
T1.(true are Ialse)
a) True b)Ialse


35.Consider the relation examine (rengo,name,score) where

Is the the primary key and score is real number.
An SQL query to list the regno oI examinees who have a
Score greater than the average score.
a)SELECT regno FROM examinee WERE score~
avg(score)
b) SELECT regno, avg(score)FROM examinee WERE
score~avg~(score)
c) SELECT regno FROM examinee where score
SELECT avg (score)FROMexaminee)
d) done

36. consider the set oI relations shown below and the SQL
Query that Iollows:
Students:Rollnumber,,Name,DateoIbirth)
Courses:Coursenumber,CCoursename,Instructor)
GradesRollnumber,Coursenumber,Grade)
SELECT DISTINCT Name
From Students,Courses,Grades WERE Students.
RollnumberGrades,Rollnumber
AND courses,instructorkorth
AND courses .CoursenumberGrades Coursenumber
AND Grades.GradeA which oI the Iollwing sets is
Computed by the above query?
a) Name oI students who have got an A Grade in all courses
taught by korth
b)Name oI students who have got an A grade in all courses
c)Name oI students who have got an A grade in at least one oI
courses taught by korth.
d) none oI the above
37. Table:
Employee (Fname,minite,SSN,Bdate,Address,Sex,Salary,
Superssn,dno) SQL query to retrieve the names oI all employee
S who do not have supervisions ?
a)SELECT Fname ,Lname FROM employee WERE Superss
0
b)SELECT Fname,Lname FROM employee WERE superssn
null
c)SELECT Fname,Lname FROM employee SSN IS NULL
d)SELECT Fname,Lname FROM employeeWERE Superssn
is null
38.Consider the join oI a relation R with a relation S.II R has m
Tuples and S has n tuples.then the maximum and minimum
And minimum sizes oI the join respectivevly are
a)mn and 0 b)m n and 0 c)mn and (mn) d)mn and
mn.
39. In SQL relations can contain null values and comparisons
With null values are treated as unknown Suppose all compare
sons with a null values are treated as Ialse which oI the

Iollowing pairs is not equivalent?
a)x5 not(not(x5) b)x5 x~4andx5,where x is an
integer c)x#5 not(x5) d)none oI the above.
40. A Iile manipulation command that extracts some oI the
Records Irom a Iiles is called
a)SELECT b)PROECT c)OIN d)none oI the above
41.Two Iiles be joined into a third Iile iI
a)They have a row in common b)they have a Iield in common
c)they have no records with the same values in common Iield
d)none oI the above
42.The PROECT command will create new table that has
a)more Iields than the original table b) more rows than the
original table c) both (a) and (b) above
d) none oI the above

43.A good query system
a) can accept English language commands
b) allows non-programmers to access inIormation stored in a
database
c) can be accessed only by data processing proIessionals
d) both (a) and (b) above

44 . The Iield size oI a city is determined by
(a) The shortest city name that will be entered
(b) The largest city name in the United states
(c) The largest city name that will be entered in the database
(d) Ten characters more than the largest city name that will
be entered in the database
45. II a Iield size is too small Ior the largest piece oI data to be entered
a) The database program will Ireeze
b) The Iield will automatically explained
c) Part of the data will be cut off
d) none oI the above
46. Which oI the Iollowing is true Ior the data manipulation language(DML) ?
a) It cannot interIace with high level programming languages.
b) It is used to deIine the physical characteristics oI each record
c) It is essentially the link between the logical and physical views oI the
database
d) none of the above
47. The language used in application programs to request data Irom the DBMS
is reIerred to as the
a) DML b) DDL c) Query language d) none oI the above
48. employees(id, Iirstname, lastname, Salesquota, address, phone number,
department, commission, bonuslevel,totalsales, hourlyrate,
Salescalls, SalesCount)
Set the values oI the SALESQUOTA column in the EMPLOYEES table to
1 Ior new employees who have not yet been assigned a quota

a) SELECT id, first_name, last_name, N&LL IF (SALES_Q&OTA,-1) as
Quota FROM employees
b) SELECT id, Iirstname, lastname, (SALESQUOTA -1) Quota FROM
employees
c) SELECT id, Iirstname, lastname, set(SALESQUOTA -1) Quota
FROM employees
d) SELECT id, Iirstname, lastname, (IF NULL (SALESQUOTA) SET(-1)
QUOTA FROM employees


(contd..)


































49. employees(Empid, Fname, Lname, dept, position) the SQL queries
SE:LECT dept FROM employees e GROUP BY dept

AVING (SELECT COUNT(*) FROM employeese where
e.deptcse.dept AND (position LIKE Managers` OR position
LIKE Supervisors` OR position LIKE President)}
~(SELECT COUNT(*) FROM employees cse Where e.deptcse.dept
AND (position NOT LIKE Manager` AND position NOT LIKE
Supervisor` AND position NOT LIKE Supervisor`
AND position NOT LIKE President)) ORDER BY dept:

a) will display the names oI the departments that have managers,
supervisors, president
b) will display the names oI the department that have managers,
assistant managers, supervisor, vice president (or) President
c) will display the names oI departments that have more employees
with job titles such as managers, supervisors (or) president than not
d) will display the names oI the departments that have more employees
with job titles such as manager, assistant manager, supervisor, vice
president or president than not.

50. invoicedeatils(itemnumber, price, invoicedat, invno);
Inventory(itemno,price, invdate,...)
Invoices(invno, invdate,....)

UPDATE query:
UPDATE inventory SET price price*:75 WERE NOT EXISTS
(SELECT * FROM invoicedetails i WERE inventory.item no
i.itemnumber AND invno IN (SELECT invno FROM invoices WERE
invdate~ GETDATE() 30))
a) it gives 25 discount to only those items that have had sales within the past 30
days
b) to discount only those items that have had sales within last 30 months
c) to discount to only those things that has sales since the invdate
d) to discount only those items that have had no sales within the past 30 days
51. Customer(Custid, Iname, empid, totalpurchases)
employees(empid,Iname, lname)
SQL:
SELECT empid, Iname, lname FROM employees WERE EXISTS
(SELECT * FROM Customers WERE Salesperson empid AND
(totalpurchases~100000 OP (SELECT SUM(totalpurchases) FROM
Customer WERE Salesperson empid)~500000))
It lists the salespeople Ior whom there exists atleast one customer with total
orders oI more than $ 100,000 or Ior whom there exists a set oI customers that
have made more purchases or more than 500000.
a) True b) Ialse



(contd...)
52. employees(empno, Iirstname, lastname, totalsales)

To list the names and total sales Ior the employees with the highest
TOTALSALES within the EMPLOYEES tables which is true Ior the above
statement.
a) SELECT Iirstname, lastname, totalsales FROM employees
WERE totalsales (SELECT MAX(totalsales)FROM employees);
a) SELECT Iirstname, lastname, totalsales FROM employees
WERE totalsales~ ALL(SELECT totalsales FROM employees)
WERE totalsales is NOT NULL);
c) both are true d) none oI the above are true

53. SELECT Iirstname, lastname, phonenumber FROM customer EXCEPT
Iirstname, lastname, phonenumber FROM employees);
a) lists all the customers that are employees
b)lists all the employees that are customers
c) lists all the customers
d) lists all the customers that are not also employees,
54. SELECT DISTINCT Studentid, Iirstname, lastname, GPA FROM students
WERE EXISTS (SELECT * FROM Iootballteam WERE
students.studentid Iootballteam.studentid);
a) lists the students that are Dean`s lists but not in Iootball team.
b) lists the students that are in Iootball team but not in Dean`s list
c) lists the students that are both in the football team and in Dean`s list
. d) none
55. employees(employeeid,Iname, lname, salary, totalsales, hiredate,
manager)
SELECT * FROM employees WERE (totalsa;les-25000)
BETWEEN (SELECT AVG(totalsales) FROM employees ) AND
SELECT(AVG(tptalsales) * 1.2 FROM employees);
a) it lists those employees whose total sales volume minus Rs25000 is
between the average sales volume and 120 present of the average
b) it retrieves the details oI employees whose total sales volume greater than
average sakes volume.
c) it lists those employees whose total sales volume minus 25000 is between
avgsales and 1.2 oI sales d) none
56. GUESTROSTER(NAME,DISCOUNT, TRAINER, DEPARTURE, ROOM,
ARRAIVAL)
SELECT NAME, DISCOUNT FROM GUESTROSTER
WERE DISCOUNT (SELECT DISCOUNT FROM GUESTROSTER
WERE NAME OANNIER RIVVLETS`);
a) it retrieves the name and discount received by joannie Rivvlets.
b) it retrieves the name and discount received by the guests except joannie
Rivvlets
c) it select all guests who receive the same discount as joannle Rivvlets. d)
none






(contd...)
57. GUESTROSTER(NAME, TRAINER , ROOM, DISCOUNT,
DEPARTURE, ARRAIVAL)
SELECT Trainer, Count(name) FROM GUESTROASTER GROUP BY
Trainer AVING COUNT(name)~(SELECT COUNT(name) FROM
GUESTROASTER WERE TRAINER ULIO`)
The query results

a) it gives the trainer and the no.oI Guests trained by ULIO.
b) it gives the TRAINER who gives training to more persons than 1&LIO
and it also displays no.of persons.
c) both d) none

58. SELECT Name, Trainer FROM GUESTROASTER WERE Trainer IN
(SELECT TRAINER FROM GUESTROASTER WERE Name Client
West word` OR Name warren Amoroso`)
The query results
a) The name and trainer oI either client westword or warren Amoroso
b) The name and trainer of everyone who has the same trainer as either
client westword and warren Amoroso
c) The name and trainer oI everyone who has the same trainer as client
westword or warren Amoroso d) none

59. Table Sales(titleid, qty, orddate)
SQL
SELECT titleid, copiessold SUM(qty) FROM Sales
WERE orddate BETWEEN 1/1/1994` AND 12/31/1994` GROUP BY
ALL titleid It lists

a) all the title ds and quality oI books sold b) all the title lds and total
quantity sold
c) total quantity oI books that sold during the year 1994
d) all the title ID`s and quantity of books sold during the year 1994.

60. Consider the Iollowing tables



REGION
REGIONCD REGIONNAME
N NORT
E EAST
W WEST
C CENTRAL

CITY
CITYID REGIONCD CITYNAME
01 N LUCKNOW

02 N KANPUR
03 W BOMBAY
04 S BANGLORE
05 W AMEDABAD
06 E CALCUTTA


(contd.)
Select regionname, city, name Irom region, city WERE region.region.cd()
city.region.cd
The output oI the Iollowing data is
A. B.
B.
REGIONNAME CITYNAME
EAST CALCUTTA
NORT LUCKNOW
NORT KANPUR
BANGLORE
WEST BOMBAY
WEST AMEDABAD

C. D. none oI the above

REGIONNAME CITYNAME
CENTRAL
EAST CALCUTTA
NORT LUCKNOW
NORT KANPUR

WEST BOMBAY
WEST AMEDABAD

61. A subquery is oI the Iorm oI a select statement enclosed in parenthesis. It can`t have
a) an order by clause b) a union oI selects c) both d) none

62. The sub query can select out only one column (except in the EXISTS predicate)
a) True b) Ialse

63. The nesting oI a query is possible upto
a) only one level b) 3 levels c) 5 levels d) none

64. GROUP BY can include expressions
a) True b)Ialse

65. Is there any 'GROUP BY ALL ' clause
a) yes b) No

66. Which oI the Iollowing is true
I. The WERE clause searches the rows aIter they are grouped by using GROUP BY` clause
II. The GROUP BY clause collects rows that met the WERE clause search conditions and
places those rows into a group Ior each unique value in the GROUP BY clause
III. Omitting the GROUP BY clause creates a single group Ior the whole table
a) I &II are true b)I & III are true c) II & III are true d)all are true


REGIONNAME CITYNAME
EAST CALCUTTA
NORT LUCKNOW
NORT KANPUR
BANGLORE
WEST BOMBAY
WEST AMEDABAD





(contd..)




67. A natural join eliminates the redundant column data in the results set that an equijoin produces
a) True b) False

68. An outer join can be done between
a) only two table b) only three tables(restricted to) c) any number oI tables d)none

69. II N` number oI tables joined should have a
a) maximum oI N 1` join clauses b) minimum oI 1` join clauses
c) maximum oI N` join clauses d) minimum of N - 1` join clauses

70. For selI join
a) table aliasing is not used b) table aliasing can be used
c) it is necessary to use tables aliases d) none

71. Table:1:authors(avid,avIname,avlastname,phone, address, city, state, zip, contact)
SELECT av1.avIname, av1.avlname, av2.avIname, av2.avlname FROM authors av1,
authors av2 WERE av1.city Okaland` AND av1.state CA` NAD av1.zip
av2.zip AND av1.avid av2.avid,
Will; results
a) which authors in Okaland, California(CA) live in the same zip code area.
b) which authors in Okaland, CaliIornia live in the same state
c) which authors in Okaland, CaliIornia in the diIIerent zip code area
d) non oI the above

72. Cross join in a join
a) with more than two tables b) with out a AVING clause
c) without a WHWRE clause d) none oI the above

73. which oI the Iollowing
I. II a table appears only in a subquery and not in the outer query, then columns Irom the
table cannot be included in the output
II. The SELECT statement oI a subquery may not be encloused in parenthesis
III. A subquery is used whenever an expression is allowed
IV. The DISTINCT key word cannot be used with sub queries that include a GROUP BY
clause
V. A view created with a subquery cannot be updated
a) I, II, III are true b) I,II,V are true
b) I, III,IV, V are true d) I, II, III, IV are true

74. From the employees table(emp)
Select the employees details those who are not managers
a) Select ename, empno, Irom emp e WERE not exists(SELECT * FROM emp WERE mgr
e.empno);
b) SELECT ename FROM emp WERE empno not in(SELECT DISTINC mgr FROM emp)
c) both a & b are true d) none



(contd..)











75. The INSERT SELECT statement
a) Inserts one row at a time b) Inserts two rows only
c) Inserts many rows d) None

76. Tables: EMPLOYEE(Fname,minit,Lname,San,Bdate, Address, Sex, Salary, Superssn, dno)
DEPARTMENT(dname, dnumber, mgrssn, mgrstartdate)
DEPENDENT(Essn, dependentname, Sex, Bdate, Relationship)
WORKSON(Essn, Pno, hours)
PROECT(pnmae, pnumber, plocation,dnum)
DEPTLOCATIONS(Dnumber, Dlocation)
SELECT Fname Lname FROM EMPLOYEE WERE
((SELECT pno FROM WORKSON WERE Ssn Essn) CONTAINS
(SELECT pno FROM PROECT WERE Dnum 5));
a) Retrieve the name oI each employee who works on all the depart no`s
b) Retrieve the name oI each employee who works on all the projects
c) Retrieve the name of each employee who works on all the projects controlled by
departments number 5
d) none

77. SELECT E.Fname,E.Lname FROM EMPLOYEES AS E
WERE E.Ssn IN (SELECT Essn FROM DEPENDENT
WERE E.Fname Dependentname AND E.Sex);
Output is (Consider the tables Irom Q.No.76)
a) Retrieve the name oI each employee who has a dependent with the same Iirst name
b) Retrieve the name oI each employee who has dependent with the same sex
c) Retrieve the name of each employee who has dependent with the same first name same
sex as the employee
d) none
78. To retrieve the name oI each employee who has a dependent with the same Iirst name and same
sex as the employee (Consider the tables Irom Q.No.76)
Give the SELECT statement:
a) SELECT E.Fname,E.Lname FROM EMPLOYEE AS E
WERE E.Ssn In(SELECT Essn FROM dependent
WERE E.Fname DEPENDENTNAME AND E.Sex Sex);

b) SELECT E.Fname,E.Lname FROM EMPLOYEE AS E, DEPENDENT AS D
WERE E.Ssn D.Essn AND E.Sex D.Sex
AND E.Fname DEPENDENTNAME
c) SELECT E.Fname,E.Lname FROM EMPLOYEE AS E
WERE EXISTS(SELECT * FROM DEPENDENT WERE E.Ssn Essn
AND E.Sex Sex AND E.Fname DEPENDENTNAME);
d) none





(contd..)












79. (Consider the tables Irom Q.No.76)
SELECT FNAME, LNAME FROM EMPLOYEE WERE EXISTS
(SELECT * FROM DEPENDENT WERE Ssn Essn)
AND EXISTS (SELECT * FROM DEPARTMENT WERE Ssn MGRSSN);
The results oI the Iollowing query is:
a) List the names oI all the employees who has managers
b) List the names oI all the managers who have dependents
c) List the names of managers who have at least one dependent
d) List the names oI all the employees with at least one dependent and managers

80. (ReIer Q.No 75) Ior tables
To retrieve the name oI each employee who works on all the projects controlled by department
number 5
The select statement is:
a) SELECT LNAME, FNAME FROM EMPLOYEE WERE NOT EXISTS
(SELECT * FROM WORKS ON B WERE (B.PNO IN
(SELECT PNUMBER FROM PROECT WERE DNUM 5))
AND NOT EXISTS (SELECT * FROM WORKSON C WERE C.ESSN SSN
C.PNO B.PNO));
b) SELECT FNAME, LNAME FROM EMPLOYEE WERE NOT EXISTS
((SELECT PNUMBER FROM PROECT WERE DNUM 5) EXCEPT
(SELECT PNUMBER FROM WORKSON WERE SSN ESSN);
c) SELECT FNAME, LNAME FROM EMPLOYEE
WERE ((SELECT PNO FROM WORKSON WERE SSN ESSN)
CONTAINS (SELECT PNUMBER FROM PROECT WERE DNUM 5));
D) ALL ARE TR&E

81. ReIer Q.No 76 FOR relations
SELECT DNUMBER,COUNT(*) FROM DEPARTMENT, EMPLOYEE
FROM DEPARTMENT, EMPLOYEE WERE DNUMBER DNO
AND SALARY~40000 AND DNO IN (SELECT DNO FROM EMPLOYEE
GROUP BY DNO AVING COUNT(*)~5) GROUP BY DNUMBER;
It retrieves
a) For each department, the department number and number oI its employees who are making
more than $40,000
b) For each department that has more than five employees, the department number and
the number of its employees who are making more than $40,000.
c) Number oI departments and employees who make more than $40,000.
d) none oI the above

82. ReIer Q.No 76 FOR relations
SELECT PNUMBER, PNAME, COUNT(*) FROM PROECT, WORKSON
WERE PNUMBER PNO GROUP BY PNUMBER,PNMAE AVING
COUNT(*)~2;
This select statement retrieves

For each project on which more than two employees work, it retrieves the project number, the
project name and the number oI employees who work on the project.
a) True b) False


(contd.)







TOPIC - 4 : RELATIONAL ALGEBRA & RELATIONAL CALC&L&S
Procedural language: a language that allows user to tell the system what data is needed and exactly
how to retrieve the data.
Non - procedural language: a language that allows user to state what data is needed rather than
how it is to be retrieved.

Relational algebra

InIormally, we may describe the relational algebra as a (high-level) procedural language; it can be
used to tell the DBMS how to build a new relation Irom one oI more relations in the database.
Again, inIormally, we may describe the relational calculus as a non-procedural language: it can be
used to Iormulate the deIinition oI a relation in terms oI one or more database relations.

Five basic operations are:
O Selection and projection(unary)
O Cartesian product, Union and Set DiIIerence (Binary).

There is also the join, Intersection, and Division operations

Theta join R3FS produces a relation that contains tuples satisIying the predicate
F Irom the Cartesian product oI R and S

Equi join R3FS produces a relation that contains tuples satisIying the predicate
F (which only contains equality comparisons) Irom the Cartesian
Product oI R and S

Natural join R 3 S An equijoin oI the two relations R and S overall common attribute x. one
occurrence oI each common attribute is eliminated

(LeIt) outer join R 5 S A join in which tuples Irom R that do not have matching values in the
common attributes oI S are also included in the result relation.

Semi join R1FS Produces a relation that contains the tuples oI R that participate in the join
oI R with S


Tuple relational calculus

The tuple relational calculus is based on speciIying a number oI tuple variables.
Each tuple variable usually ranges over a particular data base relation, meaning that
the variable may take as its value any individual tuple Irom that relation. A simple
tuple relational calculus query is oI the Iorm

t , COND(t) }


Where t is a tuple variable and COND (t) or FORMULA is a conditional expression involving t.
The result oI such a query is the set oI all tuples t that satisIy COND(t). For example, to Iind all
employees whose age is above 30, we can write the Iollowing tuples calculus expression:

t, EMPLOYEE (t) and t.age ~ 30}

(Contd..)






The condition EMPLOYEE (t) speciIies that the range relation oI tuple variable is EMPLOYEE.
Each EMPLOYEE tuple t that satisIies the condition t.age ~ 50000 will be retrieved.

A (well-formed) condition or formula is made out of one or more atoms, where an atom has
one of the following forms:

O . R(Si), where Si is a tuple variable and R is a relation.
O .Si.a10 Sj . a2, where Si and Sj are the tuple variables, a1 is an attribute oI the relation over
which Si ranges, a2 is a attribute oI the relation over which Sj ranges, and 0 one oI the
comparison operators (, _, ~, _, , =): the attributes a1 and a2 must have domains whose
members can be compared by 0
O .Si. a1 0c, where Si is a tuple variable, a1 is an attribute oI relation over which Si ranges, c
is a constant Irom the domain oI attribute a1 and 0 is one oI the comparison operators.

We recursively build up condition or Iormulae Irom atoms using the Iollowing rules:
O .an atom is a Iormula:
O .iI F1 and F2 or Iormulae, so are their conjunction F1 ` F2 and their disjunction F1 v F2 and
the negation ~F1:
O .iI F is a Iormula with Iree variable X, then (3X)(F) and ( X)(F) are also Iormulate.

The Existential and &niversal Quantifiers

In addition, two special symbols is called quantifiers can appear in Iormulas; these are the
universal/ quantifier( ) and the existential quantiIier (3). Truth values Ior Iormulas with
quantiIiers must be described. A tuple variable t is bound iI it is quantiIied, meaning that it appears
in an (3 t) or ( t) clause; otherwise, it is Iree.
Ex: All free occurrences oI a tuple variable t in F are bound in a Iormula F` oI the Iorm
F` (3I)(F) or F ( t)(F). the tuple variable is bound to the quantiIier speciIied in F`. For
example, consider the Iormulas:
F1 : d.DNAME Research`
F2 : (3I) (d.DNUMBER t.DNO)
F3 : ( t)(d.MGRSSN 333445555`)

The tuple variable d is Iree in F1, where as it is bound to the universal quantiIier in F3.
Variable t is bound to the(3) quantiIier in F2.

The Domain Relational Calculus

There is another type oI a relational calculus called the domain relational calculus, or simply,
domain calculus. The domain calculus diIIers Irom the tuple calculus in the type oI variables
used in Iormulas: rather than having variables range over tuples, the variables range over single
values Irom domains oI attributes. To Iorm a relation oI degree n Ior a query result, we must
have n oI these domain variables one Ior each attributes. An expression oI the domain
calculus is oI the Iorm.


x1, x2...,xn , COND (x1, x2...,xn, xn1, xn2....xnm)}

(Contd....)










Where x1,x2,...xn,xn1,xn2,...,xnm are domain variables that ranges cover domains (oI
attributes) and COND is a condition or formula oI the domain relational calculus. A Iormula is
made up oI atoms. The atoms oI a Iormula are slightly diIIerent Irom those Ior the tuple calculus
and can be one oI the Iollowing

1. An atom oI Iorm R(x1,x2,...xj,), where R is the name oI a relation oI degree j and each x,,
1_i_j, is a domain variable. This atom states that a list oI values oI x1,x2,...xj~ must be a
tuple in the relation whose name is R, where xi is the value oI the ith attribute value oI the tuple.
To make a domain calculus expression more concise, we drop the commons in a list oI variable;
thus we write
(x1,x2,...xn , R(x1,x2,x3)and ..}
Instead oI
(x1,x2,...xn , R(x1,x2,x3)and ..}
2. An atom oI the Iorm xi op xj, where op is one oI the Iorm comparison operates in the
set,~,_,,_,=} and xi and xj are domain variables.
3. An atom oI the Iorm xi op xj, where op is one oI the Iorm comparison operates in the
set,~,_,,_,=} and xi and xj are domain variables, and c is a constant value.
Examples : consider the schema and go through the queries given below

otel (hotelNo, hotelName, city)
Room (roomNo, hotelNo, type, price)
Booking (hotelNo, guestNo,dateForm,, dateTo, roomNo)
Guest (guestNo, guestName, guestAddress)

(a) ist all hotels

SQL: SELECT * FROM otel;

RA:

TRC:

DRC:

(b) ist all single rooms with price below Rs.200 per night.

SQL:

RA:

TRC:

DRC: roomNo, hotelNo, type, price , (Room(roomNo, hotelNo, type, price) A type S` A price 200)}







(contd.)

Authorised By
SANTOSH BHARADWA1 REDDY
Email: helpmatlabcodes.com
Engineeringpapers.blogspot.com
More Papers and Presentations available on above site








(c) ist the names and cities of all guests

SQL: SELECT guestName, guestAddress FROM Guest

RA:

TRC:

DRC:

(c) ist the price and types of all rooms at the Grosvenor Hotel

SQL:

RA:

TRC: R.price,R.type , Room(R) A (3) (otel() A (R.hotelNo .hotelNo)A(.hotelNmae Grosvenor otel`))}

DRC: price, type , (3rooNo, hotelNo1, hotelName,city)A (hotelNO hotelNO1)A(hotelName Grosvenor otel`))}

(e) ist all guests currently staying at the Grosvenor Hotel

SQL : SELECT * FROM Guest
WERE GUESTnO (select GuestNo Irom Booking
WERE date FROMCURRENTDATE AND
hotelNo
(SELECT hotelNo FROM otel
WERE hotelName Grosvenor`));

RA: Guest 3 guestNo (o date Irom_ `01-01-02` ` date To _`01-01-02;(
Booking 3 hotelno (ohotel name`Grosvenor`otel`(otel))))
(substitute ,01-01-02` Ior today`s date).

TRC: G , Guest(G) A (3B)( 3) (Booking(B) A otel() A (B.dateFrom _ `01-01-02`) A
(B.dateTo _ `01-01-02`) A (B.guestNo G.guestNo) A
(B.hotelNo .hotelNo) A (.hotelName `Grosvenor otel`)))}









(contd.)




















DRC : guestNo, guestName, guestAddress ,(3hotelNo, guestNo1,dateFrom, dateTo,

hotelNo1,hotelName,city)

(Guest(guestNo, guestName, guestAddress) A
Booking(hotelNo, guestNo1, dateFrom, dateTo) A
otel(hotelNo1,hotelName, city) A (guestNo guestNo1) A
dateFrom_ `01-01-02` A dateTo _ `01-01-02`) A
(hotelNo hotelNo1) A (hotelNmae Grosvenor otel`))}

(I) ist the guest details (guestNo, guestName, and guestAddress) of all guests staying at the
Grosvenor Hotel

SQL: SELECT guestNo , guestName, and guestAddress FROM Guest
WERE GuestNo
(SELECT guestNo FROM Booking
WERE dateFrom CURRENTDATE AND
hotelNo
(SELECT hotelNo FROM otel
WERE hotelName Grosvenor otel));
RA:

TRC: G , Guest(G) A((3B)(3)(Booking(B) A otel() A (B.guestNo G.guestNo) A

(B.hotelNo .hotelNo) A (.hotelNmae Grosvenor otel`) A

(B.dateFrom _ `01-01-02` A B.dateTo _ 01-01-02`)))}


DRC: guestNo, guestName, guestaddress , ((3hNo, gNo, dram, dTo, rNo, hNo1, hName,city)
(Guest(guestNo, guestName, guestAddress)A
Booking(hNo, gNo, dFom,, dTo, rNo) A otel(hNo1,
hName, city)A
(guestNo gNo) A (hNo hNo1) A (hNmae Grosvenor otel`) A
(dFrom _ `01-01-02` A dTo _ 01-01-02`)))}


(contd..)





















(g) ist the details of all rooms at the Grosvenor Hotel, including the name of the guest staying
in the room, if the room is occupied


SQL : SELECT * FROM Room r LEFT OIN
(SELECT g.guestName, h.hotelNo, b.roomNo FROM Guest g,
Booking b, otel h
WERE g.guestNo b.guestNo AND b.hotelNo h.hotelNo AND
hotelNmae Grosvenor otel` AND
dateFrom CURRENTDATE AND
dateTo~ CURRENTDATE) AS XXX
ON r.hotelNo XXX.hotelNo AND r.roomNo XXX.roomNo;

RA :


TRC : R, G.guestName , Room(R) A (3) (otel() A

(R.hotelNo .hotelNo)A(.hotelNmae Grosvenor otel`))} V

(Guest(G) A((3B)(3)(Booking(B) A otel() A

(G.guestNo B.guestNo) A (B.hotelNo .hotelNo) A

(.hotelNmae grosvenor otel`) A

(B.dateFrom _ `01-01-02` A B.dateTo _ 01-01-02`)))}

DRC: roomNo, hotelNo, type, price, guestName ,

(3hNo, hName, city, hNo1, gNo1, dFrom, dTo, rNo)

(Room(roomNo, hotelNo, type, price) A otel(hNo1, hNmae, city) A

(hotelNo hNo1) A (hNmae Grosvenor otel`)) V

(Guest(guestNo, guestName, guestAddress) A otel(hNo, hName, city) A

Booking(hNo1, gNo1, dFrom, dTo, rNo) A


(guestNo gNo1) A (hNo1 hNo) A (hNmae Grosvenor otel`) A

(dFrom _ `01-01-02` A dTo _ 01-01-02`)))}








(contd...)








TOPIC-5 : TRANCATIONS AND CONC&RRENCY CONTROL

TRANCATIONS

O A transaction T is a logical unit oI database processing that includes one or more database
access operations
- Embedded with in application program
- SpeciIied interactively (e.g., via SQL)

ACID Properties

Consistency:
Execution oI a transaction in isolation ( that is, with no other transaction executing concurrently)
preserves the consistency oI the database. This is typically the responsibility oI the application
programmer who codes the transactions.

Atomicity:
Either all operations oI the transaction are reIlected property in database. Or none are. Clearly lack
oI atomicity will lead to inconsistency in the database.

Isolation:
When multiple transactions execute concurrently, it should be the case that Ior every pair oI
transactions Ti and Tj , it appears to Ti that either Tj Iinished execution beIore Ti started, or Tj
started execution aIter Ti Iinished. Thus each transaction is unaware oI other transaction executing
concurrently with it. The user view oI a transaction system requires the isolation property, and the
property that concurrent schedules take the system Irom one consistent state to another. These
requirements are satisIied by ensuring that only serializable schedules oI individually consistency
preserving transactions are allowed.

Durability:
AIter a transaction completes successIully, the changes it has made to the database persist, even iI
there are system Iailures.

Transaction States

- BEGINTRANSACTION: marks start oI transaction.
- READ or WRITE: two possible operations on the data.

- ENDTRANSACTION: marks the end oI the read or write operations; start checking
whether everything went according to plan.
- COMITTRANSACTION: signals successIul end oI transaction; changes can be
'committed to DB.
- READ or WRITE: two possible operations on the data.
- ENDTRANSACTION: marks the end oI the read or write operations; start checking
whether everything went according to plan.
- ROLLBACK(or ABORT): signals successIul end oI transaction; changes applied to DB
must be undone.












BEGIN
TRANSACTION


Schedule

When transaction are executing concurrently in an interleaved Iashion, then the order oI execution oI
operations Irom the various transactions is known as Schedule.
Types of schedules: Serial. Non serial, recoverable and non recoverable schedules

Serial schedule A schedule where the operations oI each transaction are executed consecutively
without any interleaved operations Irom other transactions.
Nonserial schedule: A schedule where the operations Irom a set oI concurrent transactions are
interleaved.

Serializability

A schedule s` oI n` transactions is Serializable iI it is equivalent to some serial schedule
oI the same n` transactions , i.e iI interleaved schedule produces the same result as so that oI the
serial schedule, then the interleaved schedule is said to be serializable.

For two schedules to be equivalent, the operations applied to each data item aIIected by the
schedules should be applied to that item in both schedules in the same order. There are two types oI
equivalences they are conIlict equivalence and view equivalence and they lead to
(a) conflict serializability (b) view serializability.

Active
Terminated Failed
Partially
committed
Committed

ConIlict serializibility
O Schedule s is conIlict serializable iI it is conIlict equivalent to some serial schedule S
- can recorder the non conflicting operations to improve eIIiciency
O Non-conIlicting operations:
-Reads and writes Irom same transaction
-Reads Irom diIIerent transaction
-Reads and writes Irom diIIerent transactions on diIIerent data items
O ConIlicting operations:

- Reads and writes Irom diIIerent transactions on same data item











View Serializability

Consider two schedules S and S`, they are said to be view equivalent iI the Iollowing conditions are
met.
(1) For each data item Q iI transaction Ti reads the initial value oI Q n schedules, then
transaction T1 in schedule S` must also read the initial value oI Q.
(2) For each data item Q iI transaction T1 executes read(Q) in schedules S and that value
was produced by Tj(iI any), then then transaction Ti must in scheduleS1, also read the
value oI Q that was produced by transaction Tj.
(3) For each data item Q, the transaction (iI nay) that perIorms the Iinal write (Q) operation
is schedule S`
Consider 1 and 2, ensure that each transaction reads the same values in both schedules and thereIore
perIorm the same computation. Condition 3 ensures that both schedules result in the same Iinal
system state. The concept oI view equivalence leads to the concept oI view serializability.

O Test Ior Serializability
O Consider a directed graph, precedence graph, G (V,E)
- V : set oI all transactions participating in schedule
- E : set oI edges Ti Tj Ior which one oI the Iollowing holds.
O Ti executes a writeitem(X) beIore Tj executes readitem(X)
O Ti executes a readitem(X) beIore Tj executes writeitem(X)
O Ti executes a writeitem(X) beIore Tj executes writeitem(X)
O An edge Ti Tj means that in any serial schedule equivalent to S, Ti must come beIore Tj
O II G has a cycle, than S is not conIlict serailizable
O II not, use topological sort to obtain serializable schedule(linear order constraint with
precedence order oI graph)
Concurrency control Protocols

Two phase locking protocol

O Basic 2PL: Transactions is said to Iollow the two phase locking protocol iI all locking
operations precede the Iirst unlock operation
- Expanding(growing) Iirst phase
- Shrinking second phase
O During the shrinking phase no new locks can be acquired!
- Downgrading ok

- upgrading ok
O Conservative 2PL (state) 2PL: Lock all items needed BEFORE execution begins by
predeclaring its read and write set.
- II any oI the items in read or write set is already locked( by other transactions),
transaction waits (does not any locks)
- Deadlock Iree but not very realistic















O Strict 2PL: Transaction does not release its write locks until AFTER it aborts/commits
- Not deadlock Iree but guarantees resolvable schedule( strict schedule: transaction neither
read/write X until last transaction that wrote X has committed/aborted)
- Most popular variations oI 2PL

O Rigorous 2PL: No lock released until aIter abort/commit
- transaction is in its expanding phase until it ends

Graph based protocols

The simplest graph based protocols is tree locking protocol which is used to employ exclusive locks
and when the database is in the Iorm oI a tree oI database items. In the tree locking protocol, each
transaction Tj can lock a data item at most once and must observe the Iollowing rules.


(a) All locks are exclusive locks.
(b) The Iirst lock by T1 can be any data item including the root node.
(c) Ti can look a data item Q only iI T1 currently locks I Q
(d) Data items may be unlocked at any time.
(e) Ti cannot subsequently lock a data item that has been locked and unlocked by Tj
A schedule with a set oI transactions, that uses the tree locking protocol can be shown to be
serializable. The transactions need not be two phases

Advantage of tree locking control:

a. compared to the two phase locking protocol, unlocking oI the data item is earlier. So it
needs to the shorter waiting times and increase in concurrency.

Disadvantages of tree locking control:
a. A transaction may have to lock data items that it does not access, because to access
descendants we have to lock its parent also. So the number oI locks and associated
locking overhead is high.

Timestamp based protocols


The use oI locks combined with two phase locking protocol allows us guanrantee serializability oI
schedules. The order oI transaction in the equivalence serial schedule is based on the order in which
executing transaction lock the items they required. II transaction needs an item that is already locked
it may be Iorced to wait until the item is released. A diIIerent approach that guarantees serializable
involves using transaction timestamps to other transaction execution Ior an equivalence serial
schedule.

Time Stamps

A timestamp is a unique identiIier created by the DBMS to identiIy a transaction.
Timestamp values are assigned in the order in which the transactions are submitted to the system. So
a timestamp is considered as the transaction start time. With each transaction Ti in the system , a
unique timestamp is assigned and it is denoted by TS(Ti). When a new transaction Tj enters the
system, then TS(Ti)TS(Tj), this is known as timestamp ordering scheme. To implement this
scheme, each data item (Q) is associated with two timestamp values.







(1) ~W - timestamp(Q) denotes the largest timestamp oI any transaction that executed
write(Q) successIully.
(2) ~R - timestamp(Q) denotes the largest timestamp oI any transaction that executed
read(Q) successIully

These timestamps are updated whenever a new read (Q) or write (Q) instruction is executed.


Timestamp ordering protocol

Timestamp ordering protocol ensures that any conIlicting read and write operations are executed in
timestamp order. This protocol operation is as Iollows.

a. suppose transaction Ti issues read(Q)
a) II TS(Ti) W timestamp(Q) then Ti needs to read a value oI Q that was already
overwritten. ence, the read operation is rejected and Ti is rolled back
b) II TS(Ti) W timestamp(Q) then the read operation is executed and R-timestamp (Q)
is set to the maximum oI R-timestamp(Q) and TS(Ti).
b. Transaction issue a write(X)
a) II TS(T) read timestamp(X), this means that a younger transaction is already using
the current value oI the item and it would be an error to update it now. This occurs
when a transaction is late in doing a write and younger transaction has already read the
old value
b) II TS(T) read timestamp(X), this means that a younger transaction T asks to write
any item(X) whose value has already been written by a younger transaction. i.e, T is
attempting to write an absolute value oI data item X. So T should be rolled back and
restarted using a later timestamp.
c) Otherwise the write operation can proceed we set write- timestamp(X) TS(Ti)

This scheme is called basic timestamp ordering and guarantees that transaction are conIlict
serializable and the results are equivalent to a serial schedule.

Advantages of timestamp ordering protocol


1) ConIlicting operations are processed in timestamp order and thereIore it ensures conIlict
serializability.
2) Since timestamp do not use locks, deadlocks cannot occur

Disadvantages of timestamp ordering protocol

1) Starvation may occur iI a transaction is continually aborted and restarted.
2) It does not ensures recoverable schedules.

Thoma`s write rule.

A modiIication to the basic timestamp ordering protocol is that it relaxes conIlict serializable and
provides greater concurrency by rejecting absolute write operation. the extension is known as
Thoma`s write rule.










Suppose transaction Ti issues read(Q) no change, same as time stamp ordering protocol


II transaction issues write(X)

a) II TS(T) read timestamp(X), this means that a younger transaction is already
using the current value oI the item and it would be an error to update it now. This
occurs when a transaction is late in doing a write and younger transaction is late in
doing a write and younger transaction has already read the old value.

b) II TS(Ti)write-timestamp(X). This means that a younger transaction has already
update the value oI the item and the value that the order oI the item and the values
that the older transaction is writing must be based on an absolute value oI the item.
In this case the writing operation can saIely be ignored. This is some times known
as the ignore absolute write rule and allows greater concurrency.

Multiple granularity


In all concurrency control schemes, we have used each individual data item as the unit on which
synchronization is perIormed. owever, it would be advantageous to group several
data items and to treat them as one individual unit.

Examples, iI a transaction T1 needs to access the entire database, it uses a locking protocol. Then Ti
must lock each item in the database, so it is time consuming process. ence it
would be better iI Ti issue a single lock the entire database. On the other hand iI
transaction T1 needs to access only a Iew data items, it should not be required to
lock the entire database.

A data item can be one oI the Iollowing:


1. A data base record

2. Field value oI database record
3. A disk block
4. whole Iile
5. whole database

The size oI the database item is oIten called the data item granularity. Find granularity reIers to
overall ite size, where as coarse granularity reIers to large item size. The best item size depends on
the type oI transaction.

ierarchy oI data granularity, where the small granularity are nested with in larger once. Can be
represented graphically a tree. In the tree each node represents independent data item, non leaI node
oI multiple granularity tree represents the data associated with its descendents














The highest level represents the entire data base, then Iiles, pages, records and Iields. ence we can
use shared and exclusive lock when a transaction locks a node, all the descendants oI the node in the
same lock node. To make multiple granularity level, locking practical, additional types oI locks
called intention locks are needed. The idea behind intention locks is Ior a transaction to indicate,
along the path Irom the root to the desired node. What type oI lock it will require Irom one oI the
nodes decadence

There are three types oI intention locks. They are

1. Intention shared(IS) to indicate that a shared lock will requested on some descendent
node
2. Intention Exclusive(IX) to indicate that a exclusive lock will be requested on some
descendant node.
DB

3. Shared Intention Exclusive(SIX) to indicate that the current node is locked in shared
mode but an exclusive lock will be requested.

Compatability Matrix for multiple granularity locking
IS IX S SIX X
IS T T T T F
IX T T F F F
S T F T F F
SIX T F F F F
X F F F F F


Multi version scheme

In multi version database system each write database operation on data item say Q. creates a new
version oI Q. when a read (Q) operation is issued. The system selects one oI the Q oI Q to read.
The concurrency control scheme must ensure that the selection oI the version to be read is done in
a manner that ensyres serializabillity.













Authorised By
SANTOSH BHARADWA1 REDDY
Email: helpmatlabcodes.com
Engineeringpapers.blogspot.com
More Papers and Presentations available on above site





























There are two multi version schemes
1. Multi version timestamp ordering.
2. Multi version Two phase locking.

Multi version timestamp ordering

In this technique, several version Q1 Q2 . Qk oI each data item Q are kept by the system. For each
version the value oI the version Qk and the Iollowing two timestamps are kept.

1) W- timestamp(Qk) is the timestamp oI the transaction that created version k.
2) R - timestamp(Qk) is the ;largest timestamp oI any transaction that successIully
read version Qk.

The scheme operates as Iollows when transaction Ti issues a read(Q) or write(Q) operation. let Qk
denote the version oI Q whose write timestamp less than or equal to TS(Ti).


1) It transaction issues a read(Q), then the value returned is the content oI version
Qk.
2) It transaction Ti issues a write(Q), and iI TS(Tj) R-timestamp(Qk.), then
transactionTi is rolled back. Otherwise iI TS(Ti) W timestamp(Qk) the
contents oI Qk are over written, otherwise a new version oI Q is created.

Advantages

1) The read request never Iails and is never made to wait.

Disadvantages

1) It requires more storage to maintain multiple versions oI the data item
2) Reading oI a data item also requires the update oI the R timestamp Iield,
resulting in two potential disk access.
3) ConIlicts between transactions are resolved through roll backs, rather than
through waits. This may be expensive.

Multi version Two Phase Locking


Multi version Two Phase Locking protocol attempts to combine the advantages oI multi version
concurrency control with the advantages oI two phase locking. In the standard locking scheme, once
a transactions obtain a write lock on an item, no other transactions can access that item. So here it
allows other transactions T` to read an item X while a single transaction T holds a write lock on X.
This is accomplished by allowing two versions oI each item oI X.

When an update transaction reads an item it gets shared lock on the item and reads the latest version
oI that item. When an update transactions wants to write an item, it Iirst gets an exclusive lock on the
item and then creates a new version oI the data item. The write is perIormed on the new versions the
timestamp oI the new version is initially set to a value .











Advantages:

1) Reads can proceed concurrently with a write operation but it is not permitted in standard
two phase locking.
2) It avoids cascading aborts, since transactions are only allowed to read the version that
was written by a committed transaction.

Disadvantages

1) It requires more storage to maintain multiple versions oI the data item
2) Dead locks may occur.

Objective type questions

1. Which oI the Iollowing are true statements
I. Every conIlict serializable schedule is view serializable schedule
II. A schedule has only constrained write operations and the schedule is view serializable then
it is also conIlict serializable.
III. Every view serializable is conIlict serializable
IV. A schedule may be conIlict serializable but not view serializable.
a) I only b) I& II c) III & IV d) All the above

2. What are the possible violations iI an application program uses isolation level 'read
uncommitted
a) dirty read problem b) non repeatable read problem c) phantom phenomenon
d) All the above

3. What are the possible violations iI an application program uses isolation level 'Repeatable read?
a) dirty read problem b) non repeatable read problem
c) phantom phenomenon d) none oI the above

4. A schedule S is having only committed read operation only a value written by transaction T`
cannot be over written other transaction until T` either aborts or commits, then the schedule is
called as
a) cascade less schedule b) serializable schedule
c) strict schedule d) recoverable schedule

5. what is phantom phenomenon?
a) A transaction retrieves a collection oI objects but sees same results
b) A transaction retrieves a collection oI objects but diIIerent same results
c) Transaction T1 waits Ior T2 and T2 waits Ior T1
d) This problem arises when the transaction has not locked all the objects


















6. In a schedule, when dirty read problem occur?
a)The transaction reads an object that has been modiIied by another committed
transaction
b) The transaction reads an object that has been modiIied by a rolled back transaction
c) The transaction reads an object that has been modiIied by another not yet committed
transaction
d) Two transactions are reading the same object
7. Which oI the Iollowing is a true statement.
I. Every strict schedule is cascade less schedule recoverable schedule
II. Every cascade schedule is recoverable schedule
III. Every cascading roll back schedule is recoverable schedule
IV Every cascading roll back schedule is strict schedule
V. Every recoverable schedule is cascading rollback schedule
a) all the above b) I,II and IV only c) II,III,IV and IV only d) I,II and III only

8. The schedule S : T1 : R(x); T3 : R(z); T3 : W(z); T2 : R(y); T3 : R(x);
T1 : R(y); T2 : W(y); T3 : W(x); T2 : W(z); T1 : W(x);
The above schedule is having the below problem.
a) Read write conIlict b) write write conIlict
c) Unrepeatable read problem d) All oI the above e) None oI the above

9. Which oI the Iollowing ensures atomicity property?
a) Transaction Manager b) user
c) concurrency control subsystem d) Recovery Manager

10. Which oI the Iollowing ensures consistency preservation ?
a) Transaction Manager b) user
c) concurrency control subsystem d) Recovery Manager

11. In a schedule S, two transaction T1 and T2 are executing concurrently. The execution order oI
those transactions is given below. Are there any problems with the concurrency?


a) Phantom phenomenon

b) unrepeatable read problem

c) lost update problem

d) uncommitted read problem


Note: R - read, w - write,
Subscript transaction number











T1 T2
Read A
A A 1000 Read B
B B 1000
Read B
B B500
Read A
Write B A A500
Write A
Write B
Write A Commit
Commit




12. Consider a schedule S R1(A); R2(B); W2(B); R3(A); W3(A); R1(B); R3(B); R2(A); W2(A).
Is the above given schedule view serializable or conIlict serializable
a) view serializable b)conIlict serializable c) both (a)&(b) b) not serializable

13. Consider a schedule S: R1(B); R3(C); R1(A); W2(A); W1(A); W2(B); W3(A); W1(B);
W3(B); W3(C) In the above schedule view serializable or conIlict serializable
a) view serializable b)conIlict serializable c) both (a)&(b) b) not serializable

14. In a schedule S, three transaction T1.T2 and T3 are executing concurrently. The schedule is
given below. The given schedule is conIlict equivalent to which oI the given serial schedules


















a) T1 T2 T3 a) T3 T2 T1 a) T1 T3 T2 d) None oI the above
Note: R - read, W - write, subscript represents transaction number

15. A schedule S: R2(A); R3(B); W2(A); R1(A); W3(A); R2(B); W1(A); W2(B); R2(C); W2(C);
R1(C);W1(C); W3(B).
Is the above schedule is conIlict serializable ? II Yes. The given schedule is equivalent to which oI
the Iollowing serial schedule?
a) T1 T2 T3 a) T3 T2 T1 a) T1 T3 T2 d) None oI the above

16. A schedule S: R1(A); R2(B); R3(C); W3(C); W2(B); W1(A); is conIlict equivalent to which oI
the below given serial schedules
a) T1 T2 T3 a) T3 T2 T1 a) T1 T3 T2 d) None oI the above

17. In a schedule S, 4 transactions are executing concurrently, each transaction is reading two data
items and updating the both and the data items are not common between any two transactions. The
schedule is equivalent to ----- number oI serial schedules.

a) schedule is required b) 4 c) 8 d)16 e) 24









T1 T2 T3
Read Y
Y Y 100 Read Z
Write Y Z Z 100 Read X
Write Z X X - 100
Write X
Read X
X X100 Read Y
Write X Y Y-100 Read Z
Write Y Z Z - 100
Write Z
Read Z
Z Z100 Read X
write Z X Z 100 Read Y
Write B




18. A schedule S having 3 transactions and each transaction is reading two data items and writing the
same, the data items are distinct data items. Along with these data items, each transaction is
having a blind writeA` operation.. With the above given inIormation is it possible to decide
whether the given schedule is view serializable or conIlict serializable ?

a) can`t say. detailed schedule is required
b) the schedule is conIlict serializable and conIlict equivalent to one serial schedule
c) the schedule in view serializable and view equivalent to two serial schedules
d) B and C alternatives are true.

19. A schedule S: R1 (A); W1(A); R2(A); W2(B); commit2: W1(C); Rollback1. The above
schedule is -----------
a) recoverable schedule b) cascading rollback schedule
c) non-recoverable schedule d) strict schedule

20. Which oI the Iollowing is conIlict serializable ?
S1; R1 (X); R3 (X); W1 (X); R2 (X); W3(X); S2; R3(X); R2(X); W3(X); R1 (X); W1 (X);
a) S1 is serializable but S2 is not
b) both are serializable
c) both are not serializable
d) S1 is not serializable but S2 is serializable

21. A schedule is having two transactions T1 and T2 executing concurrently and the schedules are
given below. Which oI the schedules results in 'write read conIlict with the actions oI
transaction T1 and T2 on object x and y.
a) T2 : R(X) ; T2 : R(Y) ; T1 : R(X) ; T2 : R(Y) ; T1 : W(X) ;
b) T2 : R(X) ; T2 : R(Y) ; T2 : W(X) ; T1 : R(X) ;
c) T2 : R(X) ; T2 : W(X) ; T1 : R(Y) ; T1 : W(Y) ; T2 : R(z) ; T1 : R(z) ;
d) None oI the above

22. Consider a schedule with three transaction, T1,T2 and T3 executed concurrently. The schedule
is given below. Find out the category oI the schedule (determine the strictest recoverably
condition the schedules satisIies)
S: R1 (x); R2(z); R1(z); R3(x); R3(y); W1(x); C1;W3(y);C3; R2(y); W2(z); W2(y);C2
a) recoverable schedule b) cascading rollback schedule
c) strict schedule d) non-recoverable schedule

23. Consider a schedule with three transaction, T1,T2 and T3 executed concurrently. The schedule
is given below. Find out the category oI the schedule (determine the strictest recoverably
condition the schedules satisIies)
S: R1 (x); R2(z); R1(z); R3(x); R3(y); W1(x); W3(y); R2(y); W2(z); W2(y);C1;C2;C3
a) recoverable schedule b) cascading rollback schedule
c) strict schedule d) non-recoverable schedule

24. Consider a schedule with three transaction, T1,T2 and T3 executed concurrently. The schedule
is given below. Find out the category oI the schedule (determine the strictest recoverably
condition the schedules satisIies)
S: R1 (x); R2(z); R3(x); R1(z); R2(y); R3(y); W1(x); C1;W2(z); W3(y); W2(y);C3;C2
a) recoverable schedule b) cascading rollback schedule
c) strict schedule d) non-recoverable schedule









25. For the given schedule S, Iind out the conIlict equivalent schedule.
S: r1(x); r2(z); r1(z); r3(x); r3(y); w1(x);w3(y); r2(y);w2(z); w2(y);
a) T1 T2 T3 a) T2 T1 T3 a) T3 T1 T2 d) Not conIlict serializable

26. For the given schedule S, Iind out the conIlict equivalent schedule.
S: r1(x); r2(z); r3(x); r1(z); r3(y); w1(x);w3(y); r2(y);w2(z); w2(y);
a) T1 T2 T3 a) T2 T1 T3 a) T3 T1 T2 d) Not conIlict serializable


28. In the above schedule S1, S2 & S3 which oI the schedule is suIIering Irom last update problem
or write write conIlict

a) S1 b) S2 c) S3 d) all the above e) none oI the above

29. Aries recovery algorithm is designed to work with approach.

a) steal Force approach b) steal No Iorce approach
c) No - steal Iorce approach d) No steal No Iorce approach

30. In a schedule S having Iour transactions executed concurrently. The order oI their operations is
given below. Find out whether the given schedule is serializable or not?

a) conIlict serializable

b) view serializable
c) both a and b
d) not serializable











31. Which oI the Iollowing protocols may violate serializability oI schedules ?

a) static (or conservative) two phase locking protocol
b) static two phase locking protocol
c) optimize concurrency control protocol
d) none











T1 T2 T3 T4
R(x)






W(x)




commit

R(y)
W(x)





W(y)




Commit



W(z)

R(x)
W(y)


W(x)




commit




R(z)





R(x)
W(y)



commit




32. In multiple granularity protocol, a transaction is locking an object in exclusive mode. At the
same object, what are the locks permitted by other transactions?

a) Intension shared lock b) Intention - exclusive lock
c) Shared intension exclusive lock d) none

33. In multiple granularity protocol at a particular data item , transaction T1 is holding shared
intension exclusive lock. At the same data item, transaction T2 is allowed to request which oI the
Iollowing locks?

a) Intension exclusive b) Intension shared lock
c) Shared lock d) Shared intension exclusive lock

34. Which oI the Iollowing statement is Ialse?

a) strict 2PL protocol is not deadlock Iree and ensures cascade less schedules and strict schedules.
b) basic time stamp protocol is a deadlock Iree and allows cascading rollback schedules
c) conservative 2PL protocol is a deadlock Iree and ensures cascade less schedules
d) rigorous 2PL protocol ensures strict schedules and there is a chance oI deadlock

35. II a transaction obtains an exclusive lock beIore writing and hold until end oI transaction.
Which oI the Iollowing schedules are possible.

a) recoverable schedule b) cascade less schedule c) strict schedule d) all oI the above

36. Consider the Iollowing tree Ior data items (A, B, C, D, E, F, G) check whether the given
schedule S is serializable or not?

int: use tree protocol


















a) Serializable b) Not serializable







T1 T2 T3
Lock A
Lock B
Lock D
Unlock B
Lock B
Lock E
Un Lock D
Lock C Lock F
Un Lock A
Unlock C Lock G
Unlock E
Lock E
Unlock F
Unlock B
Unlock G
Unlock - E

A
C
G F
E D
B




37. The rules Ior two phase locking protocol are

a) each transaction must get shared lock on an object beIore reading it
b) once a transaction releases a lock, it cannot acquire any new lock
c) each transaction must get exclusive lock beIore updating it
d) all oI the above

38. What is diIIerence between timestamps assigned Ior deadlock prevention in 2PL protocol and
timestamps assigned Ior concurrent control in timestamp protocol?

a) when transaction is aborted and restarted, a new larger timestamp will be given Ior concurrency
control and same timestamp will be given Ior deadlock prevention.
b) when the transaction is aborted and restarted, same timestamp will be given Ior concurrency
control and a new larger timestamp will be given Ior deadlock prevention
c) when the transaction is aborted and restarted same timestamp will be given Ior both concurrency
control and deadlock prevention
d) when the transaction is aborted and restarted, a new timestamp will be given Ior concurrency
control and deadlock prevention.

39. Consider the database that is organized in terms oI database object D` , and it contains two Iiles
(F1 and F2) each oI which contains 1000 pages(P1...P1000) and (P1001..P2000) respectively.
Each page contains 100 records. When multiple granularity protocol is used, the operation
'Read all (records on all) pages in File1 causes note (TS-intestion shared lock, S-shared lock)

a) IS on D & F1 b) IS on F1 & S on D c) IS on D & S on F1 d) S on D & F

40. Which oI the Iollowing protocols always ensures recoverable schedules?

a) Timestamp ordering protocol b) Timestamp protocol with Thomas write rule
c) Strict timestamp protocol d) all oI the above

1.b 2.d 3.c 4.c 5.b 6.c 7.d 8.b 9.d 10.b
11.c 12.d 13.d 14.a 15.d 16.d 17.e 18.d 19.c 20.d
21.b 22.c 23.a 24.b 25.c 26.d 27.a 28.c 29.b 30.b
31.d 32.d 33.b 34.c 35.b 36.a 37.b 38.a 39.c 40.c

Problems:

1. Which are the Iollowing schedules is (conIlict) serializable Ior each serializable schedule,
determine the equivalent serial schedules.

a) r1(x); r3(x); w1(x); r2(x); w2(x);
b) r1(x); r3(x); w3(x); w1(x); r2(x)
c) r3(x); r2(x); w3(x); r1(x); w1(x)
d) r3(x)l r2(x); r1(x); w3(x); w1(x)














2. Consider a database with objects x and y and assume that there are two transactions T1 and T2.
Transactions T1 reads objects x and y and then writes objects x. Transactions T2 reads objects x and
y and then writes objects x and y

a) give actions oI T1 and T2 on x and y that results WR conIlict
b) give actions oI T1 and T2 on x and y that results RW conIlict
c) give actions oI T1 and T2 on x and y that results WW conIlict

3. Consider the Iollowing schedules serializable, conIlict seriliazable, view serializable,
recoverable avoids cascading aborts and strict. For each oI the Iollowing schedules, state which oI
the above classes it belongs to

a) T1 : R(x) , T2 : R(x), T1: W(x), T2 : W(x)
b) T1 : W(x) , T2 : R(y), T1: R(y), T2 : R(x)
c) T1 : R(x) , T2 : R(y), T3: W(x), T2 : R(x)
d) T1 : R(x) , T1 : R(y), T1: W(x), T2 : R(y), T3: W(y), T1: W(x), T2: R(y),
e) T1 : R(x) , T2 : W(x), T1: W(x), T2 : Abort, T1: commit
I) T1 : R(x) , T2 : W(x), T1: W(x), T2 : C, T1: C
g) T1 : W(x) , T2 : R(x), T1: W(x), T2 : Abort, T1: commit
h) T1 : W(x) , T2 : R(x), T1: W(x), T2 : Abort, T1: commit
i) T1 : W(x) , T2 : R(x), T1: W(x), T2 : commit, T1: commit)
j) T2 : R(x) , T3 : W(x), T3: commit, T1 : W(y), T1 : commit,T2 : R(y), T2 : W(z), T2 : Commit
k) T1 : R(x) , T2 : W(x), T2: C, T1: W(x), T1 : C, T3 :R(x), T3: C
l) T1 : R(x) , T2 : W(x), T1: W(x), T3 : R(x), T1 : C, T2 : C, T3 : C

4. For each oI the Iollowing state whether the schedule is serializable (conIlict), view serializable,
recoverable and whether it avoids cascading aborts.

a) R1(x) : R2(x): W1(x) : W2 (x), C1, C2
b) R1(x) : R2(y): W3(x) : r2 (x), C1, C2
c) R1(x) : W2(y) : W1(x), a2, C1
d) W1(x) : R2(x): W1(x) , C2, a1
e) R1(x) : W2(x): W1(x) : R3(x), C1, C2,C3
I) R1(x) : R1(y): W1(x) : R2 (y), W3(y), W1(x), R2(y)
g) Draw the procedural graph Ior W3(A), R1(A): W1(Z) : R2 (B), W2(Y), W3(B), C1, C2, C3)
h) Draw the procedural graph Ior R1(A),W1(A) : R2 (A), R2(B), C2,R1(B), W1(B), C1
i) Consider the procedure graph, is the corresponding schedule conIlict serializable



.













.


T1
T5
T2
T3 T4
END OF TE BOOK

































Authorised By
SANTOSH BHARADWA1 REDDY
Email: helpmatlabcodes.com
Engineeringpapers.blogspot.com
More Papers and Presentations available on above site

Vous aimerez peut-être aussi