1 DBMS (WWW Gatenotes In)
1 DBMS (WWW Gatenotes In)
i
t
4
Chapter 1
ER Model and Relational Model
LEARNING OBJECTIVES
Physical schema
Entity Set
Set of entities of same type that shares the same properties.
Example: All persons, all companies etc.
a1 b1
a2 b2
Number Street House-No a3 b3
a4 b4
Figure 1 A hierarchy of composite attributes.
Street address is a composite attribute. Attributes that are Figure 3 One-to-one relationship set.
not divisible are called simple (or) atomic attributes.
One-to-many: An entity in A is associated with any number
Single-valued versus multivalued attributes: Most attributes of entities in B. But an entity in B is associated with at most
have a single value for a particular entity, such attributes are one entity in A (Figure 4).
called single-valued attribute.
b1
Example: Age is a single-valued attribute a1
b2
Multivalued attributes: An attribute can have a set of values a2 b3
for the same entity. a3 b4
Example: College degrees attribute for a person b5
Example: Name is also a multivalued attribute (Figure 2).
Figure 4 One-to-many relationship set.
Name Many-to-one: An entity in A is associated with at most one
entity in B. But an entity in B can be associated with any
First name Last name number of entities in A (Figure 5).
Middle name
a1
Figure 2 Multivalued attribute. b1
a2
Stored versus derived attributes: Two (or) more attribute a3 b2
values are related. a4 b3
a5
Example: Age can be derived from a person’s date of birth.
The age attribute is called derived attribute and is said to be Figure 5 Many-to-one relationship set.
derivable from the DOB attribute, which is called a stored
attribute. Many-to-many: An entity in A is associated with any num-
ber of entities in B. But an entity in B can be associated with
Domain: The set of permitted values for each attribute.
any number of entities in A (Figure 6).
Example: A person’s age must be in the domain {0-130}
a1 b1
a2 b2
Relationship Sets a3 b3
A relationship is an association among several entities. a4 b4
Relationship sets that involve two entity sets are binary.
Figure 6 Many-to-many relationship set.
Generally, most relationships in databases are binary.
Relationship sets may involve more than two entity sets. Example: One customer can have multiple accounts
Example: Employee of a bank may have responsibilities at Customer(c-Name) (Acc. no, Amount)
multiple braches, with different jobs at different branches, then Table 3 Example of One-to-many Relationship Set
there is a ternary relation between employee, job and branch.
Arun A-101 $3000
S 1. e 1.
The collection of all entities of a particular entity type in the Binary relation If a relationship type is between entities
database at any point in time is called an entity set. in one type and entities in another type then it is called a
binary relation, because two entity types are involved in the
Types of relations relation.
1. Unary relation. 4. Quadnary relation.
2. Binary relation. 5. N-ary relation
Customer Purchased Product
3. Ternary relation.
Relationship
The above relation indicates that customers purchased prod-
uct (or) products are purchased by customers.
Number of
Degree Quadnary relation If a relationship type is among entities
entity types
of four different types, then it is called quadnary relation.
1. Unary
2. Binary
Lecturer
3. Ternary Cardinality Optionality
1:1 Optional
N–ary 1:N Mandatory
N:1
M:N Student Register Course
Unary relation If a relationship type is between entities in a
single entity type then it is called a unary relationship type.
Department
Employee Managed-by
In the above ER-diagram, any two entities can have a
relation.
In employee entity, we will have all the employees including N-ary relation ‘N’ number of entities will participate in
‘manager’, this relation indicates, employees are managed a relation, and each entity can have a relation with all the
by manager. other entities.
Chapter 1 • ER Model and Relational Model | 4.7
E6
ER Diagrams (Figure 7 and 8)
E3
E5 Cust-street
E4
C-name L No Amount
Cust-city
Cust-id
Cardinality Ratio Customer Borrower Loan
and Participation Constraints
The cardinality ratio for a binary relationship specifies the Figure 7 ER diagram.
maximum number of relationship instances that an entity
can participate in Notations:
First name
Last
r1
e1 Middle name
d1
r2 name
e2
r3 Figure 8 ER diagram.
e3 d2
r4 → Derived attribute
e4 . → Multivalued attribute
. . .
. .
→ Weak entity
R
Many-to-many
E E Total Participation
of E2 in R1 Examples:
1. Many students are taught by many teachers.
1 N
E R E Cardinality 2. Many patients are treated by many doctors.
ratio 1: n 3. Many medications are taken by many patients.
Structural
4. Many customers buy many products.
(min, max) constraint on 5. Many books are written by many authors.
R E
participation of
E In R
Examples: Job
1. One birdfeeder is located in one place in the yard. E-name Street Assets
B-city
2. One state has one governor. E-id
City B-name
3. One yard has one address.
4. One patient has one phone number.
2. One student has one ID. Employee Works-on Branch
column names are used to help in interpreting the meaning •• Manipulative aspect: The operators available to
of the values in each row. the user for manipulating those tables, for purposes
In formal relational model terminology, a row is called a of data retrieval, these operators derive tables form
tuple, a column header is called an attribute, and the table tables, the most important operators are ‘SELECT’,
is called a relation. ‘PROJECT’ and JOIN.
Employee
Home Office
Name EId Phone Address Phone Age Salary
Fig: The attributes and tuples of a relation EMPLOYEE. The 3. Constraints that cannot be directly expressed in
earlier definition of a relation can be restated as follows: the schemas of the data model, and they must be
A relation r(R) is a mathematical relation of degree ‘n’ on expressed and enforced by the application programs are
the domains dom(A1), . . . , dom(An), which is a subset of the application-based constraints.
Cartesian product of the domains that define R:
r(R) C (dom(A1) × dom(A2) . . . × dom(An)) Inherent Constraint
The constraint that a relation cannot have duplicate tuples
Characteristics of Relations is an inherent constraint. Another important category of
There are certain characteristics that make a relation differ- constraints is data dependencies, which include ‘functional
ent from a file or a table. dependencies’ and ‘multivalued dependencies’. They are used
Ordering of tuples in a relation: A relation is defined mainly for testing the ‘goodness’ of the design of a relational
as a set of tuples. Tuples in a relation do not have any par- database and are utilized in a process called normalization.
ticular order. In a file, records are stored on disk in order.
This ordering indicates first, second, ith, and last records in Schema-based Constraints
the file. Similarly, when we display a relation as a table, the 1. Domain constraints
rows are displayed in a certain order. 2. Key constraints
Tuple ordering is not part of a relation definition, because 3. Constraints on nulls (Not null constraint)
a relation attempts to represent facts at a logical or abstract 4. Entity integrity constraints
level. Many logical orders can be specified on a relation. 5. Referential integrity constraints
Tuples in the EMPLOYEE relation could be logically 6. Unique constraint
ordered by values of Name or by EID or by Age or by some 7. Check constraint
other attribute. When a relation is implemented as a file or
displayed as a table, a particular ordering may be specified Domain constraints
on the records of the file or the rows of the table. Domain constraints specify that within each tuple, the value
of each attribute ‘X’ must be an atomic value from the
NULL in Tuples domain dom(X).
Each value in a tuple is an atomic value; that is, it is not The data types associated with domains include standard
divisible into components. Hence, composite and multi- numeric data types for integers
valued attributes are not allowed. This model is sometimes 1. Short integer
called the flat relational model. Multivalued attributes must 2. Integer
be represented by separate relations, and composite attrib- 3. Long integer
utes are represented only by their simple component attrib- 4. Real numbers
utes in the basic relational model. •• Float
NULLS are used to represent the values of attributes that •• Double-precision float
may be unknown or may not apply to tuple. For example,
5. Characters
some student tuples have null in their office phones because
6. Booleans
they do not have an office. In this case, the meaning behind
7. Fixed-length strings
NULL is not applicable. If a student has a NULL for home
8. Variable-length strings
phone, it means either he/she does not have a home phone
9. Date, time, time stamp
or he/she has one but we do not know it, in this case the
10. Money data types
meaning of NULL is ‘Unknown’.
Key constraints
Relational Model Constraints A relation is a set of tuples. All elements of a set are dis-
In a relational database, there will be many relations, and tinct; hence, all tuples in a relation must also be distinct.
the tuples in those relations are related in various ways. This means no two tuples can have the same combination of
There are many restrictions or constraints on the actual val- values for all their attributes.
ues in a database state.
1. There are other subsets of attributes of a relation
Constraints on database can generally be divided into
schema R with the property that no two tuples
three main categories as follows:
in any relation state ‘r’ of R should have the same
1. Constraints that are inherent in the data model, we combination of values of these attributes.
call them inherent model-based constraints. Suppose that we denote one subset of attributes by
2. Constraints that can be directly expressed in the ‘SK’, then for two distinct tuples t1 and t2 in a relation
schemes of the data model, by specifying them in state ‘r’ of R, we have the following constraint:
the DDL (Data Definition Language). We call these
schema-based constraints. t1[SK] = t2[SK]
Chapter 1 • ER Model and Relational Model | 4.11
2. Any such set of attributes SK is called a super key of Another constraint on attributes specifies whether null
the relation schema R. values are permitted in tuples or not. If we want some tuples
SK specifies a uniqueness constraint that no two to have a valid (or) non-null value, we need to use NOT
distinct tuples in any state r or R can have the same NULL constraint on that attribute.
value for SK.
3. Every relation has at least one default super key, the Referential and entity integrity constraint
set of all its attributes. A key, ‘K’ of a relation schema
The entity Integrity constraint states that no primary key
R is a super key of R with the additional property that
value can be null. If we have NULL values in the primary
removing any attributes ‘X’ from K leaves a set of
key column, we cannot identify some tuples in a relation.
attributes K’ that is not a super key of R any more.
1. Key constraints and entity Integrity constraints are
A key satisfies the following two constraints:
specified on individual relations
1. Two distinct tuples in any state of the relation cannot 2. Referential integrity constraint is specified between
have identical values for all the attributes in the key. relations and used to maintain the consistency among
2. A super key from which we cannot remove any tuples in the two relations.
attributes and still have the uniqueness constraints 3. Referential Integrity constraints states that a tuple in
mentioned in above condition is known as a minimal one relation that refers to another relation must refer
super key. to an existing tuple in that relation.
The first condition applies to both keys and super 4. To understand the concept of Referential Integrity,
keys. The second condition is required only for keys. first we have to understand the concept of
Example: Consider the employee relation in Page no. 9. FOREIGN KEY.
The attribute set {EId} is a key of employee because no two 5. Suppose we have two relations R1 and R2. A set of
employee tuples can have the same value for EId. attributes FK in relation schema R1 is a foreign key
Any set of attributes that include EId will form a super key. of R1 that references relation R2 if it satisfies the
1. {EId, Homephone, Name} following two rules:
2. {EId, Age, Salary} •• The attributes in FK have the same domains as the
3. {Name, EId, Address} primary key attributes PK of R2, FK will have to
refer to PK.
However, the super key {EId, Name, Age} is not a key of
•• A value of FK in a tuple t1 of the current state r1(R1)
EMPLOYEE, because removing Name or age or both from
either occurs as a value of PK for some tuple t2 in
the set leaves us with a super key. Any super key formed from
the current state r2(R2) or is null. We have t1[FK]
a single attributes is also a key. A key with multiple attributes
= t2[PK], and we say that the tuple t1 references to
must require all its attributes to have the uniqueness property.
the tuple t2. In this definition, R1 is called the ref-
A relation schema may have more than one key. In that
erencing relation and R2 is the referenced relation.
case, each of the keys is called a candidate key.
6. A foreign key can refer to its own relation. We
Example: Employee relation has three candidate keys. can diagrammatically display referential integrity
{Name, EId, Homephone} constraints by drawing a directed Arc from each foreign
One of the candidate keys is chosen as primary key of the key to the relation it references. The arrow head may
relation. point to the primary key of the referenced relation.
Example:
EMPLOYEE
FNAME LNAME EID DOB GENDER SALARY DNO
DEPARTMENT
DEPENDENT
WORKS
7. Referential integrity rule: The database must not 3. It is like checking a condition before saving data into
contain any unmatched foreign key values. a column.
If ‘B’ References ‘A’, then A must exist. Example: Create table student (RNo:INT CHECK
(Rno>0)
NOT NULL constraint Name:varchar(60)
1. NOT NULL constraint restricts a column from having Dept:varchar(4))
a NULL value. NOT NULL constraint can be applied Suppose the following tuple is inserted into student table.
to any column in a table.
1. Insert into student values <-4, ‘Bhanu’, ‘CS’>
2. We cannot give NULL values under that column
2. CHECK constraint is enforced on RNo column, the
3. NOT NULL Constraint enforces a column to contain
RNo should be greater than ‘0’, but ‘-4’ is given.
a proper value.
3. CHECK constraint is violated.
4. This constraint cannot be defined at table level.
Creating table from a table: A view is called a derived table
Example: CREATE TABLE (or) virtual table, because the data stored in views is taken
student(RNo:INT Name:varchar(70) NOT NULL age:INT) from already existing tables.
Suppose a row is inserted into the following table, A view can also be defined as a logical subset of data
Insert into student values <11, NULL, 20> from one or more tables.
In the schema, we enforced NOT NULL constraint on Name Syntax:
column, means Name cannot have NULL value, when the CREATE view view-name As
above insert command is executed, the system gives, NOT SELECT column-names
NULL constraint violation. FROM table-name
WHERE condition
UNIQUE constraint
Example: Consider the following table “sales”.
The column on which UNIQUE constraint is enforced
should not have any duplicate values. Sales
Order Previous
1. UNIQUE constraint can be enforced on any column
Order-Id Name Balance Customer
except the primary key column.
21 Order 3 3000 Ana
2. By default primary key column will not accept any
22 Order 4 1000 Adam
duplicate values that are handled by key constraint.
23 Order 5 3000 Brat
3. UNIQUE constraint can be applied at column level or
table level. 24 Order 6 2000 John
25 Order 7 2000 Ana
Example: CREATE TABLE 26 Order 8 4000 Ana
student (RNo:INT Name:varchar(60) Grade:CHAR(1))
Assume that the table contains following tuples Query to create a view:
CREATE view sales-view As
Student
SELECT *
R no. Name Grade
FROM Sales
11 Sita B
WHERE customer = ‘Ana’
12 Anu A
13 Bala A 1. The data fetched from select statement will be stored
Suppose the following tuple is inserted into the student table. in an object called ‘sales-view’.
2. To display the contents stored in view, execute the
1. Insert into student values <14, ‘Anu’, ‘B’> following statement.
2. UNIQUE constraint is enforced on Name column, in
SELECT *
the student table we have ‘Anu’, and again the new
FROM Sales-view
tuple contains name ‘Anu’, this Insert command
violates the UNIQUE constraint. Removal of specific rows:
Consider the following SQL query:
CHECK constraint Delete *
This constraint is used to restrict a value of a column FROM Sales
between a range. The above query will delete all the tuples from sales.
1. When a value is inserted into particular column, To remove specific rows, we have to specify the condi-
before storing that, a check will be performed to see tion in WHERE clause.
whether the values lie within the specified range. Consider the table “sales” given in the above example.
2. If the value entered is out of range, it will not accept Remove the rows from sales table whose previous bal-
and violation happens. ance is 3000.
Chapter 1 • ER Model and Relational Model | 4.13
We can achieve this effect by extending the foreign key as In general, CREATE TRIGGER specifies, among other
indicated below: things, an event, a condition, and an action.
The event is an operation on the database (“INSERT ON
CREATE TABLE SHIPMENT{.....}....... HYDERABAD - SUPPLIER” in the example)
FOREIGN KEY {SUPPLIER - NUMBER} 1. The “condition” is a Boolean expression that has to
REFERENCES evaluate to TRUE in order for the action to be executed.
SUPPLIER ON DELETE CASCADE 2. The ‘action’ is the triggered procedure (“INSERT
INTO SUPPLIERS . . .)
The specification ON DELETE CASCADE defines a 3. The event and condition together are sometimes
delete rule for this particular foreign key, and the speci- called the triggering event. The combination of all
fication CASCADE is the referential action for that three (event, condition, and action) is usually called a
delete rule. The meaning of these specifications is that a trigger.
DELETE operation on the suppliers relvar will ‘Cascade” 4. Possible events include INSERT, DELETE, UPDATE,
to delete matching tuples (if any) in the shipments relvar reaching end-of-transaction (COMMIT) reaching a
as well. specified time of day, exceeding a specified elapsed
Same procedure is applied for all the referential actions. time, violating a specified constraint, etc.
5. A database that has associated triggers is sometimes
called an active database.
Triggers
Triggers are precompiled procedures that are stored along
with the database and invoked automatically whenever Base Table Constraints
some specified event occurs. SQL-base table constraints are specified on either CERATE
Suppose we have a view called HYDERABAD - TABLE or ALTER TABLE. Each such constraint is a can-
SUPPLIER defined as follows: didate key constraint, a foreign key constraint, or a CHECK
constraint.
CREATE VIEW HYDERABAD-SUPPLIER Candidate keys: An SQL candidate key definition takes one
AS SELECT SUPPLIER - NUMBER, SUPPLIER- of the following two forms:
NAME, STATUS
FROM SUPPLIER
WHERE CITY = ‘HYDERABAD’, PRIMARY KEY (< column name comma list>)
UNIQUE (< column name comma list>)
Normally, if the user tries to insert a row into this view, The following example illustrates base table con-
SQL will actually insert a row into the underlying base straints of all three kinds:
table SUPPLIERS with CITY value whatever the default CREATE TABLE SHIPMENTS
is for the CITY column. Assuming that default is not (SUPPLIER-NUMBER. SUPPLIER-NUMBER
Hyderabad, the net effect is that the new row will not NOT NULL, PART - NUMBER PART-NUMBER
appear in the view; therefore, let us create a triggered pro- NOT NULL, QUANTITY NOT NULL
cedure as follows: PRIMARY KEY (SUPPLIER - NUMBER,
PART NUMBER)
FOREIGN KEY (SUPPLIER-NUMBER)
CREATE TRIGGER HYDERABAD -
REFERENCES SUPPLIERS
SUPPLIER - INSERT
ON DELETE CASCADE
INSTEAD OF INSERT ON HYDERABAD
ON UPDATE CASCADE,
- SUPPLIER
FOREIGN KEY (PART-NUMBER)
REFERENCING NEW ROW AS R
REFERENCES PARTS
FOR EACH ROW
ON DELETE CASCADE
INSERT INTO SUPPLIERS (SUPPLIER -
ON UPDATE CASCADE
NUMBER, SUPPLIER - NAME, STATUS, CITY)
CHECK(QUANTITY ≤ QUANTITY (0) AND
VALUES (R. SUPPLIER - NUMBER, R.
SUPPLIER - NAME, R. STATUS, ‘HYDERABAD’); QUANTITY ≤ QUANTITY (1000));
Inserting a row into the view will now cause a row to be A check constraint of the form CHECK (< column name >
inserted into the underlying base table with CITY value IS NOT NULL) can be replaced by a simple NOT NULL
equal to Hyderabad inserted of the default value. specification in the definition of the column.
Chapter 1 • ER Model and Relational Model | 4.15
Exercises
Practice Problems 1 B
Directions for questions 1 to 20: Select the correct alterna- Id Name Age
tive from the given choices. 15 Shreya 24
1. Consider the following two tables T1 and T2. Show the 25 Hari 40
output for the following operations: 98 Rohit 20
Table T1 99 Rohit 11
P Q R C
11 a 6 Id Phone Area
16 b 9 10 2200 02
26 a 7 99 2100 01
Table T2 How many tuples does the result of the following rela-
tional algebra expression contain? Assume that the
A B C scheme of (A∪B) is the same as that of A.
11 b 7 (A∪B)⋈[Link]>40 v [Link]<15C
26 c 4 (A) 6 (B) 7
11 b 6 (C) 8 (D) 9
4. Consider the relations A, B and C given in Question 3.
What is the number of tuples present in the result of
How many tuples does the result of the following SQL
given algebraic expressions?
query contain?
(i) T1 ⋈T1.P = T2.AT2
SELECT [Link]
(A) 2 (B) 3 FROM A
(C) 4 (D) 5
WHERE [Link]>
(ii) T1 ⋈T1.Q = T2.BT2
ALL (SELECT [Link]
(A) 2 (B) 3 FROM B
(C) 4 (D) .5
WHERE [Link] = ‘Arun’)?
(iii) T1 ⋈(T1.p = T2.A AND T1.R = T2.C)T2 (A) 0 (B) 1
(A) 1 (B) 2 (C) 2 (D) 3
(C) 3 (D) .4 5. Consider a database table T containing two columns
2. Suppose R1(A, B) and R2(C, D) are two relation schemas. X and Y each of type integer. After the creation of the
Let R1 and R2 be the corresponding relation instances. B table, one record (X = 1, Y = 1) is inserted in the table.
is a foreign key that refers to C in R2. If data in R1 and Let MX and MY denote the respective maximum value
R2 satisfy referential integrity constraints, which of the of X and Y among all records in the table at any point
following is true? in time. Using MX and MY, new records are inserted in
the table 128 times with X and Y values being MX + 1,
(A) π B ( R1 ) − π c ( R2 ) = φ 2 * MY + 1, respectively. It may be noted that each time
(B) π C ( R2 ) − π B ( R1 ) = φ after the insertion, values of MX and MY change. What
will be the output of the following SQL query after the
(C) π B ( R1 ) − π C ( R2 ) ≠ φ steps mentioned above are carried out?
(D) Both A and B Select y from t where x = 7;?
3. Consider the following relations: (A) 15 (B) 31
(C) 63 (D) 127
A, B and C
6. Database table by name loan records is given below:
A
Id Name Age Borrower Bank Manager Loan Amount
12 Arun 60 Ramesh Sunderajan 10000
15 Shreya 24 Suresh Ramgopal 5000
99 Rohit 11 Mahesh Sunderajan 7000
4.16 | Unit 4 • Databases
What is the output of the following SQL Query For any arbitrary predicate P, this query is equivalent to
SELECT count (*) which relational algebra expression?
FROM((SELECT Borrower, Bank-manager (A) Π a1 , a2 , … an (σ p R1 × R2 ×…× Rm )
FROM Loan-Records)AS S
(B) σ a1 , a2 , … an (σ p R1 × R2 ×…× Rm )
NATURAL JOIN
(SELECT Bank-manager, Loan-Amount (C) σ a1 , a2 , … an (∏ p R1 × R2 ×…× Rm )
FROM Loan-Records) AS T);
(D) Π R1 , R2 , … Rm (σ p a1 × a2 ×…× ( an )
(A) 3 (B) 4
(C) 5 (D) 6 11. Consider the following relation schema pertaining to a
7. Consider the following ER diagram: student’s database:
Student (Rollno, name, address)
m1 m2 m3 P1 P2 N1 N2 Enroll (Rollno, courseno, coursename)
Where the primary keys are shown underlined. The
m R1 P R2 N number of tuples in the student and Enroll tables are
120 and 6, respectively. What are the maximum and
What is the minimum number of tables needed to rep- minimum number of tuples that can be present in
resent M, N, P, R1, R2? (student * Enroll)
(A) 2 (B) 3 Where ‘*’ denotes natural join?
(C) 4 (D) 5 (A) 6, 6 (B) 6, 120
8. Let E1 and E2 be two entities in an ER diagram with (C) 120, 6 (D) 120, 120
simple single-valued attributes. R1 and R2 are two rela- 12. A relational schema for a train reservation database is
tionships between E1 and E2, where R1 is one-to-many given below
and R2 is many-to-many. R1 and R2 do not have any
Table 4 Passenger
attributes of their own. What is the minimum number
of tables required to represent this situation in the rela- Pid P Name Age
tional model? 0 ‘Sachin’ 65
(A) 2 (B) 3 1 ‘Rahul’ 66
(C) 4 (D) 5
‘Sourav’ 67
9. The following table has two attributes A and C where A 3 ‘Anil’ 69
is the primary key and C is the foreign key referencing
A with ON DELETE CASCADE.
Table 5 Reservation
A C Pid Class Tid
2 4 0 AC 8200
3 4 1 AC 8201
4 3 2 SC 8201
5 2 5 AC 8203
7 2 1 SC 8204
9 5 3 AC 8202
6 4
What pid’s are returned by the following SQL query for
What is the set of all tuples that must be additionally the above instance of the tables?
deleted to preserve referential integrity when the tuple SELECT pid
(2, 4) is deleted?
FROM Reservation
(A) (5, 2),(7, 2) (B) (5, 2), (7, 2),(9, 5)
(C) (5, 2),(9, 5) (D) (2, 4), (7, 2) WHERE class = ‘AC’ AND
10. Consider the following SQL query EXISTS (SELECT *
SELECT DISTINCT a1, a2, a3 … an FROM passenger
FROM R1, R2 … Rm WHERE age > 65 AND
WHERE P [Link] = [Link])
Chapter 1 • ER Model and Relational Model | 4.17
(A) 0, 1 (B) 1, 3 (A) The above query displays DA and gross for all
(C) 1, 5 (D) 0, 3 those employees whose basic is ≥ 2000
13. Given {customer} is a candidate key, [customer name, (B) The above query displays DA and gross for all em-
customer street} is another candidate key then ployees whose basic is less than 2000
(A) {customer id, customer name} is also a candidate (C) The above query displays DA as well as gross for
key. all those employees whose basic is >2000
(B) {customer id, customer street} is also a candidate (D) Above all
key. 17. Which of the following query transformations is correct?
(C) {customer id, customer name, customer street} is R1 and R2 are relations C1, C2 are selection conditions
also a candidate key. and A1 and A2 are attributes of R1
(D) None (A) σC1(σC1(R1))→σC2(σC2(R1))
Common data for questions 14 and 15: Consider the fol- (B) σC1(σA1(R1))→σA1(σC1(R1))
lowing diagram, (C) pA2(pA(R1))→pA(pA2(R1))
(D) All the above
X1 X2 X3 18. Consider the following query select distinct a1, a2, …an
from r1, r2 . . . rm where P for an arbitrary predicate P,
this query is equivalent to which of the following rela-
X
tional algebra expressions:
(A) π σ p ( r1 × r2 × ... × rm )
a1 ... an
R1
(B) π σ p ( r1 × r2 × r3 ×…. × rm )
a1 ... an
Y1 Z1
(C) σ π p ( r1 × r2 × ... × rm )
a1 ... an
Y R1 Z
(D) σ π p ( r1 × r2 ×…× rm )
Y2 Z1 a1 ... an
4. In entity relationship diagram double lines indicate (C) query which involves a Cartesian product and a
(A) Cardinality projection
(B) Relationship (D) None
(C) Partial participation 12. The number of entities participating in the relationship
(D) Total participation is known as
5. An edge between an entity set and a binary relationship (A) maximum cardinality (B) composite identifiers
set can have an associated minimum and maximum (C) degree (D) None
cardinality, shown in the form 1… h where 1 is the 13 A minimum cardinality of 0 specifies
minimum and h is the maximum cardinality A mini- (A) non-participation
mum value 1 indicates: (B) partial participation
(A) total participation (B) partial participation (C) total participation
(C) double participation (D) no participation (D) zero participation
6. Let R be a relation schema. If we say that a subset k
14. What is not true about weak entity?
of R is a super key for R, we are restricting R, we are
(A) They do not have key attributes.
restricting consideration to relations r(R)in which no
(B) They are the examples of existence dependency.
two district tuples have the same value on all attributes
(C) Every existence dependency results in a weak entity
in K. That is if t1 and t2 are in r and t1 ≠ t2
(D) Weak entity will have always discriminator attributes
(A) t1[k] = 2t2[K] (B) t2[K] = 2t1[k]
(C) t1[k] = t2[k] (D) t1[k] ≠ t2[k] 15. Which one is the fundamental operation in the rela-
tional algebra?
7. Which one is correct?
(A) Natural join (B) Division
(A) Primary key ⊂ Super key ⊂ Candidate key
(C) Set intersection (D) Cartesian product
(B) Candidate key ⊂ Super key ⊂ Primary key
(C) Primary key ⊂ Candidate key ⊂ Super key 16. For the given tables
(D) Super key ⊂ Primary key ⊂ Candidate key
A B
8. If we have relations r1(R1) and r2(R2), then r1 (r2 is a X Y Y
relation whose schema is the
a1 b1 b1
(A) concatenation (B) union
(C) intersection (D) None a2 b1 b2
a1 b2
9. Match the following:
a2 b2
I Empid 1 Multivalued
II Name 2 Derived
A ÷ B will return
III Age 3 Composite (A) a1, a2 (B) a1
IV Contact No. 4 Simple (C) a2 (D) None
(A) I – 4, II – 3, III – 2, Iv – 1 17. The number of tuples selected in the above answer is
(B) I – 3, II – 2, III – 4, Iv – 1 (A) 2 (B) 1
(C) I – 2, II – 1, III – 4, Iv – 3 (C) 0 (D) 4
(D) I – 1, II – 3, III – 2, IV – 4
Common data for questions 18 and 19: Consider the fol-
10. Match the following: lowing schema of a relational database.
I Double-lined ellipse 1 Multivalued attribute Emp (empno, name, add)
II Double line 2 Total participation Project (Pno, Prame)
III Double-lined box 3 Weak entity set Work on (empno, Pno)
IV Dashed ellipse 4 Derived attribute Part (partno, Pname, qty, size)
(A) I – 1, II – 2, III – 3, IV – 4 Use (empno, pno, partno, no)
(B) I – 2, II – 3, III – 4, IV – 1 18. ((name(emp) ( (name(emp ⋈ workon) displays
(C) I – 3, II – 4, III – 2, IV – 2 (i) The names of the employees who are not working
(D) I – 4, II – 3, III – 2, IV –1 in any project
11. The natural join is a (ii) The names of the employees who were working in
(A) binary operation that allows us to combine certain every project.
selections and a Cartesian product into one operation (A) Only (i) (B) Only (ii)
(B) unary operations that allows only Cartesian product (C) Both (A) and (B) (D) None
Chapter 1 • ER Model and Relational Model | 4.19
19. List the partno and names of the parts used in both the 20. The following query shows. SELECT job-status, sum
projects DBMS & MIS: (basic – salary) AVG (basic – salary) from employees
(A) spartno, pname,(part ⋈ (ppartno (spname = “DBMS”(project) ⋈ group by job – status.
use).
∩ ppartno (spname = “MIS”(project) ⋈ use)) (i) It shows job status, sum, AVG of all data
(B) (partno, pname(part ⋈ ((partno ((pname = (ii) It shows job status, Sum, AVG, with group by
“DBMS”(project ⋈ use) ((partno(spname = clause in use.
“MIS”(project) ⋈ use))) (A) only (i)
(C) ppartno, pname(part ⋈ (spartno (spname = “DBMS”(project ⋈ (B) only (ii)
use)
( (partno ((pname = “MIS”(project) ⋈ use))) (C) both (A) and (B)
(D) None (D) None
8. An ER model of a database consists of entity types A set E2. Assume that E1 and E2 participate totally in
and B. These are connected by a relationship R which R and that the cardinality of E1 is greater than the
does not have its own attribute, Under which one of cardinality of E2.
the following conditions, can the relational table for R Which one of the following is true about R?[2018]
be merged with that of A?[2017]
(A) Every entity in E1 is associated with exactly one
(A) Relationship R is one-to-many and the participa-
entity in E2.
tion of A in R is total.
(B) Some entity in E1 is associated with more than
(B) Relationship R is one-to-many and the participa-
one entity in E2.
tion of A in R is partial.
(C) Every entity in E2 is associated with exactly one
(C) Relationship R is many-to-one and the participa-
entity in E1.
tion of A in R is total.
(D) Every entity in E2 is associated with at most one
(D) Relationship R is many-to-one and the participa-
entity in E1.
tion of A in R is partial.
9. In an Entity-Relationship (ER) model, suppose R is a
many-to-one relationship from entity set E1 to entity
Answer Keys
Exercises
Practice Problems 1
1. (i) B (ii) A (iii) A 2. A 3. B 4. D 5. D 6. D 7. B 8. B
9. B 10. A 11. A 12. B 13. D 14. A 15. A 16. C 17. B 18. B
19. C 20. D
Practice Problems 2
1. D 2. B 3. C 4. A 5. A 6. D 7. C 8. A 9. A 10. A
11. A 12. C 13. C 14. A 15. D 16. A 17. A 18. A 19. C 20. B
LEARNING OBJECTIVES
1. It provides a procedural way to query a database. 113 John 12, SP Road Coin collection
2. Input is one (or) more relations. 114 Mary 16, SP Road Painting
3. Output is one relation. 115 Brat 18, GP Road Stamp collection
4.22 | Unit 4 • Databases
σ Hobby = ‘stamp. Collection’(person) In the output table, John name has appeared once, project
The above given statement displays all tuples (or) records operation eliminated duplicates.
with hobby ‘stamp collection’. 2. pName, address (person)
Output: Output:
Id Name Address Hobby Name Address
Intersection B
Like union, Intersection operator requires its operands to Supplier number Supplier number Status City
be of the same type. Given are two relations a and b of the SN3 SURESH 40 HYDERABAD
same type, then, the intersection of those two relations, ‘a’ SN4 RAMESH 30 CHENNAI
INTERSECT ‘b’, is a relation of the same type, with body
consisting of all tuples t such that t appears in both ‘a’ and UNION (A ∪ B)
‘b’.
Supplier number Supplier name Status City
Intersection operation returns tuples which are common
SN1 MAHESH 40 HYDERABAD
to both tables
SN3 SURESH 40 HYDERABAD
Table 3 Result of intersection operation SN4 RAMESH 30 CHENNAI
Example: Consider the given database scheme and the 1. In co-related nested queries, the inner query depends
statement: on the outer query for its value.
2. Sub-query is executed repeatedly, once for each row
EMPLOYEE that is selected by the outer query.
FNAME INITIAL LNAME ENO DOB ADDRESS SALARY DNO 3. A correlated subquery is a sub query that contains a
reference to a table that also appears in the outer query.
DEPARTMENT
Example: Consider the following correlated nested query:
SELECT *
D NAME DNO MANAGER-NO FROM table1
WHERE col1 ≥ ALL
DEPARTMENT–LOCATIONS
(SELECT col1 FROM table2 WHERE table2. col2 =
table1. col2)
DNO D-LOCATION
1. The subquery contains reference to a column of table1,
even though the sub-queries FROM clause does not
PROJECT mention a table table1
2. SQL has to check outside the sub-query and find Table
PNAME PNO P-LOCATION DNO
1 in the outer query
3. Suppose that Table 1 contains a row where col1 = 3 and
col2 = 4 and Table 2 contains a row where col1 = 5 and
WORKS–ON
col2 = 4
ENO PNO HOURS 4. The expression
Example: SELECT DISTINCT ENO FROM WORKS - 1. In this, there is no specific series of operations.
ON WHERE (PNO, HOURS) IN (SELECT PNO, HOURS 2. Relational algebra defines the sequence of operations.
FROM WORKS - ON WHERE ENO = 929). 3. Relational calculus is closer to how users would for-
mulate queries, in terms of information requirements,
This query will select the employee numbers of all rather than in terms of operations.
employees who work on the same (PROJECT, HOURS)
combination on some project a particular employee whose Relational Calculus
ENO = ‘929’ works on. In this example, the IN operator
compares the subtuple of values in parentheses (PNO,
HOURS) for each tuple in works on with the set of union- Tuple Relational Domain Relational
compatible tuples produced by the nested query. calculus (variables Calculus (variables
range over tuples) range over domain
Correlated nested queries: Nested queries can be evaluated attributes)
by executing the sub query (or) Inner query once and sub-
stituting the resulting value (or) values into the WHERE 4. Relational calculus is based on predicate logic, gives
clause of the outer query. the usual quantifiers to construct complex queries.
4.26 | Unit 4 • Databases
sname age
A non-procedural language, where each query is of the
yuppy 35
form {t| p(t)}. It is a set of all tuples t such that predicate p
rusty 35
is true for t, t is a tuple variable, t [A] denotes the value of
tuple ‘t’ on attribute A.
{T| p (T)} Join Operation in Tuple Relational Calculus
T is a tuple and P (T) denotes a formula in which tuple vari- Examples:
able T appears. 3. Find sailors rated > 7 who have reserved boat = 103.
1. ∀ × (P(X)) Solution: {S | S ∈ sailors ∧ [Link] > 7 ∧ ∃ R (R ∈ reserves
∀ is called the universal or ‘for all’ quantifier because ∧ [Link] = [Link] ∧ [Link] = 103)}
every tuple in ‘the universe of’ tuples must make F 4. Find sailors rated > 7 who have reserved a red boat.
true to make the quantified formula true.
Only true if p(X) is true for every X in the universe. Solution: {S | S ∈ sailors ∧ [Link] > 7 ∧ ∃ R (R ∈ reserves ∧
[Link] = [Link] ∧ ∃ B( Boats ∧ [Link] = [Link] ∧ [Link] = ‘Red’))}
Example: ∀ × ([Link] = ‘Red’)
means everything that exists is red.
Division Operation in Tuple
Example: ∀ × ((x ∈ Boats) ⇒ (X. color = ‘Red’)) Relational Calculus
‘⇒’ is a logical implication. a ⇒ b means that if a is Examples
true, b must be true 1. Find sailors who have reserved all boats.
(or)
∃ × ∈ Boats ([Link] = ‘Red’) Solution: {S | S ∈ sailors ∧ ∀ B ∈ boats (∃ R ∈ reserves
For every ‘x’ in the boats relation, the color must be ([Link] = [Link] ∧ [Link] = [Link]))}
red.
Domain Relational Calculus
2. ∃ × (P(X))
1. Tuple relational and domain relational are semantically
∃ is called the existential or ‘there exists’ quantifier
similar.
because any tuple that exists in ‘the universe of’ tuples
2. In TRC, tuples share an equal status as variables, and
may take F true, to make the quantified formula true.
field referencing can be used to select tuple parts.
Chapter 2 • Structured Query Language | 4.27
In the above table, we have studentId that uniquely identifies Foreign key: A foreign key is a column or group of columns
the students in a student table. This would be a candidate in a relational database table that provides connectivity
key. between data in two tables.
In the same table, we have student’s first name and last 1. The majority of tables in a relational database system
name, which are also candidate keys. adhere to the concept of foreign key.
1. If we combine first name and last name then also it 2. In complex databases, data must be added across mul-
becomes a candidate key. tiple tables, thus the link or connectivity has to be
2. Candidate key must (have) maintained among the tables.
•• Unique values 3. The concept of Referential Integrity constraint is
•• No null values derived from Foreign key.
•• Minimum number of fields to ensure uniqueness. Example: Emp
•• Uniquely identify each record in the table.
EId EName Dept – No
3. The candidate keys which are not selected for primary
key are known as secondary keys or alternative keys.
Dept
Primary key: A primary key is a candidate key that is most Dept-No DName
suitable (or) appropriate to become main key of the table.
1. It is a special relational database table column ((or)
In the above specified tables, Dept-No is common to both
combination of columns)
the tables, In Dept table it is called as primary key and in
2. Primary key main features are
Emp table it is called as foreign key.
•• It must contain a unique value for each row of data.
These two tables are connected with the help of
•• It cannot contain null values.
‘Dept-No’ field
Example: We can choose primary key as studentId which 1. For any column acting as a foreign key, a correspond-
is mentioned in the table given in above example. ing value should exist in the link (or) connecting table.
Composite primary key: A key that consists of two or more 2. While inserting data and removing data from the for-
attributes that uniquely identify an entity is called compos- eign key column, a small incorrect insertion or dele-
ite key or composite primary key. tion destroys the relationship between the two tables.
Example: Customer
SQL Commands
Cust-Id Order-Id Sale-details
SELECT statement
C1 O–2 Sold
The most commonly used SQL command is SELECT state-
C1 O–3 Sold
ment. The SQL SELECT statement is used to query or retrieve
C2 O–2 Sold data from a table in the database. A query may retrieve infor-
C2 O–3 Sold mation from specified columns or from all of the columns in
the table. To create a simple SQL SELECT statement, you
Composite primary key is {cust-Id, order-Id} must specify the column(s) names and the table name.
Super key: A super key is a combination of attributes that Syntax: SELECT column-name (s) from table name
can be uniquely used to identify a database record. A table
can have any number of super keys. Example: Persons
Lastname Firstname Address City
1. Candidate key is a special subset of super keys.
Hansen Ola SpRoad,-20 Hyd
Example: Customer
Svendson Tove GPRoad,-18 Secbad
Customer name Customer Id SSN Address DOB Petterson Kari RpRoad,-19 Delhi
Male-Female We may specify ‘desc’ for descending order (or) ‘asc’ for
ascending order. - ‘asc’ is default.
Female name Female job Male name Male job
Komal Clerk Rohit Clerk Example: ORDERBY customer-name desc.
Komal Clerk Raju Sales
Join (⋈)
Ankita Sales Rohit Clerk SQL Join is used to get data from two (or) more tables,
Ankita Sales Raju Sales which appear as single table after joining.
2. Find the name, loan-no and loan amount of all custom- SELECT *
ers, rename the column name loan-no as [Link]? FROM Class INNER JOIN Info
Solution: SELECT [Link], [Link] no AS WHERE [Link] = [Link]
[Link], amount FROM borrower, loan, WHERE borrower. Result:
loan-no = [Link]-no
SID Name SID City
Both tables being joined have SID column (same name and Example: Consider the tables class 1 and Info1
same data type), the tuples for which value of SID matches Query:
in both the tables, appear in the result. SELECT *
FROM class1 FULL OUER JOIN Info1
Dangling tuple: When NATURAL JOIN is performed on ON([Link] = [Link])
two tables, there would be some missing tuples in the result
Result:
of NATURAL JOIN
SID Name City
Those missing tuples are called Dangling tuples. In the
16 Arun Chennai
above example, the number of dangling tuples is 1 that is
17 Kamal NULL
14 Adam 18 NULL Noida
OUTER JOIN: Outer Join is based on both matched and ALTER command: ALTER command is used for altering the
unmatched data. table structure
LEFT OUTER JOIN: Left outer Join returns the tuples 1. It is used to add a new column to existing table.
available in the left side table with the matched data of 2 2. To rename existing column.
tables and null for the right tables column. 3. ALTER is used to drop a column.
Example: Consider the table’s class and Info 4. It is used to change data type of any column or modify
SELECT * its size.
FROM class LEFT OUTER JOIN Info Add new column: By using alter command, we can add a
ON([Link] = Info. SID) new column to the table.
Result:
Syntax: ALTER table table-name ADD(column-name data
SID Name City type).
11 Ana Banglore
Example: Consider a student table.
12 Bala Delhi
SID S Name Grade
13 Sudha Hyderabad
14 adam NULL
RIGHT OUTER JOIN: RIGHT OUTER JOIN returns the Add a new column called address
tuples available in the Right side table with the matched ALTER table student ADD (address char);
data of 2 tables and NULL for the left table’s column.
Example: Class 1 Example: Add multiple columns, parent-name, course-
Name, date-of-birth to student table.
SID Name
16 Arun ALTER table student ADD (parent-name
17 Kamal varchar(60), course-Name varchar(20),
date-of-birth date);
Info 1
SID City Example: Change the data type of column address to varchar?
16 Chennai
17 Noida ALTER table student modify(address varchar(30))
Chapter 2 • Structured Query Language | 4.33
Exercises
Practice Problems 1 (C) SELECT *
Directions for questions 1 to 20: Select the correct alterna- FROM Persons
tive from the given choices. WHERE last-name=’svendson’
AND (first-name=’tove’ AND first-name=’ola’)
1. Consider the given table called Persons (D) SELECT *
FROM Persons
P-Id Lastname Firstname Address City
WHERE last-name=’svendson’
1 Hansen ola Timoteivn -10 Sandnes OR (first-name=’tove’ AND first-name=’ola’)
2 Svendson Tove Brazil-50 Sandnes 3. Write an SQL statement to add a new row, but only in
3 Petterson Kari Storgt-20 Stavanger specified columns, for the persons table add data into
4 Joseph ole Brazil-20 Sandnes columns ‘P-Id’, ‘Last name’ and the ‘First name’ with
values (5, Teja, Jakob)?
Write a query to select the persons with first name (A) INSERT INTO Persons VALUES(5,‘teja’,‘jakob’)
‘Tove’ and last name ‘Svendson’? (B) INSERT INTO Persons VALUES(5,teja,jakob)
(A) SELECT * (C) INSERT INTO Persons (P-Id, last-name, first-
FROM Persons name) VALUES(5,’teja’,’jakob’)
WHERE first-name=’tove’ (D) INSERT INTO Persons(P-Id, last-name, first-
AND last-name=’svendson’ name) VALUES(5,teja,jakob)
(B) SELECT * 4. Write an SQL statement:
FROM Persons (i) To select the persons living in a city that starts
WHERE first-name=’tove’ with ‘S’ from the ‘Persons’ table?
OR last-name=’svendson’ (A) SELECT *
(C) SELECT first-name FROM Persons
FROM Persons WHERE city LIKE ‘s__’.
WHERE first-name=’tove’ (B) SELECT *
AND last-name=’svendson’ FROM Persons
(D) SELECT last-name WHERE city LIKE ‘s%’.
FROM Persons (C) SELECT *
WHERE first-name=’tove’ FROM Persons
AND last-name=’svendson’ WHERE city LIKE ‘%s’.
(D) SELECT *
2. Write a query to select only the persons with last name
FROM Persons
‘Svendson’ and the first name equal to ‘Tove’ or ‘ola’?
WHERE city LIKE ‘_s%’.
(A) SELECT * (ii) To select the persons living in a city that contains
FROM Persons the pattern ‘tav’ from ‘Persons’ table?
WHERE last-name=’svendson’ (A) SELECT *
AND first-name=’tove’ FROM Persons
(B) SELECT * WHERE city LIKE ‘_tav_’.
FROM Persons (B) SELECT *
WHERE last-name=’svendson’ FROM Persons
AND (first-name=’tove’ OR first-name=’ola’) WHERE city LIKE ‘_tav%’.
4.34 | Unit 4 • Databases
(C) SELECT * (i) Find out the students who have scored more than
FROM Persons 80 marks, and display them in descending order
WHERE city LIKE ‘%tav_’. according to their marks?
(D) SELECT * (A) SELECT student-name,marks
FROM Persons FROM Result
WHERE city LIKE ‘%tav%’. WHERE marks > 80
(iii) To select the persons whose last name starts with ORDERBY marks DESC
‘b’ or ‘s’ or ‘p’ ? (B) SELECT *
(A) SELECT * FROM Result
FROM Persons WHERE marks > 80
WHERE last-name LIKE ‘b-s-p’ ORDERBY marks DESC
(B) SELECT * (C) SELECT student-name,marks
FROM Persons FROM Result
WHERE last-name LIKE ‘b%s%p’ WHERE marks > 80
(C) SELECT * ORDERBY marks
FROM Persons (D) (A) and (B)
WHERE last-name LIKE ‘b%s%p%’ (ii)
From the above table, find out the top-most three
(D) SELECT * students.
FROM Persons (A) SELECT student-name
WHERE last-name LIKE ‘[bsp]%’ FROM Result
5. Consider the given table called ‘Persons’ ORDERBY marks DESC > 3
(B) SELECT student-name
P-Id Last-name First-name Address City FROM Result
1 Hansen ola Timoteivn-10 Sandnes ORDERBY marks DESC = 3
2 Svendson Tove Brazil-50 Sandnes (C) SELECT student-name
3 Petterson Kari Storgt-20 Stavanger FROM Result
ORDERBY marks DESC limit 3
and the ‘Orders’ table (D) None of these
O-Id Order No P-Id 8. From the table ‘Results’, Identify the suitable SQL
11 77895 3 expression?
12 44678 3 (i) Find out the student Who stood 2nd?
13 22456 1 (A) SELECT student-name
14 24562 1
FROM Result
ORDERBY marks DESC limit 2
15 34764 5
(B) SELECT student-name
perform NATURAL JOIN operation on both the tables FROM Result
and what is are the O_Id’s displayed in the result? ORDERBY marks DESC limit 1,1
(A) 11, 12, 13 (B) 11, 13, 14 (C) SELECT student-name
(C) 11, 12, 13, 14 (D) 12, 13, 14 FROM Result
6. Write an SQL to perform FULL JOIN operation on ORDERBY marks DESC limit 1,2
both ‘Person’ and ‘Orders’ tables and What is the num- (D) SELECT student-name
ber of tuples in the Result? FROM Result
(A) 4 (B) 5 ORDERBY marks DESC limit 2,1
(C) 6 (D) 7 (ii) Find out how many students scored > = 80.
(A) SELECT COUNT(*)
7. Consider the given table ‘Result’. FROM Result
Student Name Marks WHERE marks > = 80
A 55 (B) SELECT COUNT
B 90 FROM Result
C 40 WHERE marks > = 80
(C) SELECT SUM(*)
D 80
FROM Result
E 85
WHERE marks > = 80
F 95 (D) SELECT SUM
G 82 FROM Result
WHERE marks > = 80
Chapter 2 • Structured Query Language | 4.35
Practice Problems 2 7. Select the persons whose hobby is either painting (or)
Directions for questions 1 to 20: Select the correct alterna- singing.
tive from the given choices. (A) sHobby = ‘painting’ OR Hobby = ‘singing’ (person)
1. The correct order of SQL expression is (B) sHobby = ‘painting’,’ singing’ (person)
(A) Select, group by, where, having (C) sHobby = ‘painting’ OR ‘singing’ (person)
(B) Select, where, group by, having (D) All are correct
(C) Select, group by, having, where 8. Select the persons whose age is above 21 and below 32:
(D) Select, having, where, group by (A) sage > 21 AND age < 32 (person)
2. Which one is not a query language? (B) s21 < age < 32 (person)
(A) SQL (B) QBE
(C) sage > 21 OR age < 32 (person)
(C) Data log (D) MySQL
(D) sage < 21 AND age > 32 (person)
3. Like ‘a b \ % c d’ escape ‘\’ matches all the strings
(A) Ending with a b c d Common data for questions 9 and 10: Consider the fol-
(B) Beginning with a b c d lowing relation: Teach
(C) Beginning with a b c d
Name course Rating Age
(D) Beginning with a b % c d
Zohar MD 7 35
4. ‘_ _ _%’ matches any string of
(A) At least three characters Nisha BDS 8 27
(B) At most three characters Zohar MS 7 34
(C) Exactly three characters Ravi MBA 9 33
(D) exactly three characters ending with %
5. Which of the following are set operations? 9. Select the teachers whose rating is above 7 and whose
(i) Union age is less than 32?
(ii) Intersection (A) sRating > 7 AND Age < 32 (Teach)
(iii) Set Difference (B) sRating ≥ 7 AND Age < 32 (Teach)
(iv) Cartesian Product (C) sRating > 7 AND < 32 (Teach)
(A) (i), (ii), (iii) (D) Both (A) and (B)
(B) (i), (iii), (iv)
10. Select the courses with rating above 7?
(C) (i), (iii), (ii), (iv)
(D) (i), (ii), (iv) (A) pcourse (srating > 7 (Teach))
(B) scourse (p rating > 7(Teach))
6. What is the purpose of project operation?
(C) pname, course (srating > 7 (Teach))
(A) It selects certain columns
(B) It selects certain rows (D) None
(C) It selects certain strings Common data for questions 11 and 12: Consider the follow-
(D) It selects certain integers ing schema of a relational database employee (empno, ename,
eadd) project (pno, pname) Work–on (empno, pno) Part(partno,
Common data for questions 7 and 8: Person partname, qty-on-hand, size) Use (empno, pno, partno, number)
Id Name Age Hobby 11. Display the names of the employees who are working
11 Anu 21 Stamp Collection on a project named ‘VB’.
22 Kamal 32 Painting
(A) sname(employee ⋈ (spname = ‘VB’ project) ⋈ worked on)
(B) sname (employee ⋈ (ppname = ‘VB’ (project) ⋈ work on)
33 Ravi 24 Dancing
(C) pname (employee ⋈ (spname = ‘VB’ (project) ⋈ work on)
44 Ram 22 Singing
(D) pname (employee ⋈ (ppname = ‘VB’ (project) ⋈ work on)
Chapter 2 • Structured Query Language | 4.41
12. Display the names of the people who are not working (A) Names of the students who are working in either
for any project. projects ‘MS’ or ‘MD’
(A) pname (employee ⋈(pname (employee + work on) (B) Names of the students who are working in both the
(B) pname (employee – pname (employee ∩ work on) projects ‘MS’ or ‘MD’
(C) pname (employee – pname (employee ⋈ work on) (C) Names of the students who are not working in any of
the projects ‘MS’ or ‘MD’
(D) sname (employee – sname (employee ⋈ work on)
(D) None of the above
13. Consider the following tables: 16. ‘All rows corresponding to students whose sno’s are
A B C D C D between 10 and 20
b c e f e f
(i) Select * form student where SNo are between 5
AND 10
a b i j g h
(ii) Select * from student where SNO IN(5, 10)
b c g h (A) Only (i) (B) Only (ii)
b c a d (C) Both (A) and (B) (D) None
d i g h 17. UPDATE account SET
d j j k DA = basic * .2,
d i e f GROSS = basic * 1.3, Where basic > 2000;
(A) The above query displays DA and gross for all
R÷S those employees whose basic is ≥ 2000
A B (B) The above query displays DA and Gross for all
b c employees whose basic is less than 2000
(C) The above query displays updated values of DA as
d i
well as gross for all those employees whose basic
Which of the following statements is true? is > 2000
(A) R ÷ S = pA, B(R) – pA, B(pA, B(R) × S + R) (D) All the above
(B) R ÷ S = pA, B(R) – pA, B(pA, BR × S – R) 18. Given two union compatible relations R1(A, B) and R2(C,
D), what is the result of the operation
(C) R ÷ S = pA, B(R) – pA, B((pA, B(R) × S) – R)
R1 A = CAB = DR2?
(D) R ÷ S = pA, B(R) – pA, B(pA, B(R) × R – S) (A) R1 ∪ R2 (B) R1 × R2
(C) R1 – R2 (D) R1 ∩ R2
Common data for questions 14 and 15: Consider the fol-
lowing schema of a relational data base 19. Which of the following queries finds the clients of banker
student (sno, name, address) Agassi and the city they live in?
project (pno, Pname) work-on (sno, pno) [Link]([Link] = customer c name (sBanker.
(A)
Part (part no, part name, qtyon hand size) name = Aggassi
(client × customer)
Use (sno, pno, part no, number) (B) pClient.c city (sBanker name = ‘Aggasi’(client × customer)
14. List the names of the students who are participating in pclient.c [Link](sclient.c name = ‘Aggasi’ ([Link] = Cutomer
(C)
every project and have used every part. (client × customer)
(A) sname(student ⋈(((Workon) ÷ spro(project)) ∩ (ssno, part p .c [Link](sBankers name = name (sBanker. = agassi (cli-
(D)
no
(use) ÷ spart no (part))) ent × customer)
(B) pname(student ⋈(((Workon) ÷ ppro(project)) ∩ (psno, 20. Consider the following schema pertaining to students data
partno
(use) ÷ spart no (part))) Student (rno, name, add)
(C) pname(student ⋈(((Workon) ÷ ppartno (project)) ∩ (psno, Enroll (rno, Cno, Cname) Where the primary keys are
partno
(use) ÷ spart no (part))) shown Underlined. The no. of tuples in the student and
(D) pname(student ∞ (((Workon) ÷ ppro(project)) ∪ (pssno, Enroll tables are 120 and 8 respectively. What are the
partno
(use) ÷ ppart no (part))) maximum and minimum no. of tuples that can be pre-
sent in (student * Enroll) where ‘*’ denotes natural join.
15. The following query gives pname (employee ⋈(work on ÷
(A) 8, 8 (B) 120, 8
ppro (sPname = ‘MS’ AND ‘MD’(project))) (C) 960, 8 (D) 960, 120
4.42 | Unit 4 • Databases
(C)
Courses in which only male students are en- 8. Let R and S be relational schemes such that R =
rolled. {a,b,c} and S = {c}. Now consider the following que-
(D) None of the above ries on the database:
I. π R − S (r ) − π R − S (π R − S (r ) × s − π R − S , S (r ))
5. Consider the relation employee (name, sex, super-
visorName) with name as the key. supervisorName II. {t | t ∈ π R − S (r ) ∧ ∀u ∈ s (∃v ∈ r (u = v[ s ] ∧ t
gives the name of the supervisor of the employee = v[ R − S ]))}
under consideration. What does the following Tuple
Relational Calculus query produce? III. {t | t ∈ π R − S (r ) ∧ ∀v ∈ r (∃u ∈ s (u = v[ s ] ∧ t
e ⋅ name | employee(e) ∧ = v[ R − S ]))}
(A) Only I and II (B) Only I and III 1 ‘Rahul’ 66 1 ‘AC’ 8201
(C) Only I, II and III (D) Only I, III and IV 2 ‘Sourav’ 67 2 ‘SC’ 8201
4.44 | Unit 4 • Databases
3 ‘Anil’ 69 5 ‘AC’ 8203 Let MX and MY denote the respective maximum values
of X and Y among all records in the table at any point
1 ‘SC’ 8204 in time. Using MX and MY, new records are inserted
3 ‘AC’ 8202 in the table 128 times with X and Y values being MX
+ 1, 2 * MY + 1 respectively. It may be noted that each
time after the insertion, values of MX and MY change.
What pids are returned by the following SQL query for the
What will be the output of the following SQL query
above instance of the tables?
after the steps mentioned above are carried out?
SELECT pid SELECT Y FROM T WHERE X = 7; [2011]
FROM Reservation (A) 127 (B) 255
WHERE class = ‘AC’ AND (C) 129 (D) 257
EXISTS (SELECT * 14. Which of the following statements are true about an
FROM Passenger SQL query?
WHERE age > 65 AND P: An SQL query can contain a HAVING clause
[Link] = [Link]) [2010] even if it does not have a GROUP BY clause
(A) 1, 0 (B) 1, 2 Q: An SQL query can contain a HAVING clause
(C) 1, 3 (D) 1, 5 only if it has a GROUP BY clause
11. Consider a relational table r with sufficient number of R: All attributes used in the GROUP BY clause must
records, having attributes A1, A2, … An and let 1 ≤ p ≤ n. appear in the SELECT clause
Two queries Q1 and Q2 are given below. S: Not all attributes used in the GROUP BY clause
need to appear in the SELECT clause [2012]
Q1: π A1 … An (σ Ap=c (r )) where c is a constant.
(A) P and R (B) P and S
Q2: π A1 … An (σ c1 ≤ Ap ≤ c2 (r )) where c1 and c2 are constants. (C) Q and R (D) Q and S
The database can be configured to do ordered indexing 15. Suppose R1(A, B) and R2(C, D) are two relation
on AP or hashing on Ap. Which of the following state- schemas. Let r1 and r2 be the corresponding relation
ments is TRUE? [2011] instances. B is a foreign key that refers to C in R2.
(A) Ordered indexing will always outperform hash- If data in r1 and r2 satisfy referential integrity con-
ing for both queries straints, which of the following is always true?[2012]
(B) Hashing will always outperform ordered index- (A) ΠB (r1) – ΠC(r2) = ∅
ing for both queries. (B) ΠC(r2) – ΠB (r1) = ∅
(C) Hashing will outperform ordered indexing on (C) ΠB (r1) = ΠC (r2)
Q1, but not on Q2.
(D) Hashing will outperform ordered indexing on (D) ΠB (r1) – ΠC (r2) ≠ ∅
Q2, but not on Q1.
Common data for questions 16 and 17: Consider the fol-
12. Database table by name Loan_Records is given below.
lowing relations A, B and C:
Borrower Bank manager Loan amount (A)
Ramesh Sunderajan 10000.00 Id Name Age
16. How many tuples does the result of the following 20. Given the following schema:
SQL query contain? Employees (emp–id, first-name, last– name, hire–
SELECT [Link] date, dept–id, salary)
FROM A Departments (dept–id, dept–name, manager–id,
WHERE A. Age > ALL (SELECT B. Age location–id)
FROM B you want to display the last names and hire dates of
WHERE B. Name = ‘Arun’) [2012] all latest hires in their respective departments in the
(A) 4 (B) 3 location ID 1700. You issue the following query:
(C) 0 (D) 1 SQL > SELECT last–name, hire–date
17. How many tuples does the result of the following FROM employees
relational algebra expression contain? Assume that WHERE (dept–id, hire–date) IN
the schema of A ∪ B is the same as that of A. (SELECT dept–id, MAX (hire–date)
(A⋃B) ⋈[Link] > 40 V [Link] <15C [2012] FROM employees JOIN departments USING
(A) 7 (B) 4 (dept–id)
(C) 5 (D) 9 WHERE location–id = 1700
18. Consider the following relational schema. Students GROUP BY dept–id);
(rollno: integer, sname: string) Courses (courseno: What is the outcome? [2014]
integer, cname: string) Registration(rollno:integer,co (A) It executes but does not give the correct result.
urseno: integer, percent: real) (B) It executes and gives the correct result.
Which of the following queries are equivalent to (C) It generates an error because of pair wise compari-
this query in English? son.
‘Find the distinct names of all students who score (D) It generates an error because the GROUP BY
more than 90% in the course numbered 107’ clause cannot be used with table joins in a sub-
(I) SELECT DISTINCT [Link] FROM Students query.
as S, Registration as R WHERE [Link]=[Link] 21. Given an instance of the STUDENTS relation as
AND [Link]=107 AND [Link]>90 shown below:
(II) psname(σcourseno=107^percent>90 Registration⑅Students) Student Student
Student ID Name Student Email Age CPI
(III) {T |∃ S ∈ Students, ∃R∈ Registration ([Link]=R.
rollno ∧ [Link]=107 ∧ [Link]>90∧T. 2345 Shankar shaker @ math X 9.4
sname=[Link])} 1287 Swati swati @ ee 19 9.5
(IV) {<SN> |∃SR∃RP (<SR, SN> ∈ Students ∧ <SR, 107, 7853 Shankar shankar @ cse 19 9.4
(A) I, II, III and IV (B) I, II and III only 8765 Ganesh ganesh@ civil 19 8.7
(C) I, II and IV only (D) II, III and IV only For (StudentName, StudentAge) to be a key for this
instance, the value X should NOT be equal to _____.
19. Given the following statements: [2014]
S1: A foreign key declaration can always be replaced
22. Consider a join (relation algebra) between relations
by an equivalent check assertion in SQL.
(r(R)) and (s(S)) using the nested loop method. There
S2: Given the table R (a, b, c) where a and b together
are three buffers each of size equal to disk block size,
form the primary key, the following is a valid ta-
out of which one buffer is reserved for intermediate
ble definition.
results. Assuming size r(R) < size s(S), the join will
CREATE TABLE S (
have fewer number of disk block accesses if [2014]
a INTEGER
(A) Relation r(R) is in the outer loop
d INTEGER,
(B) Relation s(S) is in the outer loop
e INTEGER,
(C) Join selection factor between r(R) and s(S) is
PRIMARY KEY (d),
more than 0.5
FOREIGN KEY (a) references R)
(D) Join selection factor between r(R) and s(S) is less
Which one of the following statements is CORRECT? than 0.5
[2014]
23. SQL allows duplicate tuples in relations, and corre-
(A) S1 is TRUE and S2 is FALSE
spondingly defines the multiplicity of tuples in the
(B) Both S1 and S2 are TRUE result of joins. Which one of the following queries
(C) S1 is FALSE and S2 is TRUE always gives the same answer as the nested query
(D) Both S1 and S2 are FALSE shown below:
4.46 | Unit 4 • Databases
Select * from R where a in (select S. a from S)[2014] (C) Names of all the employees with none of their cus-
(A) Select R.* from R, S where R. a = S. a tomers having a ‘GOOD’ rating.
(B) Select distinct R * from R, S where R . a = S . a (D) Names of all the employees with all their customers
(C) Select R.* from R, (select distinct a from S) as S1 having a ‘GOOD’ rating.
where R.a = S1.a 27. SELECT operation in SQL is equivalent to [2015]
(D) Select R.* from R, S where R.a = S.a and is unique (A) The selection operation in relational algebra
R (B) The selection operation in relational algebra,
except that SELECT in SQL retains duplicates.
24. What is the optimized version of the relation algebra
(C) The projection operation in relational algebra.
expression π A1 (π A2 (σ F1 (σ F2 ( r ) ))), where A1, A2 are sets
(D) The projection operation in relational algebra,
of attributes in r with A1 ⊂ A2 and F1, F2 are Boolean except that SELECT in SQL retains duplicates.
expressions based on the attributes in r? [2014]
28. Consider the following relations:
(A) π A1 (σ ( F ∧ F )( r ) )
1 2
Student
(B) π A1 (σ ( F ∨ F )( r ) ) Roll No Student Name
1 2
(C) π A2 (σ ( F ∧ F )( r ) ) 1 Raj
1 2
2 Rohit
(D) π A2 (σ ( F ∨ F )( r ) ) 3 Raj
1 2
EMP
EmpId EmpName DeptName
1 XYA AA SELECTIVE AVG ( [Link] )
2 XYB AA FROM EC
3 XYC AA
WHERE ( DeptName, Num ) IN
4 XYD AA
(SELECT DeptName, COUNT ( EmpId ) AS
5 XYE AB
6 XYF AB EC ( DeptName, Num )
7 XYG AB FROM EMP
8 XYH AC GROUP BY DeptName)
9 XYI AC
10 XYJ AC
11 XYK AD
12 XYL AD
13 XYM AE
The following query is made on the database. 36. Consider the following two tables and four queries in
SQL.
T 1 ← pCouraseName (sStudentName =' SA ' (CR))
Book (isbn, bname), Stock (isbn, copies)
T 2 ← CR ÷ T 1 Query 1: SELECT [Link], [Link]
The number of rows in T2 is . [2017] FROM Book B INNER JOIN Stock S
35. Consider the following database table named ON [Link] = [Link];
top_scorer. Query 2: SELECT [Link], [Link]
FROM Book B LEFT OUTER
top_scorer
JOIN Stock S
player country goals
ON [Link] = [Link];
Klose Germany 16
Query 3: SELECT [Link], [Link]
Ronaldo Brazil 15 FROM Book B RIGHT OUTER
G Miiller Germany 14 JOIN Stock S
Fontaine France 13 ON [Link] = [Link];
Pelé Brazil 12 Query 4: SELECT [Link], [Link]
Klinsmann Germany 11 FROM Book B FULL OUTER
Kocsis Hungary 11 JOIN Stock S
ON [Link] = [Link];
Batistuta Argentina 10
Cubillas Peru 10 Which one of the queries above is certain to have an
Lato Poland 10
output that is a superset of the outputs of the other
three queries? [2018]
Lineker England 10
(A) Query 1 (B) Query 2
T Muller Germany 10
(C) Query 3 (D) Query 4
Rahn Germany 10
37. Consider the relations r(A, B) and s(B, C), where s ⋅ B
Consider the following SQL query: is a primary key and r ⋅ B is a foreign key referencing
SELECT [Link] FROM top_scorer AS ta s ⋅ B. Consider the query
WHERE [Link] >ALL (SELECT [Link] Q: r (σB<5 (S))
FROM top_scorer AS tb Let LOJ denote the natural left outer-join operation.
WHERE [Link] = ‘Spain’) Assume that r and s contain no null values.
AND [Link] >ANY (SELECT [Link]
Which one of the following queries is NOT equiva-
FROM top_scorer AS tc
lent to Q? [2018]
WHERE tc. country = ‘Germany’)
(A) σB<5(r s) (B) σB<5(r LOJ s)
The number of tuples returned by the above SQL (C) r LOJ (σB<5(s)) (D) σB<5(r) LOJ s
query is _________. [2017]
Answer Keys
Exercises
Practice Problems 1
1. A 2. B 3. C 4. (i) B (ii) D (iii) D 5. C 6. C 7. (i) A (ii) C
8. (i) B (ii) A 9. A 10. A 11. (i) A (ii) B 12. (i) B (ii) B (iii) A
13. (i) A (ii) A (iii) A 14. (i) A (ii) A (iii) A 15. (i) A (ii) A (iii) A 16. C
17. A 18. D 19. A 20. D
Practice Problems 2
1. B 2. D 3. D 4. A 5. C 6. A 7. A 8. A 9. A 10. A
11. C 12. C 13. C 14. C 15. C 16. B 17. C 18. D 19. B 20. A
LEARNING OBJECTIVES
NormaliZatioN requirements of the preceding forms have been met. Many rela-
tional database designers feel that, if their tables are in third nor-
Database design theory includes design standards called normal
mal form, most common design problems have been addressed.
forms. The process of making data and tables match these stand-
However, the higher-level normal forms can be of use and are
ards is called normalizing data or data normalization. By normal-
included here.
izing data, we eliminate redundant information and organize table
Database normalization is the process of removing redundant data
to make it easier to manage the data and make future changes to
from tables to improve storage efficiency, data integrity and scalability.
the table and database structure. This process removes the inser-
tion, deletion, and modification anomalies. In normalizing your 1. In the relational model, methods exists for quantifying how
data, we usually divide large tables into smaller, easier to maintain efficient a database is, these classifications are called q′.
tables. We can then use the technique of adding foreign keys to 2. Normalization generally involves splitting existing tables
enable connections between the tables. into multiple ones, which must be rejoined (or) linked each
Data normalization is part of the database design process and time a query is issued.
is neither specific nor unique to any particular RDBMS. These 3. Edgar F. Codd originally established three normal forms: 1NF,
are in order, such as first, second, third, Boyce-Codd, fourth, and 2NF, 3NF. There are others also, but 3NF is widely considered
fifth normal forms. Each normal form represents an increasingly to be sufficient for most applications, most tables when
stringent set of rules; that is, each normal form assumes that the reaching 3NF are also in BCNF (Boyce–Codd normal form).
Table 1
Title Author 1 Author 2 I SBN Subject Pages Publisher
Database system concepts Abraham Silber schatz Henry F. Korth 0072958863 My SQL, computers 1160 McGraw-Hill
OS concepts Abraham Silberschatz Henry F. Korth 0471694665 Computers 990 McGraw-Hill
Anomalies
Problems: An anomaly is a variation that differs in some way from what is
1. This table is not very efficient with storage. said to be normal, with respect to maintaining a database.
2. This design doesn’t protect data integrity. 1. The basic operations performed on Databases are Record
3. This table doesn’t scale well. insertion, Record updation, Record deletion.
4.50 | Unit 4 • Databases
2. It is desirable for these operations to be straight If we delete a tuple where SNo = S43, he is the only (or) last
forward and efficient. student in the accounts department, we will lose data about
3. When relations are not fully normalized they exhibit student ‘S43, Arun’ as well as data about Accounts course
anomalies. that is ‘C9608, Accounts’.
4. The design goal of database is too easily to understand
Updation anomaly An updation anomaly occurs when one
and to maintain.
or more instances of duplicated data are updated but not all.
5. Anomalies are problems that occur in un-normalized
databases where all the data is stored in one table. Example: Consider the ‘course’ table given in the above
example.
If we want to update course – No (Cno) of sales C9201
Types of anomalies to C8686, in the course table.
There are three types of anomalies that can arise in the data-
1. It might happen that, the tuple with S No = S41
base because of redundancy as follows:
updated its CNo to C8686, but not the tuple with SNo
1. Insertion anomaly = S43.
2. Deletion anomaly 2. Inconsistency occurs in the table, because for the same
3. Updation anomaly course sales we have 2 different course Numbers.
Insertion anomaly An insertion anomaly occurs when par- Determining keys For a table ‘R’, its schema R consists of
ticular attributes cannot be inserted into the database with- all attributes of R, we say X is a key to R
out the presence of other attributes. if X → R means
Example: Consider the following table: Sales X determines R
Sales-Rep-Id Name Hire-Date Client R is dependent upon X
1 Ana 1/1/2015 Madison If you know x then you know R
2 Sudha 2/4/2014 Peterson
Example: Consider a relation schema R(ABCDE) and the
3 Joey 3/2/2014 John
functional dependencies:
* New
AC → D
B→E
Insertion anomaly occurs in the above table which stores
records for a company’s sales representatives and the clients DA → B
for whom they are responsible. The closure of AC determines all the attributes present in
Relation R, so the key for R is ‘AC’.
1. It is not possible to add records for newly hired Sales
representatives until they have been assigned to one AC+ =
{AC} (self determination)
or more clients.
2. If we insert a record for newly hired, client column {ACD} (AC → D)
will be NULL, which is a required field for the table. {ACDB} (DA → B)
3. It is not possible to record newly hired in the table
during training. {ACDBE} (B → E)
\ key = AC
Deletion anomaly Deletion anomaly occurs when some
particular attributes are lost because of the deletion of other Any attribute which does not appear on the right-hand-side
attributes. of a given functional dependency appears in any one of the
candidate keys.
Example: Consider the following table ‘course’.
1. From the above example, neither A (or) C appears in
S No C No S Name Course
the right hand side of any functional dependency.
S41 C9201 John Sales
S42 C9401 Brat Finance
S40 C9201 Amit Sales
First Normal Form (1NF)
S43 C9608 Arun Accounts In Table 1, we have two violations of 1NF such as:
1. More than one author field and
Execute the following SQL query: 2. Subject field contains more than one piece of
Delete * information with more than one value in a single
From course field; thus, it would be very difficult to search for all
Where S No = S43 books on a given subject.
Chapter 2 • Normalization | 4.51
In Table 2, we have two rows for a single book. Additionally, Table 5 Book table
we would be violating the second NF. A better solution to the ISBN Title Pages Publisher
problem would be to separate the data into separate tables—
00729 Database System 1160 McGraw-Hill
an author table and a subject table to store our information, 58863 Concepts
removing that information from the book table.
04716 OS concepts 990 McGraw-Hill
Table 3 Subject table 94665
Subject–ID Subject
Each table has a primary key, used for joining tables together
1 My SQL
when querying the data.
2 computers A table is in first normal form (1NF) if there are no
Table 4 Author table
repeating groups. A repeating group is a set of logically
related fields or values that occur multiple times in one
Author–ID Last Name First name record. The sample tables below do not comply with first
1 Silberschatz Abraham normal form. Look for fields that contain too much data and
2 Korth Henry repeating group of fields.
EMPLOYEES_PROJECTS_TIME
A table with fields containing too much data.
Employee ID Name Project Time
EN1-26 Sean O’Brien 30-452-T3, 30-457-T3, 32-244-T3 0.25, 0.40, 0.30
EN1-33 Amy Guya 30-452-T3, 30-382-TC, 32-244-T3 0.05, 0.35, 0.60
EN1-35 Steven Baranco 30-452-T3, 31-238-TC 0.15, 0.80
EN1-36 Elizabeth Roslyn 35-152-TC 0.90
EN1-38 Carol Schaaf 36-272-TC 0.75
EN1-40 Alexandra Wing 31-238-TC, 31-241-TC 0.20, 0.70
The example above is also related to another design issue, Why is this table design a problem?
namely, that each field should hold the smallest meaning- There would be no way to sort by last names or to know
ful value and that there should not be multiple values in a which allocation of time belonged to which project.
single field.
EMPLOYEES_PROJECTS_TIME
Table 5 A table with repeating groups of fields.
Emp ID Last Name First Name Project1 Time1 Project2 Time2 Project3 Time3
EN1-26 O’Brien Sean 30-452-T3 0.25 30-457-T3 0.40 32-244-T3 0.30
EN1-33 Guya Amy 30-452-T3 0.05 30-382-TC 0.35 32-244-T3 0.60
EN1-35 Baranco Steven 30-452-T3 0.15 31-238-TC 0.80
EN1-36 Roslyn Elizabeth 35-152-TC 0.90
EN1-38 Schaaf Carol 36-272-TC 0.75
EN1-40 Wing Alexandra 31-238-TC 0.20 31-241-TC 0.70
4.52 | Unit 4 • Databases
Functional Dependency
PROJECTS_EMPLOYEES_TIME A functional dependency is a relationship between fields so
that the value in Field A determines the value in Field B, and
Project Num EmployeeID Time there can be only one value in Field B. In that case, Field B
30-328-TC EN1-33 0.35 is functionally dependent on Field A. Consider the follow-
ing sample table:
30-452-T3 EN1-26 0.25
30-452-T3 EN1-33 0.05 Airport City
30-452-T3 EN1-35 0.15 National Washington, DC
If a ProjectTitle changed, we would have to edit it in containing the titles and an employee was assigned to only
several records. And what would happen in this table if the that project, you would also delete that employee’s record,
EmployeeID was part of the primary key and we wanted something that we may not want to do.
to add a new ProjectNum and ProjectTitle even though no In the above example, the asterisks indicate the fields
employees had yet been assigned? that make up the primary key of this table as it now stands.
The primary key cannot contain a null value so you A multifield primary key is necessary because neither the
couldn’t add the new project. Additionally, if a project EmployeeID nor the ProjectNum fields contain unique values.
ended and you wanted to delete it, you would have to delete The reason there are repeated values in LastName,
the individual values because, if we deleted the records FirstName, and ProjectTitle is that these fields are dependent
4.54 | Unit 4 • Databases
on only part of the primary key. The value in EmployeeID Now we’ll take the table above and design new tables
determines what the value in LastName will be, but the that will eliminate the repeated data in the non-key fields.
value in ProjectNum has nothing to do with it. Similarly, the
value in ProjectNum determines the value in ProjectTitle, 1. To decide what fields belong together in a table, think
but EmployeeID does not. These non-key fields relate to about which field determines the values in other fields.
only part of the primary key. They are not functionally Create a table for those fields and enter the sample data.
dependent on the entire primary key. 2. Think about what the primary key for each table would
The solution to this lies in breaking the table into smaller be and about the relationship between the tables. If
tables that do meet second normal form. You will find that necessary, add foreign keys or a junction table.
more tables are the solution to most problems encountered 3. Mark the primary key for each table and make sure
during data normalisation. that you don’t have repeating data in non-key fields.
EMPLOYEES PROJECTS
EmployeeID Last Name First Name Projec tNum Project Title
EN1-26 O’Brien Sean 30-452-T3 STAR manual
EN1-33 Guya Amy
30-457-T3 ISO procedures
EN1-35 Baranco Steven
30-482-TC Web site
EN1-36 Roslyn Elizabeth
31-124-T3 Employee handbook
EN1-38 Schaaf Carol
31-238-TC STAR prototype
EN1-40 Wing Alexandra
31-238-TC New catalog
35-152-TC STAR pricing
EmployeeID Project Num Examine the tables to make sure there are no repeating values
EN1-26 30-452-T3
in non-key fields and that the value in each non-key field is
determined by the value(s) in the key field(s). This removes
EN1-26 30-457-T3
the modification anomaly of having the repeated values.
EN1-26 31-124-T3
EN1-33 30-328-TC
EN1-33 30-452-T3 Third Normal Form
EN1-33 32-244-T3 A table is said to be in third normal form if it is in second
EN1-35 30-452-T3 normal form (2NF) and there are no transitive dependencies.
EN1-35 31-238-TC
A transitive dependency is a type of functional depend-
ency in which the value in a non-key field is determined
EN1-36 35-152-TC
by the value in another non-key field and that field is not a
EN1-38 36-272-TC candidate key. Again, look for repeated values in a non-key
EN1-40 31-238-TC field as in the following example.
EN1-40 31-241-TC
A table with a single field primary key and repeating
values in non-key fields.
The phone number is repeated each time a manager’s key). This normal form applies to situations where you have
name is repeated. It is dependent on the manager, which is overlapping candidate keys.
dependent on the project number (a transitive dependency). If a table has no non-key fields, it is automatically in
The Project Manager field is not a candidate key, because BCNF (Figure 1). Look for potential problems in updating
the same person manages more than one project. Again, the existing data (modification anomaly) and in entering new
solution is to remove the field with repeating data to a sepa- data (insertion anomaly).
rate table. Imagine that we were designing a table for a college
Take the above table and create new tables to fix the to hold information about courses, students, and teaching
problem. assistants. We have the following business rules:
1. Think about which fields belong together and create 1. Each course can have many students.
new tables to hold them. 2. Each student can take many courses.
2. Enter the sample data and check for unnecessarily 3. Each course can have multiple teaching assistants (TAs).
(not part of primary key) repeated values. 4. Each TA is associated with only one course.
3. Identify the primary key for each table and, if 5. For each course, each student has one TA.
necessary, add foreign keys. Some sample data:
COURSES_STUDENTS_TA’s
PROJECTS
CourseNum Student TA
Project Num Project Title Project Mgr
ENG101 Jones Clark
30-452-T3 STAR manual Garrison
ENG101 Grayson Chen
30-457-T3 ISO procedures Jacanda
ENG101 Samara Chen
30-482-TC Web site Friedman
MAT350 Grayson Powers
31-124-T3 Employee handbook Jones
MAT350 Jones O’Shea
31-238-TC STAR prototype Garrison
MAT350 Berg Powers
31-241-TC New catalog Jones
35-152-TC STAR pricing Vance To uniquely identify each record, we could choose
36-272-TC Order system Jacanda CourseNum + Student as a primary key. This would sat-
isfy third normal form also because the combination of
MANAGERS CourseNum and Student determines the value in TA.
Another candidate key would be Student + TA. In this case,
Project Manager Phone you have overlapping candidate keys (Student is in both).
Friedman 2846 The second choice, however, would not comply with third
Garrison 2756 normal form, because the CourseNum is not determined by
Jacanda 2954
the combination of Student and TA; it only depends on the
value in TA. This is the situation that Boyce-Codd normal form
Jones 3102
addresses; the combination of Student + TA could not be consid-
Vance 3022
ered to be a candidate key.
Reexamine your tables to make sure there are no unneces- If we wanted to assign a TA to a course before any stu-
sarily repeating values in non-key fields and that the value in dents enrolled, we couldn’t because Student is part of the
each non-key field is determined by the value(s) in the key primary key. Also, if the name of a TA changed, would
field(s). In most cases, 3NF should be sufficient to ensure have to update it in multiple records. If assume have just
that your database is properly normalised. these fields, this data would be better stored in three tables:
one with CourseNum and Student, another with Student
and TA, and third with CourseNum and TA.
Higher Normal Forms
COURSES
(Boyce–Codd Normal Form) Course Num Student
A table is in third normal form (3NF), and all determinants
ENG101 Jones
are candidate keys.
ENG101 Grayson
Boyce–Codd normal form (BCNF) can be thought of
ENG101 Samara
as a ‘new’ third normal form. It was introduced to cover
MAT350 Grayson
situations that the ‘old’ third normal form did not address.
The mean of a determinant (determines the value in another MAT350 Jones
field) and candidate keys (qualify for designation as primary MAT350 Berg
STUDENTS
4.56 | Unit 4 • Databases
Fourth Normal Form data maintenance problems that causes and you would have
trouble with deletion anomalies.
A table is in Boyce-Codd normal form (BCNF) and there
The Star and the Producer really aren’t logically related.
are no multi-valued dependencies.
The Movie determines the Star and the Movie determines
A multi-valued dependency occurs when, for each value
the Producer. The answer is to have a separate table for each
in field A, there is a set of values for field B and a set of val-
of those logical relationships: one holding Movie and Star
ues for field C but fields B and C are not related.
and the other with Movie and Producer, as shown below:
Look for repeated or null values in non-key fields. A multi-
valued dependency occurs when the table contains fields that
are not logically related. An often used example is the fol- STARS
lowing table: *Movie *Star
Once Upon a Time Julie Garland
MOVIES
Once Upon a Time Mickey Rooney
Movie Star Producer
Moonlight Humphrey Bogart
Once Upon a Time Julie Garland Alfred Brown
Moonlight Julie Garland
Once Upon a Time Mickey Rooney Alfred Brown
Once Upon a Time Julie Garland Muriel Humphreys PRODUCERS
Once Upon a Time Mickey Rooney Muriel Humphreys
*Movie *Producer
Moonlight Humphrey Bogart Alfred Brown
Once Upon a Time Alfred Brown
Moonlight Julie Garland Alfred Brown
Once Upon a Time Muriel Humphreys
A movie can have more than one star and more than one Moonlight Alfred Brown
producer. A star can be in more than one movie. A producer
can produce more than one movie. The primary key would Above, showing tables that comply with 4NF
have to include all three fields, and so this table would be in Below is another example of a common design error, and
BCNF. But you have unnecessarily repeated values, with the it’s easily spotted by all the missing or blank values.
PROJECTS_EQUIPMENT
Dept Code Project Num Project Mgr ID Equipment Property ID
IS 36-272-TC EN1-15 CD-ROM 657
IS VGA desktop monitor 305
AC 35-152-TC EN1-15
AC Dot-matrix printer 358
AC Calculator with tape 239
TW 30-452-T3 EN1-10 486 PC 275
TW 30-457-T3 EN1-15
TW 31-124-T3 EN1-15 Laser printer 109
TW 31-238-TC EN1-15 Handheld scanner 479
RI Fax machine 775
MK Laser printer 858
MK Answering machine 187
TW 31-241-TC EN1-15 Standard 19200 bps modem 386
SL 486 Laptop PC 772
SL Electronic notebook 458
Chapter 2 • Normalization | 4.57
A table with many null values (Note: It also does not com- A cyclic dependency can occur only when you have a
ply with 3NF and BCNF). multifield primary key consisting of three or more fields.
It is the same problem here because not all of the data is For example, let’s say your primary key consists of fields
logically related. As usual, the answer is more tables: one to A, B, and C. A cyclic dependency would arise if the val-
hold the information on the equipment assigned to depart- ues in those fields were related in pairs of A and B,
ments (with PropertyID as the primary key) and another B and C, and A and C.
with projects and departments. We would now the business Fifth normal form is also called projection-join normal
rules to know whether a project might involve more than form. A projection is a new table holding a subset of fields
one department or manager and be able to figure out the from an original table. When properly formed projections
primary key. Assuming a project can have only one man- are joined, they must result in the same set of data that was
ager and be associated with only one department, the tables contained in the original table.
would be as follows: Look for the number of records that will have to be added
or maintained
EQUIPMENT Following is some sample data about buyers, the prod-
ucts they buy, and the companies they buy from.
*Property ID Equipment DeptCode
657 CD-ROM IS BUYING
305 VGA desktop monitor IS
Buyer Product Company
358 Dot-matrix printer AC
Chris Jeans Levi
239 Calculator with tape AC
Chris Jeans Wrangler
275 486 PC TW
Chris Shirts Levi
109 Laser printer TW
Lori Jeans Levi
479 Handheld scanner TW
775 Fax machine RI Figure 3 A table with cyclic dependencies.
Figure 2 Tables that eliminate the null values and comply with PRODUCTS
4NF.
Product Company
jeans Wrangler
Fifth Normal Form jeans Levi
A table is in fourth normal form (4 NF) and there are no shirts Levi
cyclic dependencies.
4.58 | Unit 4 • Databases
However, if you joined the two tables above on the Product PRODUCTS
field, it would produce a record not part of the original data *Product *Company
set (it would say that Lori buys jeans from Wrangler). This jeans Wrangler
is where the projection-join concept comes in. jeans Levi
The correct solution would be three tables: shirts Levi
BUYERS
COMPANIES
*Buyer *Product *Buyer *Company
Chris jeans Chris Levi
Chris shirts Chris Wrangler
Lori jeans Lori Levi
Figure 4 Tables that comply with 5NF.
When the first two tables are joined by Product and the result joined to the third table by Buyer and Company, the result
is the original set of data.
Exercises
Practice Problems 1 Which functional dependencies are violating 2NF
Directions for questions 1 to 20: Select the correct alterna- property?
tive from the given choices. (A) FD1 (B) FD2
(C) FD3 (D) Both A and B
1. Consider the given functional dependencies
A→B 4. Consider the given relation
BC → DE EMPLOYEE-DEPARTMENT
AEF → G EName ENo DOB Address DNo. DName DManager
16. The given table is in the BCNF form, convert it to the 18. Which of the following FDs are satisfied by the instance
4th normal form. from the below relation:
8. Which one of the following is not possible? 16. For a database relation x(a, b, c, d), where all the
(A) Relation is in BCNF but not in 4NF domains of a, b, c, d, include only atomic values, only
(B) Relation is in 3NF but not in BCNF the following FDs and those that can be inferred from
(C) Relation is in 2NF but not in 3NF them hold.
(D) Relation is in 3NF but not in 2NF a → b, c → d
Common data for questions 9 and 10: Let R be a relation The relation is decomposed into R1(ab), R2(cd). Which of
schema R (A, B, C, D); the following is true, The decomposition
F = {AB → CD; C → A} F is the set of functional (A) is dependency preserving
dependencies (B) is not dependency preserving
9. How many prime attributes are there? (C) is loss less
(A) 1 (B) 2 (D) Both A and C
(C) 3 (D) 4 17. Which of the following FDs are satisfied by the instance
10. The highest normal form of the above relation is from the below relation?
(A) 1NF (B) 2NF A B C
(C) 3NF (D) 4NF
4 12 8
Linked answer questions 4 14 10
11. For a given relation schema R = {A, B, C, D, E} 4 16 10
A → BC
10 8 8
CD → E
B→D (A) AB → C and C → B
E→A (B) BC → A and B → C
Which of the following is not a candidate key? (C) BC → A and A → C
(A) A (B) B (D) AC → B and B → A
(C) E (D) BC 18. Indicate which of the following statements are false: ‘A
12. For the above answer, what is the closure? relational database, which is in 3NF still have undesirable
(A) BD (B) ABC data redundancy because there may exist.
(C) ABCDE (D) BC (A) Below all
13. Consider the following functional dependencies: (B) Non trivial FDs involving prime attributes on the
A→B right side.
C→D (C) Non-trivial FDs involving prime attributes on the
B→E left side
F→A (D) Non-trivial FDs involving only prime attributes
The relation (A, B, C, D) is 19. Consider the following database:
(A) in second normal form, but not in third normal form SOFTWARE (software-vendor, product, Release-date,
(B) in third normal form, but not in B C N F systemReq, warranty)
(C) in B C N F FD: (software-vendor, product, Releasedate) → system
(D) None of the above Req, price, Warranty.
Common data for questions 14 and 15: Which of the following are non–prime attributes?
R = (A, B, C, D, E, F ) (A) SystemReq
FDs = A → B (B) Price
C → DF (C) Warranty
AC → E (D) All the above
D→F 20. Consider a relation schema R (A, B, C, D, E, X, Y) with
14. Determine the key from the given FDs: the following FDs
(A) AB (B) AC F = {0 → A, XD → C, DA → B, A → X, XE → B, E →
(C) ACB (D) ACD A, B → D, DA → B, EB → C, AB → C, Y → B, C → B}
15. Decompose the FDs into 2NF is in
(A) R1(AB) R2(CDF) R3(ACE) (A) 2NF
(B) R1(AB) R2(CDEF) (B) 3NF
(C) R1(ABC) R2(CDF) (C) 4NF
(D) R1(AB) R2(CD) R3(EF ) (D) BCNF
4.62 | Unit 4 • Databases
attributes a21 and a22 of which a21 is the key attrib- 3 Bikaner 20
ute. E3 has two single-valued attributes a31 and a32 of 1 Churu 20
which a31 is the key attribute. The relationships do not 2 Churu 20
have any attributes. 1 Dungargarh 10
If a relational model is derived from the above ER The number of tuples returned by the following SQL
model, then the minimum number of relations that query is ______ .
would be generated if all the relations are in 3 NF is with total (name, capacity) as
_______.[2015] select district _ name, sum (capacity)
13. Consider the relation X(P, Q, R, S, T, U) with the fol- from water _ schemes
lowing set of functional dependencies group by district _ name
F = { with total _avg (capacity) as
select avg (capacity)
{P, R} → {S, T}
from total
{P, S, U} → {Q, R}
select name
}
from total, total _ avg
Which of the following is the trivial functional where total . capacity ≥ total_avg. capacity
dependency in F +, where F + is closure of F ?[2015] 16. The following functional dependencies hold true for
(A) {P, R} → {S, T} the relational schema R {V, W, X, Y, Z}:
(B) {P, R} → {R, T}
(C) {P, S} → {S} V →W
(D) {P, S, U} → {Q} VW → X
14. A database of research articles in a journal uses the Y → VX
following schema. [2016] Y→Z
(VOLUME, NUMBER, STARTPAGE, ENDPAGE, Which of the following is irreducible equivalent for
TITLE, YEAR, PRICE) this set of set of functional dependencies? [2017]
The primary key is (VOLUME, NUMBER, (A) V → W (B) V → W
STARTPAGE,ENDPAGE) and the following func- V → X W→X
tional dependencies exist in the schema. Y → V Y →V
(VOLUME, NUMBER, STARTPAGE, ENDPAGE) Y → Z Y→Z
→ TITLE (C) V → W (D) V → W
V → X W→X
(VOLUME, NUMBER) → YEAR Y → V Y →V
(VOLUME, NUMBER, Y → X Y→X
STARTPAGE,ENDPAGE) → PRICE Y → Z Y→Z
The database is redesigned to use the following 17. Consider the following tables T1 and T2.
schemas. T1 T2
(VOLUME, NUMBER, STARTPAGE, ENDPAGE, P Q R S
TITLE, PRICE)
2 2 2 2
(VOLUME, NUMBER, YEAR)
3 8 8 3
Which is the weakest normal form that the new data-
base satisfies, but the old one does not? 7 3 3 2
(A) 1NF (B) 2NF 5 8 9 7
(C) 3NF (D) BCNF
6 9 5 7
15. Consider the following database table water_
schemes:[2016] 8 5 7 2
water_schemes 9 8
scheme_no District name Capacity
In table T1, P is the primary key and Q is the foreign
1 Ajmer 20 key referencing R in table T2 with on-delete cascade
1 Bikaner 10 and on-update cascade. In table T2, R is the primary
2 Bikaner 10 key and S is the foreign key referencing P in table Tl
4.64 | Unit 4 • Databases
Answer Keys
Exercises
Practice Problems 1
1. A 2. A 3. D 4. B 5. B 6. B 7. C 8. D 9. B 10. A
11. C 12. D 13. A 14. B 15. A 16. D 17. A 18. B 19. C 20. C
Practice Problems 2
1. D 2. C 3. A 4. B 5. A 6. C 7. D 8. D 9. C 10. C
11. B 12. A 13. D 14. B 15. A 16. A 17. C 18. C 19. D 20. B
LEARNING OBJECTIVES
Atomicity Example:
It requires that all operations of a transaction be completed; UPDATE PRODUCT
if not, the transaction is aborted. Therefore, a transaction is SET PROD_QOH = PROD_QOH_100
treated as a single, logical unit of work. WHERE PROD_CODE = ‘345TYX’;
UPDATE ACCREC
SET AR_BALANCE = AR_BALANCE + 3500
Consistency WHERE AR_NUM = ‘60120010’;
It describes the result of the concurrent execution of COMMIT;
several transactions. The concurrent transactions are
treated as though they were executed in serial order. This
property is important in multiuser and distributed data-
Concurrency Control
base, where several transactions are likely to be executed The coordination of simultaneous execution of transactions
concurrently. in a multiprocessing database system is known as concur-
rency control. The objective of concurrency control is to
ensure the serializability of transaction in a multiuser data-
Isolation base environment. Concurrency is important, because the
It means that the data used during the execution of a simultaneous execution of transactions over a shared data-
transaction cannot be used by a second transaction until base can create several data integrity and consistency prob-
the first one is completed. Therefore, if a transaction T1 lems. Three main problems are lost updates, uncommitted
is being executed and is using the data item X1, that data data and inconsistent retrievals.
item cannot be accessed by any other transaction (T2…
Tn) until T1 ends. This property is particularly useful in Lost Updates
multiuser database environment, because several differ- Consider the following two concurrent transactions where
ent users can access and update the database at the same PROD_QOH represents a particular PRODUCT’s quantity
time. on hand. (PROD_QOH is an attribute in the Product table)
Chapter 4 • Transaction and Concurrency | 4.67
Assume the current PROD_QOH value for the product con- 2. At the same time, T2 updates the PROD_QOH for
cerned is 35. two of the PRODUCT table’s products (T2 represents
the correction of a typing error: the user added 30
Table 1 units to product 345TYX’s PROD_QOH but meant to
Transaction Computation
add the 30 units to 125TYZ’s PROD_QOH to correct
the problem, the user subtracts 30 from product
T1: purchase 100 units PROD_QOH = PROD_QOH + 100
345TYX’s PROD_QOH and adds 30 to product
T2: sell 30 units PROD_QOH = PROD_QOH - 30 125TYZ’s PROD_QOH).
Table 1 shows the serial execution of these transactions The computed answer 485 is obviously wrong, because we
under normal circumstances, yielding the correct answer: know the correct answer to be 455.
PROD_QOH = 105. But suppose that a transaction is able
to read a product’s PROD_QOH value from the table before
a previous transaction (using the same product) has been Transaction Processing Systems
committed. The sequence depicted in Table 2 shows how the Transaction processing systems are systems with large data-
cost update problem can arise. Note that the first transaction bases and hundreds of concurrent users that are executing
(T1) has not yet been committed when the second transaction database transactions. For example, banking, credit card
(T2) is executed. Therefore T2 still operates on the value 135 processing, stock markets, supermarket checkout, etc.
to disk which is promptly over written by T2. As a result, the They require high availability and fast response time for
addition of 100 units is “lost” during the process. hundreds of concurrent users.
1. A transaction includes one or more database access
Uncommitted Data operations. These can include insertion, deletion,
Data are not committed when two transactions, T1 and T2 are modification, or retrieval operations.
executed concurrently and the first transaction (T1) is rolled 2. Basic operations: The basic database access
back after the second transaction (T2) has already accessed operations that a transaction can include are as
the uncommitted data, thus violating the isolation property follows:
of transaction. Consider the same transactions from T1 and •• read_item (X): Reads a database item named X into
T2, from above. However, this time T1 is rolled back to elim- a program variable.
inate the addition of the 100 units. Because T2 subtracts 30 •• Write_item (X): Writes the value of program vari-
from the original 35 units, the correct answer should be 5. able X into the database item named X
Table 2 Executing a read_item (X): Command includes the follow-
ing steps:
Computation
1. Find the address of the disk block that contains item X
T1: purchase PROD_QOH = PROD_QOH + 100 (Rolled
100 units Back)
2. Copy that disk block into a buffer in main memory (if
that disk block is not in main memory buffer).
T2: sell PROD_QOH = PROD_QOH_30
30 units
3. Copy item X from the buffer to the program variable
named x
Table 2 shows how, under normal circumstances, the serial Executing a write_item (X) command includes the follow-
execution of these transactions yield the correct answer. The ing steps:
uncommitted data problem can arise when the ROLLBACK
is completed after T2 has begun its execution. 1. Find the address of the disk block that contains item X
2. Copy that disk block into a buffer in main memory (if
Inconsistent Retrievals that disk block is not in main memory buffer)
3. Copy item X from the program variable named X into
Inconsistent retrievals occur when a transaction calculates its correct location in the buffer
some summary (aggregate) functions over a set of data, 4. Store the updated block from the buffer back to
while other transactions are updating the data. The prob- disk.
lem is that the transaction might read some data before they
are changed and other data after they are changed, thereby Step 4 actually updates the database on disk.
yielding inconsistent results. The decision about when to store back a modified disk
Example: block that is in a main memory buffer is handled by the
recovery manager of the DBMS in cooperation with the
1. T1 calculates the total PROD_QOH of the products underlying operating system.
stored in the PRODUCT table
4.68 | Unit 4 • Databases
READ / WRITE
BEGIN COMMIT
END
ACTIVE PARTIALLY COMMITTED
ABORT ABORT
FAILED TERMINATED
For the purpose of recovery, the system needs to keep track Concurrency Control with
of when the transaction starts, terminates, and commits or
aborts. Hence, the recovery manager keeps track of the fol- Locking Methods
lowing operations: A lock guarantees exclusive use of a data item to a transac-
tion. In general, if transaction T1 holds a lock on a data item
1. BEGIN_TRANSACTION: It shows the beginning (e.g., an employee’s salary) then transaction T2 does not
of Execution of a transaction. have access to that data item. A transaction acquires a lock
2. READ/WRITE: These specify read or write prior to data access; the lock is released (unlocked) when
operations on the database items. the transaction is completed, so that another transaction can
3. END_TRANSACTION: This specifies that READ lock the data item for its exclusive use. All lock informa-
and WRITE operations have ended and marks the end tion is managed by a lock manager, which is responsible for
of transaction execution. assigning and policing the locks used by the transactions.
4. COMMIT_TRANSACTION: This shows a
successful end of the transaction so that any changes
executed by the transaction can be safely committed Lock Granularity
to the database and will not be undone. Lock granularity indicates the level of lock use. Locking
5. ROLL BACK OR ABORT: This shows that the can take place at the following levels: database level, table
transaction has ended unsuccessfully, so that any level, page level, row level and field (or attribute) level.
changes or effects that the transaction may have
applied to the database must be undone.
Database Level
6. ACTIVE STATE: A transaction goes into an active
state immediately after it starts execution where it can In a database-level lock, the entire database is locked, thus
issue READ and WRITE operations. preventing the use of any tables in the database by transaction
7. PARTIALLY COMMITTED: When the transaction T2 while transaction T1 is being executed. Transaction T1 and
ends, it moves to the partially committed state T2 cannot access the database concurrently, even if they use
8. COMMIT: A transaction reaches its commit point different tables. This level of locking is suitable for batch pro-
when all its operations that access the database cesses, but it is not unsuitable for online multiuser DBMSs.
have been executed successfully, and the effect of
all the transaction operations on the database have Table Level
been recorded in the log. Beyond the commit point, In a table-level lock, the entire table is locked, preventing
the transaction is said to be committed, and its access to any row by transaction T2 while transaction T1 is
effect is assumed to be permanently recorded in the using Table 2 transactions can access the same database, as
database. long as they access different tables. Transactions T1 and T2
9. FAILED_STATE: A transaction can go to the failed cannot access the same table even if they try to use different
state if the transaction is aborted during its active rows, T2 must wait until T1 unlocks the table.
state. The transaction may then have to be rolled back
to undo the effect of its WRITE operations on the
database. Page level
10. TERMINATIED: The terminated state corresponds In a page level lock, the DBMS will lock an entire disk page (a
to the transactions leaving the system. disk page or page is the equivalent of a disk block, which can
Chapter 4 • Transaction and Concurrency | 4.69
Using the shared/exclusive locking concept, a lock can a big city and are caused when two transactions wait
have three states: unlocked, shared (READ) and exclusive for each other to unlock data.
(WRITE). 2 READ transactions can be safely executed and Both problems can be solved. Serializability is guaranteed
shared locks allow several READ transactions to concurrently through a locking protocol known as two-phase locking and
read the same data item. For example, if transaction T1 has a deadlocks can be eliminated by using deadlock detection, and
shared lock on data item X, and transaction T2 wants to read prevention techniques. We shall examine these techniques next.
data item X, T2 may also obtain a shared lock on data item X.
If transaction T2 updates data item X, then an exclusive
lock is required by T2 over data item X. The exclusive lock Two-phase Locking to Ensure
is granted if and only if no other locks are held on the data Serializability
item. Therefore, if a shared or exclusive lock is already held The two-phase locking protocol defines how transactions
on data item X by transaction T1, an exclusive lock cannot acquire and relinquish locks. It guarantees serializability, but
be granted to transaction T2. it does NOT prevent deadlocks. The two phases are as follows:
1. A growing phase, in which a transaction acquires all
Potential problems with locks the required locks without unlocking any data. Once
Although locks prevent serious data inconsistencies, their all locks have been acquired, the transaction is in its
use may lead to two major problems: locked point.
2. A shrinking phase, in which a transaction releases all
1. The resulting transaction schedule may not be
locks and cannot obtain any new lock.
serializable.
2. The schedule may create deadlocks. Database The two-phase locking protocol is governed by the follow-
deadlocks are the equivalent of a traffic gridlock in ing rules”
4.70 | Unit 4 • Databases
Deadlocks exist when two transactions, T1 and T2, exist in Transaction T1 is waiting for Y which is locked by Transaction
the following mode: T2 and transaction T2 is waiting for z which is locked by
1. T1 would like to access data item X and then data transaction T1. The below graph is called wait for graph.
item Y. (So far, T1 has locked data item X and T1 is in
Y
progress, it will eventually require to lock data item Y.)
2. T2 needs to access data items X and Y, to begin. (So T1 T2
far, T2 has locked data item Y.)
If T1 has not unlocked data item X, T2 cannot begin; if Z
T2 has not unlocked data item Y, T1 cannot continue.
Consequently, T1 and T2 wait indefinitely, each waiting for Deadlock Prevention
the other to unlock the required data item. Such in a real- There are number of deadlock prevention schemes that make
world DBMS, many transactions can be executed simulta- a decision about what to do with a transaction involved in a
neously, thereby increasing the probability of generating possible deadlock situation:
deadlocks. Note that deadlocks are possible only if one
of the transactions wants to obtain an exclusive lock on a 1. Should it be blocked and made to wait
data item; no deadlock condition can exist among shared 2. Should it be aborted
locks. 3. Should the transaction pre-empt and abort another
Three basic techniques exist to control deadlocks: transaction.
The rules followed by these schemes are as follows: Two-phase Locking Theorem
1. Wait-die: If Ts (Tk) < Ts (TL), then (Tk older than TL) If all transactions obey the two phase locking protocol, then
Tk is allowed to wait; otherwise (Tk younger than TL) all possible interleaved schedule are serializable.
abort Tk and restart it later with the same time stamp 1. Before operating on any object (it could be a database
2. Wound-wait: If Ts (Tk) < Ts (TL) then (Tk older than tuple), a transaction must acquire a lock on the object
TL) abort TL and restart it later with the same time 2. After releasing a lock, a transaction must never go on
stamp; otherwise (Tk younger than TL) Tk is allowed to to acquire any more locks.
wait A transaction that obeys this protocol thus has two
Both schemes end up aborting the younger of the two phases: a lock acquisition or “growing phase and a lock
transactions that may be involved in a deadlock releasing or “shrinking” phase
Let ‘I’ be an interleaved schedule involving some set of
transactions T, T2, T3, . . . Tn.
Concurrency Control with
If ‘I’ is serializable, then there exists at least one serial
Optimistic Methods schedule ‘S’ involving T1, T2, . . . Tn such that ‘I’ is equivalent
Optimistic methods are based on the assumption that the to ‘S’ is said to be a serialization of ‘I’
majority of the database operations do not conflict. A trans- Let Ti and Tj be any two distinct transactions in the set
action is executed without restrictions until it is committed. T1, T2, T3, . . . Tn. Let Ti precede Tj in the serialization ‘S’. In
Each transaction moves through two or three phases: the interleaved schedule I, then the effect must be as if Ti
Read phase: The transaction reads the database, executes really did execute before Tj. In other words, if A and B are
the needed computations, and makes the updates to a pri- any two transactions involved is some serializable schedule,
vate copy of the database values. then either A logically precedes B or B logically precedes A
in that schedule, that is, either B can see A’s output or A can
Validation phase: The transaction is validated to assure that see B’s. If the effect is not as if either A ran before B or B ran
the changes made will not affect the integrity and consist- before A, then the schedule is not serializable and not correct.
ency of the database.
If the validation test is positive, transaction goes to the 1. A schedule ‘S’ of ‘n’ transactions T1, T2 . . . Tn is an
Write Phase. ordering of the operations of the transactions subject
If the validation test is negative, transaction is restarted, to the constraint that, for each transaction Ti that
and changes are discarded. participates in ‘S’, the same order in which they occur
Write phase: The changes are permanently applied to the in Ti.
database. 2. For the purpose of recovery and concurrency control,
we are mainly interested in the ‘read item’ and ‘write
item’ operations of the transactions, as well as the
Serializability COMMIT and ABORT operations. A shorthand
Serializabilty is accepted as ‘criterion for correctness’ for notation for describing a schedule uses the symbols,
the interleaved execution of a set of transactions, such an ‘R’, ‘W’, ‘C’ and ‘A’ for the operations read item, write
execution is considered to be correct if and only if it is item, commit, and abort respectively, and appends as
serializable. subscript the transition-id (transaction number) to
each operation in the schedule
1. A set of transactions is serializable if and only if it
is equivalent to some serial execution of the same Example: The schedule of the given set of transactions can
transactions be written as follows:
2. A serial execution is one in which the transactions are T1 T2
run one at a time in some sequence Read item (x);
Schedule: Given a set of transactions, any execution of those X = X – N;
transactions interleaved or otherwise is called a schedule. Read item (x);
S1 S2
Read item (x); Read item (x)
Algorithm
1. For each transaction Ti participating in schedule S,
X = X + 20; X = X * 1.1;
create a node labelled Ti in the precedence graph
Write item (x); Write item (x);
2. For each case in S where Tj executes a read item (x)
after Ti executes a write item (x), create an edge (Ti →
Solution: Tj) in the graph
Schedules S1 and S2 will produce the same final database 3. For each case in S where Tj executes a write item (x)
state if they execute on a database with an initial value of x after Ti executes a read item (x), create an edge (Ti →
= 200; but for other initial values of x, the schedules are not Tj) in the graph
result equivalent 4. For each case in S where Tj executes a write item (x)
For two schedules to be equivalent, the operations after Ti executes a write item (x), create an edge (Ti →
applied to each data item affected by the schedules should Tj) in the precedence graph
be applied to that item in both schedules in the same order. 5. The schedule S is serializable, if the precedence graph
The other two definitions of equivalence of schedules gen- contains no cycles
erally used are conflict equivalence and view equivalence
A cycle in a directed graph is a sequence of edges C = ((Tj
Conflict Equivalence → Tk), (Tk → Tp), . . . (Ti → Tj))
With the property that the starting node of each edge,
Two schedules are said to be conflict equivalent if the order
except the first edge is the same as the ending node of the
of any two conflicting operations is the same in both sched-
previous edge, and the starting node of the first edge is the
ules. If two conflicting operations are applied in different
same as the ending node of the last edge.
orders in two schedules, the effect can be different on the
database or on other transactions in the schedule, and hence Example: Check whether the given schedule is conflict
the schedules are not conflict equivalent. serializable or not by drawing precedence graph:
4.74 | Unit 4 • Databases
Exercises
Practice Problem 1 3. Consider the three data items D1, D2 and D3 and the
Directions for questions 1 to 20: Select the correct alterna- following execution of schedules of transactions T1, T2
tive from the given choices. and T3:
1. Consider the given schedules S1 and S2
T1 T2 T3
S1: r1(x), r1(y), r2(x), r2(y), w2(y), w1(x)
R(D2)
S2: r1(x), r2(x), r2(y), w2(y), r1(y), w1(x)
R(D2)
Which schedule is conflict serializable?
W(D2)
(A) S1 (B) S2
R(D2)
(C) S1 and S2 (D) None of these
R(D3)
2. Consider the given schedule with three transactions T1,
T2 and T3: R(D1)
T1 T2 T3 W(D1)
r1(x) W(D2)
r2(y) W(D3)
r3(y) R(D1)
w2(y) R(D2)
w1(x) W(D2)
w3(x) W(D1)
r2(x)
Which of the following is true?
w2(x)
(A) The schedule is conflict serializable
Which of the following is correct serialization? (B) The schedule is not conflict serializable
(A) T2 → T1 → T3 (B) T1 → T3 → T2 (C) The schedule has deadlock
(C) T3 → T1 → T2 (D) None of these (D) Both (A) and (C)
Chapter 4 • Transaction and Concurrency | 4.75
T1 T2
read-item(x)
(B) T3 T7 T4
x=x–N
read-item(x)
x=x+M
Write-item(x)
(C) T7 T4 T3
read-item(y)
Write-item(x)
y=y+N
Write-item(y)
(D) T3 T4 T7
(A) 220, 110 (B) 210, 120
(C) 220, 120 (D) 210, 110
5. Consider two Transactions T1 and T2 and four sched- 8. For the above data, if the transactions are executed in
ules: S1, S2, S3 and S4 of T1 and T2: serial manner, what would be the values of X and Y at
the end of the serial execution of T1 and T2?
T1: r1(x), w1(x), w1(y)
T2: r2(x), r2(y), w2(y) T1 T2
S1: r1(x), r2(x), r2(y), w1(x), w1(y), w2(y) Read-item(x)
S2: r1(x), r2(x), r2(y), w1(x), w2(y), w1(y) X=X–N
S3: r1(x), w1(x), r2(x), w1(y), r2(y), w2(y) Write-item(x)
S4: r2(x), r2(y), r1(x), w1(x), w1(y), w2(y) Read-item(y)
Which schedules are conflict serializable in the given Y=Y+N
schedules? Write-item(y)
(A) S1 and S2 Read-item(x)
(B) S1 and S3
X=X+M
(C) S2 and S3
Write-item(x)
(D) S1 and S4
6. Consider the following transactions with data items P (A) 190, 120
and Q initialized to ‘0’: (B) 180, 120
T1: read(P) (C) 190, 110
Read(Q) (D) 180, 110
if p = 0 then Q = Q + 1 9. Consider the given two transactions T1 and T2:
Write(Q) T1: r1(x), w1(x), r1(y)
4.76 | Unit 4 • Databases
T2: r2(x), r2(y), w2(x), w2(y) (A) r3(x), r3(y), w3(y), r1(x), r1(z), w1(x), r2(z), r2(y),
Which of the following schedules are complete schedules? w2(z), w2(y)
(A) r1(x), r2(x), w1(x), r1(y), r2(y), w2(x), w2(y) (B) r1(x), r1(z), w1(x), r2(z), r2(y), w2(z), w2(y), r3(x),
(B) r2(x), r1(x), r2(y), w1(x), w2(x), r1(y), w2(y) r3(y), w3(y)
(C) r1(x), r1(y), r2(x), r2(y), w1(x), w2(x), w2(y) (C) r2(z), r2(y), w2(z), w2(y), r3(x), r3(y), w3(y), r1(x),
(D) All the above r1(z), w1(x)
(D) r2(z), r2(y), w2(z), w2(y), r1(x), r1(z), w1(x), r3(x),
10. Consider the given schedule with data-locks on data-
r3(y), w3(y)
items, check whether it has dead-lock or not. The locks
are shared-lock(S) and Exclusive-lock(X). Shared-lock 13. Consider schedule S3, which is a combination of transac-
is also called Read-lock, Exclusive-lock is also called tions T1, T2 and T3 from Q. No.11.
Write-lock. Read and Write operations are denoted by S3: r1(x), r2(z), r1(z), r3(x), r3(y), w1(x), c1, w3(y), c3,
R and W, respectively. r2(y), w2(z), w2(y), c2?
Which of the following is true?
T1 T2 T3 T4
(A) Recoverable and conflict serializable
S(A)
(B) Recoverable but not conflict serializable
R(A) (C) Conflict serializable but not Recoverable
X(B) (D) Not recoverable and not conflict serializable
W(B) 14. Consider the given schedule:
S(B) S4: r1(x), r2(z), r1(z), r3(x), r3(y), w1(x), w3(y), r2(y),
S(C) w2(z), w2(y), c1, c2, c3:
R(C) Which of the following is true?
X(C) (A) Recoverable and conflict serializable
X(B) (B) Recoverable but not conflict serializable
(C) Conflict serializable but not Recoverable
X(A)
(D) Not recoverable and not conflict serializable
Which of the following is incorrect? 15. Which of the following is correct for the below com-
(A) T1 → T2 (B) T3 → T1 patibility matrix?
(C) T2 → T3 (D) T4 → T3
Mode of Locks Shared-Lock Exclusive-Lock
11. Consider the three transactions T1, T2 and T3 and the Currently held by
schedule S1 as given below. Draw the serializability other S
(precedence) graph for S1, and state whether the sched- transactions
X
ule is serializable or not. If a schedule is serializable,
which one of the following is equivalent serial schedule? S – shared - Lock, X – Exclusive - Lock
T1: r1(x), r1(z), w1(x) (A)
T2: r2(z), r2(y), w2(z), w2(y) S X
T3: r3(x), r3(y), w3(y)
S No No
S1: r1(x), r2(z), r1(z), r3(x), r3(y), w1(x), w3(y), r2(y), X Yes No
w2(z), w2(y)? (B)
(A) r3(x), r3(y), w3(y), r1(x), r1(z), w1(x), r2(z), r2(y),
S X
w2(z), w2(y)
(B) r1(x), r1(z), w1(x), r2(z), r2(y), w2(z), w2(y), r3(x), S Yes No
r3(y), w3(y) X No No
(C) r2(z), r2(y), w2(z), w2(y), r3(x), r3(y), w3(y), r1(x),
(C)
r1(z), w1(x)
(D) r2(z), r2(y), w2(z), w2(y), r1(x), r1(z), w1(x), r3(x), S X
r3(y), w3(y) S Yes Yes
12. Consider the data given in the above question. Draw the X No No
precedence graph for S2 and state whether each sched-
(D)
ule is serializable or not. If a schedule is serializable,
which of the following is equivalent serial schedule? S X
S2: r1(x), r2(z), r3(x), r1(z), r2(y), r3(y), w1(x), w2(z), S No Yes
w3(y), w2(y) X No No
Chapter 4 • Transaction and Concurrency | 4.77
p
Practice Problem 2 (B) Each leaf node has at most values.
2
Directions for questions 1 to 20: Select the correct alterna- (C) Each internal node, except the root, has at least
tive from the given choices.
p
1. Which of the following is false with respect to B+ - 2 tree pointers.
trees of order p?
(A) Each internal node has at most p tree pointers. (D) All leaf nodes are at same level.
4.78 | Unit 4 • Databases
T1 T2 LIST I LIST II
(A) Undo: T3, T1; Redo: T2 (A) guarantee serializability and deadlock-freedom.
(B) Undo: T3, T1; Redo: T2, T4 (B) guarantee neither serializability nor deadlock-
(C) Undo: none; Redo: T2, T4, T3, T1 freedom.
(D) Undo: T3, T1, T4; Redo: T2 (C) guarantee serializability but not deadlock-free-
5. Consider the following partial schedule S involving dom.
two transactions T1 and T2. Only the read and the write (D)
guarantee deadlock-freedom but not serializa-
operations have been shown. The read operation on bilty.
data item P is denoted by read(P) and the write opera- 8. Suppose a database schedule S involves transactions
tion on data item P is denoted by write(P) T1,….Tn. Construct the precedence graph of S with
vertices representing the transactions and edges rep-
resenting the conflicts. If S is serializable, which one
Transaction – id of the following orderings of the vertices of the prec-
Time Instance T1 T2 edence graph is guaranteed to yield a serial schedule?
1 read(A) [2016]
2 write(A)
(A) Topological order
(B) Depth - first order
3 read(C)
(C) Breadth - first order
4 write(C) (D) Ascending order of transaction indices
5 read(B) 9. Consider the following database schedule with two
6 write(B) transactions T1 and T2.
7 read(A) S = r2(X); r1(X); r2(Y); w1(X); r1(Y); w2(X); a1;a2
8 commit Where ri (Z) denotes a read operation by transaction
9 read(B) Ti on a variable Z, wi(Z) denotes a write operation by
Schedule S Ti on a variable Z and ai denotes an abort by transac-
Suppose that the transaction T1 fails immediately after tion Ti.
time instance 9. Which one of the following state- Which one of the following statements about the
ments is correct? [2015] above schedule is TRUE? [2016]
(A) T2 must be aborted and then both T1 and T2 must (A) S is non - recoverable
be re-started to ensure transaction atomicity. (B) S is recoverable, but has a cascading abort
(B) Schedule S is non-recoverable and cannot ensure (C) S does not have a cascading abort
transaction atomicity. (D) S is strict.
(C) Only T2 must be aborted and then re-started to 10. In a database system, unique timestamps are assigned
ensure transaction atomicity. to each transaction using Lamport’s logical clock. Let
(D) Schedule S is recoverable and can ensure atomic- TS(T1) and TS(T2) be the timestamps of transactions
ity and nothing else needs to be done. T1 and T2 respectively. Besides, T1 holds a lock on the
6. Which one of the following is NOT a part of the resource R, and T2 has requested a conflicting lock on
ACID properties of database transactions? [2016] the same resource R. The following algorithm is used
(A) Atomicity to prevent deadlocks in the database system assum-
(B) Consistency ing that a killed transaction is restarted with the same
(C) Isolation timestamp.
(D) Deadlock - freedom if TS(T2) < TS(T1) then
7. Consider the following two phase locking protocol. T1 is killed
Suppose a transaction T accesses (for read or write else T2 waits.
operations), a certain set of objects {O1, ….. , Ok). Assume any transaction that is not killed terminates
This is done in the following manner: [2016] eventually. Which of the following is TRUE about the
Step 1. T acquires exclusive locks to O1,….Ok in database system that uses the above algorithm to pre-
increasing order of their addresses. vent deadlocks? [2017]
(A) The database system is both deadlock-free and
Step 2. The required operations are performed. starvation-free.
Step 3. All locks are released. (B) The database system is deadlock-free, but not
This protocol will starvation-free.
Chapter 4 • Transaction and Concurrency | 4.81
(C) The database system is starvation-free, but not T2 : r2 (Y)w2 (Y)r2 (Z)w2 (Z)
deadlock-free. where ri (V) denotes a read operation by transaction
(D) The database system is neither deadlock-free nor Ti on a variable V and wi (V) denotes a write operation
starvation-free. by transaction Ti on a variable V. The total number of
11. Two transactions T1 and T2 are given as conflict serializable schedules that can be formed by
T1 : r1(X)w1 (X)r1 (Y)w1 (Y) T1 and T2 is _______. [2017]
Answer Keys
Practice Problem 1
1. B 2. B 3. B 4. B 5. C 6. B 7. B 8. A 9. A 10. D
11. A 12. A 13. A 14. C 15. B 16. D 17. C 18. D 19. B 20. D
Practice Problem 1
1. B 2. A 3. A 4. D 5. A 6. B 7. B 8. B 9. D 10. C
11. B 12. B 13. B 14. B 15. D 16. D 17. C 18. D 19. A 20. D
LEARNING OBJECTIVES
files Index files These files are used to access a record in the file. The
entire index file is loaded into main memory data and indexes are
Databases are stored on magnetic disks as files of records.
stored in the same file. The term ‘index file’ is used as a synonym
Computer storage media form a storage hierarchy that includes
for the term ‘database file’. The index file contains parameters that
two main categories.
specify the name and location of file used to store DB.
Primary storage This category includes storage media that can be
Indexing Indexing mechanism is used to speed up access to
operated on, directly by CPU, such as the computer main memory
desired data. An index file consists of records (called index entries)
and cache memory. Primary storage provides fast access but is of
of the form.
limited storage capacity.
Search-key Pointer
Secondary storage This category includes magnetic disks, optical
disks, and tapes. These devices usually have a larger capacity, less Index files are typically much smaller than the original file.
cost, and slower access to data. Data in secondary storage cannot
be processed directly by the CPU, it must be copied into primary Ordered indices In ordered index, index entries are stored, sorted
storage. on the search-key value.
Example: Author catalogue in library.
File Structure
Taxonomy of file structure MeMorY HierarcHies
At the primary storage level, the memory hierarchy includes cache
Files memory which is a static RAM.
access methods The next level of primary storage is DRAM (dynamic RAM)
which provides the main work area for the CPU for keeping pro-
Sequential Random
grams and data and is called the main memory.
At the secondary storage level, the hierarchy includes magnetic
Index file Hashed file disks, as well as mass storage in the form of CD-ROM (compact
Sequential file
disk read-only memory) and tapes. Programs reside in DRAM and
large permanent databases reside on secondary storage.
Sequential file A sequential file is one in which records can only Another form of memory, flash memory, is non-volatile.
be accessed sequentially, one after another from beginning to end. Flash memories are high-density, high-performance memories
Records are stored contiguously on the storage device. using EEPROM (electrically erasable programmable read-only
Chapter 5 • File Management | 4.83
memory) technology. The advantage of flash memory is the Record type A collection of field names and their correspond-
fast access speed, the disadvantage is that an entire block ing data types constitutes a record type (or) record format.
must be erased and written over at a time. Finally, magnetic A file is a sequence of records. If every record in the
tapes are used for archiving and backup storage of data. file has exactly the same size (in bytes), the file is said to
be made up of fixed-length records. If different records in
the file have different sizes, the file is said to be made up of
Description of Disk Devices variable-length records.
Magnetic disks are used for storing large amounts of data.
The capacity of a disk is the number of bytes it can store. A Spanned Versus Unspanned Records
disk is single sided if it stores information on only one of
The records of a file must be allocated to disk blocks because
its surfaces and double sided if both surfaces are used. To
a block is the unit of data transfer between disk and memory.
increase storage capacity, disks are assembled into a disk
When the block size is larger than the record size, each block
pack, which may include many disks and hence many sur-
will contain numerous records, although some files may
faces. Information is stored on a disk surface in concentric
have unusually large records that cannot fit in one block.
circles with small width, each having a distinct diameter.
Suppose that the block size is B bytes. For a file of fixed-
Each circle is called a track. For disk packs, the tracks with
length records of size R bytes, with B ≥ R, we can fit
the same diameter on the various surfaces are called a cyl-
inder because of the shape they would form if connected in bfr = ⎣B/R⎦ records per block
space.
The value bfr is called the blocking factor for the file. Some
A track usually contains a large amount of information;
times R may not divide B exactly, so we have some unused
it is divided into smaller blocks (or) sectors. The division
space in each block equal to B – (bfr * R) bytes. To uti-
of track into equal-sized disk blocks (or pages) is set by the
lize this unused space, we can store part of a record on one
operating system during disk formatting.
block and the rest on another. A pointer at the end of the
Blocks are separated by fixed-size inter-block gaps,
first block points to the block containing the remainder of
which include specially coded control information writ-
the record in case it is not the next consecutive block on
ten during disk initialization. This information is used
disk. This organization is called spanned, because records
to determine which block on the track follows each inter
can span more than one block. Whenever a record is larger
block gap. Transfer of data between main memory and
than a block, we must use a spanned organization. If records
disk takes place in units of disk blocks. The hardware
are not allowed to cross block boundaries, the organization
address of a block is the combination of a cylinder num-
is called unspanned. This is used with fixed-length records
ber, track number and block number is supplied to the disk
having B > R, because it makes each record start at a known
I/O hardware.
location in the block. For variable-length records, either a
The actual hardware mechanism that reads or writes a
spanned or an unspanned organization can be used.
block is the disk read/write head, which is part of a sys-
For variable-length records using spanned organization,
tem called a disk drive. A disk is mounted in the disk drive,
each block may store a different number of records. In this
which includes a motor that rotates the disk. To transfer a
case, the blocking factor bfr represents the average number
disk block, given its address, the disk controller must first
of records per block for the file. We can use bfr to calculate
mechanically position the read/write head on the correct
the number of blocks ‘b’ needed for a file of ‘r’ records.
track. The time required to do this is called the seek time.
b = ⎡(r/bfr)⎤ blocks
There is another delay called rotational delay or latency; the
beginning of the desired block rotates into position under Block x Record 1 Record 2 Record 3
the read/write head. It depends on the RPM of the disk.
Finally, some additional time is needed to transfer the data, Block x + 1 Record 4 Record 5
which is called block-transfer time. Hence, the total time
needed to locate and transfer an arbitrary block, given its Figure 1 Unspanned records
address is the sum of the seek time, rotational delay and
block transfer time. The seek time and rotational delay are Block x Record 1 Record 2 Record 3 Record 4 P
usually much larger than the block transfer time.
Data is usually stored in the form of records. Each record Figure 2 Spanned
consists of a collection of related data values or items where
each value is of one or more bytes and corresponds to a There are several standard techniques for allocating the
particular field of the record. Records describe entities and blocks of a file on disk. In contiguous allocation, the file
their attributes. blocks are allocated to consecutive disk blocks. In linked
4.84 | Unit 4 • Databases
allocation, each file block contains a pointer to the next Hashing Techniques
file block. A combination of the two allocates clusters
The other type of primary file organization is based on
of consecutive disk blocks, and the clusters are linked.
hashing, which provides very fast access to records on cer-
Clusters are sometimes called file segments (or) extents.
tain search conditions. This organization is usually called a
Another possibility is to use indexed allocation, where
hash file.
one or more index blocks contain pointers to the actual
The search condition must be an equality condition on
file blocks.
a single field, called the hash field of the file. If the hash
is also a key field of the file, in which case it is called the
Sorted Files (Ordered Records) hash key.
We can physically order the records of a file on disk based The idea behind hashing is to provide a function ‘h’,
on the values of the one of their fields called the ordering called a hash function or randomizing function, which is
field. This leads to an ordered or sequential file. If the order- applied to the hash field value of a record and yields the
ing field is also a key field of the file, a field guaranteed to address of the disk block in which the record is stored. We
have a unique value in each record, then the field is called need only a single-block access to retrieve that record.
the ordering key for the file. Example:
Chaining For this method, various overflow locations blocks. The hashing function maps a key into a relative
are kept, usually by extending the array with a number of bucket number, rather than assigning an absolute block
overflow positions. In addition, a pointer field is added to address to the bucket. A table maintained in the file header
each record location. A collision is resolved by placing the converts the bucket number into the corresponding disk
new record in an unused overflow location and setting the block address.
pointer of the occupied hash address location to the address The collision problem is less severe with buckets,
of that overflow location. A linked list of overflow records because as many records as will fit in a bucket can hash to
for each hash address is thus maintained. the same bucket without causing problems. If the capacity
of bucket exceeds, we can use a variation of chaining in
Multiple hashing The program applies a second hash which a pointer is maintained in each bucket to a linked
function if the first results in a collision. If another collision list of overflow records for the bucket. The pointers in the
results, the program uses open addressing or applies a third linked list should be record pointers, which include both
hash function and then uses open addressing if necessary. a block address and a relative record position within the
If we expect to have ‘r’ records to store in the table, we block.
should choose M locations for the address space such that
(r/M) is between 0.7 and 0.9. It may also be useful to choose
a prime number for M, since it has been demonstrated that Block
address
this distributes the hash addresses better over the address on disk
space when the ‘mod’ hashing function is used. Other hash 0 . . . . .
functions may require M to be a power of 2. 1
2 . . . . .
Bucket . .
External Hashing number .
.
.
.
.
.
. .
.
.
Hashing for disk files is called external hashing. To suit the . . .
n −2
characteristics of disk storage, the target address space is . . . . .
n −1
made of buckets, each of which holds multiple records. A
bucket is either one disk block or a cluster of contiguous
Bucket 0
22
Overflow
31
86 Record pointer
Record pointer
Record pointer
25 Record pointer
Bucket 1 NULL
62
74 Record pointer
57
81
Record pointer
Record pointer
Record pointer
Bucket 2
32
62
Record pointer
The hash function is h(k) = k mod 10 and the hashing records will fit in the allocated space. If the number of
scheme described above is called static hashing because a records turns out to be substantially fewer than (m * M), we
fixed number of buckets M is allocated. It can be a draw- are left with a lot of unused space.
back for dynamic files. Suppose that we allocate M buckets If the number of records increases to substantially more
for the address space and let ‘m’ be the maximum number than (m * M), numerous collisions will result and retrieval
of records that can fit in one bucket, then at most (m * M) will be slowed down because of the long lists of overflow
4.86 | Unit 4 • Databases
records. In either case, we may have to change the number The value of d can be increased and decreased by one at a
of blocks M allocated and then use a new hashing function time, thus doubling or halving the number of entries in the
(based on the new value of M) to redistribute the records. directory array. Doubling is needed if a bucket, whose local
These organizations can be quite time consuming for large depth d′ is equal to the global depth d, overflows. Halving
files. Newer dynamic file organizations based on hashing occurs if d > d′ for all the buckets after some locations
allows the number of buckets to vary dynamically with only occur. Most record retrievals require two block accesses:
localized reorganization. one to the directory and the other to the bucket.
The main advantage of extendible hashing is the per-
Hashing Techniques with Dynamic formance of the file does not degrade as the file grows,
File Expansion as opposed to static external hashing where collisions
increases and the corresponding chaining causes addi-
The disadvantage of static hashing is that the hash address
tional accesses. No space is allowed in extendible hashing
space is fixed. Hence, it is difficult to expand or shrink the
for future growth, but additional buckets can be allocated
file dynamically. The first scheme is extendible hashing, It
dynamically as needed. The space overhead for the direc-
stores an access structure in addition to the file hence it is
tory table is negligible.
similar to indexing. The main difference is that the access
Another advantage is that splitting causes minor reorgan-
structure is based on the values that result after applica-
ization in most cases, since only the records in one bucket
tion of the hash function to the search field. In indexing,
are redistributed to the two new buckets. The only time a
the access structure based on the values of the search field
reorganization is more expensive is when the directory has
itself. The second technique, called linear hashing, does not
to be doubled (or) halved.
require additional access structure.
A disadvantage is that the directory must be searched
These hashing schemes take advantage of the fact that
before accessing the buckets themselves, resulting in two
the result of applying a hashing function is a non-negative
block accesses instead of one in static hashing.
integer and hence can be represented as a binary number.
The access structure is built on the binary representation
of the hashing function result, which is a string of bits. We Indexing
call this the hash value of a record. Records are distributed Indexes are auxiliary access structures, which are used to
among buckets based on the values of the leading bits in speed up the retrieval of records in response to certain search
their hash values. conditions. The index structure typically provides secondary
access paths, which provide alternative ways of accessing the
Extendible Hashing records without affecting the physical placement of records
on disk. They enable efficient access to records based on the
In extendible hashing, a type of directory, an array of 2d indexing fields that are used to construct the index.
bucket addresses is maintained, where d is called the global Any field of the file can be used to create an index and
depth of the directory. The integer value corresponding to multiple indexes on different fields can be constructed on the
the first (high-order) d bits of a hash value is used as an same file. To find a record or records in the file based on a cer-
index to the array to determine a directory entry, and the tain selection criterion on an indexing field, one has to initially
address in that determines the bucket in which the corre- access the index, which points to one or more blocks in the
sponding records are stored. Several directory locations file where the required records are located. The most preva-
with the same first d′ bits for their hash values may contain lent types of indexes are based on ordered files (single-level
the same bucket address if all the records that hash to these indexes) and tree data structures (multilevel indexes, B+ trees).
locations fit in a single bucket. A local depth d′ is stored Dense Index files: Index record appears for every search-
with each bucket specifies the number of bits on which the key value in the file.
bucket contents are based.
Brighton A-217 Brighton 750
3
000 Downtown A-101 Downtown 600
Bucket A
001 Mianus A-110 Downtown 300
2 Perryridge A-215 Mianus 400
010
Bucket B
011
A102 Perryridge 800
100 2 Figure 3 Dense index file.
101 Bucket C
Sparse index files These files contain index records for
110 3 only some search-key values. Applicable when records are
111 Bucket D sequentially ordered on search key.
Chapter 5 • File Management | 4.87
Zakir
Block n Zamal
Zakir
log2b = log26000 = 13 block accesses
Zamal
Example: For the above data, suppose that the ordering
key field of the file is V = 7 bytes long, a block pointer, P =
5 bytes long, and we have constructed a primary index for
Figure 6 Primary index on the ordering key field of the file. the file.
Indexes can also be characterized as dense or sparse. A The size of each index entry is Ri = (7 + 5) = 12 bytes, so
dense index has an index entry for every search-key value the blocking factor for the index is bfri = (B/Ri)
(every record) in the data file. A sparse (non-dense) index 512/12 = 42.66 = 42 entries per block.
has index entries only for some of the search values. A pri- The total number of index entries ri is equal to number of
mary index is non-dense (sparse) index, since it includes an blocks in the data file, which is 6000. The number of index
entry for each disk block of the data file and the keys of its blocks is hence
anchor record rather than for every search value. bi = (ri/bfri) = 6000/42 = 142 blocks
The index file for primary index needs fewer blocks than
does the data file, for two reasons as follows: To perform a binary search on the index file would need
log2bi = log2142 = 8 block accesses. To search for a
1. There are fewer index entries than there are records in record using the index, we need one additional block access
the data file. to the data file for a total of ‘9’ block accesses.
2. Each index entry is typically smaller in size than a
data record because it has only two fields. So more Disadvantage: A major problem with a primary index is
index entries than data records can fit in one block. insertion and deletion of records. If we attempt to insert a
record in its correct position in the data file, we have to not
A binary search on the index file requires fewer block only move records to make space for the new record but also
accesses than a binary search on the data file. The binary change some index entries.
search for an ordered data file required log2b block accesses.
But if the primary index file contains bi blocks, then to Clustering Index If records of a file are physically ordered
locate a record with a search-key value requires a binary on a non-key field, which does not have a distinct value for
search of that index and access to the block containing that each record, that field is called the clustering field. We can
record, a total of log2bi + 1 accesses. create a different type of index called clustering index to
Chapter 5 • File Management | 4.89
speed up the retrieval of records that have the same value to different leaf nodes are of the same length (balanced path
for the clustering field. length). All leaf nodes are at the same depth level.
A clustering index is also an ordered file with two fields, This ensures that number of disk accesses required for
the first field is of the same type as the clustering field of the all the searches are same. The lesser the depth (level) of an
data file, and the second field is a block pointer. index tree, the faster the search.
There is one entry in the clustering index for each dis-
tinct value of the clustering field, containing the value and
Insertion into B+ tree
a pointer to the first block in the data file that has a record
with that value for its clustering field. Given nodes 8 5 1 7 3 12 Initially start with root node (has
The record insertion and deletion still cause problems, no children)
because the data records are physically ordered. To alleviate
the problem of insertion, reserve a whole block (or a cluster 5 8 Insert 1 (overflow)
of contiguous blocks) for each value of the clustering field,
all records with that value are placed in the block (or block
5
cluster). A clustering index is an example of a non-dense Insert 7
index, because it has an entry for every distinct value of the
1 5 8
indexing field which is a non-key.
3. B+ tree ensures some space always left in nodes for 3. Each node in a tree should correspond to a block of
new entries. Also makes sure all nodes are at least data.
half full. 4. Each node can store many data items and has many
successors.
5. The B– tree has fewer levels but search for an item
Deletion in B+ Trees
takes more comparisons at each level.
Delete 5,12,9 from the below B+ tree: 6. If a B– tree has order ‘d’, then each node (except root)
7
has at least d/2 children, then the depth of the tree is
at most log d/2 (size) + 1.
1 6
9
7. In the worst case, we need (d - 1) comparisons in
each node (using linear search)
1 5 6 7 8 9 8. Fewer disk accesses are required compared to binary
12
Tree.
Delete 5: 9. The usual data structure for an index is the B+ tree.
10. Every modern DBMS contains some variant of B–
7 trees in addition with other index structures depending
on the application.
11. B– trees and B+ trees are one and the same. They differ
1 6 9 from B– trees in having all data in the leaf blocks.
12. Compared to binary trees, B– trees will have higher
branching factor.
1 6 7 8 9 12 13. Binary trees can degenerate to a linear list,
B– trees are balanced, so this is not possible.
Delete 12: 14. In B+ tree, the values in inner nodes are repeated in
Under flow has occurred, so redistribute. the leaf nodes.
7 15. The height of the tree might decrease, because the
data pointer is needed only in the leaf nodes, we can
1 6 8 also get a sorted sequence.
16. In B– trees, all leaves have the same distance from
1 6 7 8 9
root hence B– trees are balanced. This ensures that the
chain of links followed to access a leaf node is never
Delete 9: Underflow (merge with left) redistribute.
too long.
6 17. The time complexity of search operation in B– tree
1 7 (tree height) is O(log n), where ‘n’ is the number of
entries.
1 6 7 8
18. Advantage of B+ tree automatically reorganizes itself
with small and local changes while doing insertions
Advantages and deletions, reorganization of entire file is not
required to maintain performance.
1. B– Trees and B+ trees: B– tree is a data structure used
19. Disadvantage of B+ tree, extra Insertion and deletion
for external memory.
overhead, space overhead.
2. B– trees are better than binary search trees if data is
20. B+ trees can be used as dynamic multilevel Indexes.
stored in external memory.
Exercises
Practice Problems 1 (A) 124000 (B) 1260000
Directions for questions 1 to 20: Select the correct alterna- (C) 5120000 (D) 512000
tive from the given choices. (ii) What is the capacity of disk excluding Inter block
1. Consider the following specifications of a disk. Block gap?
size of a disk is 512 bytes, inter-block gap size is 128 (A) 25400 (B) 25600
bytes Number of blocks per track is 20 and number of (C) 25800 (D) 25900
tracks per surface is 400. 2. Consider the following specifications of a disk. Block
(i) What is the capacity of disk including Inter block size of disk is 512 bytes, 2000 tracks per surface, 50
gap? sectors per track and 5 double sided platters.
Chapter 5 • File Management | 4.91
(i) What is the capacity of track in bytes? (i) What is the blocking factor?
(A) 4096000 (B) 4086000 (A) 16 (B) 17
(C) 4076000 (D) 4066000 (C) 18 (D) 19
(ii) What is the capacity of surface in bytes? (ii) What is the number of blocks needed for the file?
(A) 25600000 (B) 512000 (A) 2642 (B) 2644
(C) 5120000 (D) 51200000 (C) 2646 (D) 2648
(iii) What is the capacity of disk in bytes? (iii) How many block accesses are required to search
(A) 512*10^4 (B) 512*10^5 for a particular data file using binary search?
(C) 512*10^6 (D) 512*10^7 (A) 10 (B) 11
(iv) How many cylinders does it have? (C) 12 (D) 13
(A) 512 (B) 1000 8. Suppose that the ordering key field of the file is 12
(C) 2000 (D) 2048 bytes long, a block pointer is 8 bytes long, and we have
(v) Identify the In valid disk block size from below: constructed a primary index for the file. Consider the
(A) 2048 (B) 51200 file specifications given in the above questions.
(C) 4098 (D) 4096 (i) What is the size of each index entry?
3. What is the order of internal node of B+ tree suppose (A) 16 (B) 18
that a child pointer takes 6 bytes, the search field value (C) 20 (D) 22
takes 14 bytes and the block size is 512 bytes? (ii) What is the blocking factor for the index?
(A) 23 (B) 24 (A) 101 (B) 102
(C) 25 (D) 26 (C) 103 (D) 104
4. The order of a leaf node in a B+ tree is the maximum (iii) What is the total number of index entries?
number of (value, data, record pointer) pairs it can (A) 2642 (B) 2644
hold. Given that block size is 1 k bytes (1024 bytes), (C) 2646 (D) 2648
data record pointer is 7 bytes long, the value field is ‘9’ (iv) What is the number of index blocks?
bytes long and block pointer is 6 bytes. (A) 22 (B) 24
(A) 63 (B) 64 (C) 26 (D) 28
(C) 65 (D) 66
(v) How many block accesses are required, if binary
5. The following key values are inserted into a B+ tree search is used?
in which order of the internal nodes is 3, and that of (A) 3 (B) 4
the leaf nodes is 2, in the sequence given below. The (C) 5 (D) 6
order of internal nodes is the maximum number of tree
pointers in each node, and the order of leaf nodes is the 9. For the file specifications given in Q. No. 7, if we con-
maximum number of data items that can be stored in it. struct secondary index on a non-ordering key field of
The B+ tree is initially empty. 10, 3, 6, 8, 4, 2, 1. What the file that is 12 bytes long, a block-pointer of size 8
is the maximum number of times leaf nodes would get bytes, each index entry is 20 bytes long and the block-
split up as a result of these insertions? ing factor is 102 entries per block.
(A) 3 (B) 4 (i) What is the total number of index blocks?
(C) 5 (D) 6 (A) 422 (B) 424
6. For the same key values given in the above question, sup- (C) 442 (D) 444
pose the key values are inserted into a B– tree in which (ii) How many block accesses are required to access
order of the internal nodes is 3 and that of leaf nodes is 2. the secondary index using binary search?
The order of internal nodes is the maximum number of (A) 6 (B) 7
tree pointers in each node and the order of leaf nodes is (C) 8 (D) 9
the maximum number of data items that can be stored 10. For the file specifications given in Q. No. 8, if we construct
in it. The B– tree is initially empty. What is the maxi- a multilevel index, number of 1st-level blocks are 442,
mum number of times leaf nodes would get split up as blocking factor is 102, each index entry is 20 bytes long.
a result of these insertions?
(A) 1 (B) 2 (i) What is the number of 2nd-level blocks?
(C) 3 (D) 4 (A) 4 (B) 5
(C) 6 (D) 7
7. Suppose that we have an ordered file with 45,000
records stored on a disk with block size 2048 bytes. (ii) What is the number of 3rd-level blocks?
File records are of fixed size and are unspanned with (A) 0 (B) 1
record length 120 bytes. (C) 2 (D) 3
4.92 | Unit 4 • Databases
11. Construct a B+ tree for (1,4,7,10,17,21,31) with n = 4, 16. What will be the number of index records/block?
which nodes will appear two times in a final B+ tree? (A) 68 (B) 65
(A) 17,7,20 (B) 17,7,20,25 (C) 69 (D) None
(C) 17,20,25 (D) 7,17.25 17. What will be the number of index blocks?
12. Suppose the hash function is h(x) = xmod 8 and each (A) 442 (B) 440
bucket can hold at most two records. The extendable (C) 400 (D) None
hash structure after inserting 1, 4, 5 ,7, 8, 2, 20, what is
18. Consider the following:
the local depth of ‘4’?
(A) 0 (B) 1 Block size = 1025 bytes
(C) 2 (D) 3 Record length in data file = 100 bytes
13. Consider the given B+ tree, insert 19 into the tree, what Total number of records = 30000
would be the new element in level 2? Search key = 9 bytes
13 30 Pointer = 6 bytes
What is the number of index blocks?
5 10 20 40 50 (A) 44 (B) 45
(C) 46 (D) None
1 4 5 9 11 12 13 18 20 29 30 38 41 45 60 70 19. Which of the following is maximum search time tmax in
B– trees?
(A) 13 (B) 18
(C) 20 (D) 29
(A) t = a log N a + d + bm + c
14. Consider the given B+ tree, delete 70 and 25 from the max 2
2 log 2 m log 2 m
tree, what are the elements present in level 2? (∴ root
is at level 1)
N a + d bm
60 (B) tmax = a log 2 + + c
2 log 2 m log 2 m
25 50 75 85
a+d bm
(C) tmax = a log 2 N + + c
log 2 m log 2 m
5 10 15 20 25 28 30 50 55 60 65 70
75 80 85 90 95 a bm
(D) tmax = a log 2 ( N ) + + c
log 2 m log 2 m
(A) 25, 50, 75 (B) 25, 50,75, 85
(C) 28, 50, 75, 85 (D) 28, 50, 65, 75 20. Consider a B+ tree. A child pointer takes 3 bytes, the
15. Delete 60 from the above given tree (Q. No. 14). After search field value takes 7 bytes, and the block size is
deletion, what is the total number of nodes present in 256 bytes. What is the order of the internal node?
the tree? (A) 63 (B) 64
(C) 65 (D) 66
60
25 50 75 85
5 10 15 20 25 28 30 50 55 60 65 70
75 85 85 90 95
(A) 5 (B) 6
(C) 7 (D) 8
Chapter 5 • File Management | 4.93
Practice Problems 2 (A) When a transaction Ti issues a read (Q) operation, the
Directions for questions 1 to 20: Select the correct alterna- system issues a lock s(Q) instruction followed by the
tive from the given choices. read instruction.
(B) When Ti issues a write Q operation, the system
1. Which of the following is true? checks to see whether Ti already holds a shared
(A) Every conflict serializable is view serializable lock on Q. If it does, then the system issues an
(B) Every view serializable is conflict serializable upgrade Q instruction followed by the write Q
(C) Both A and B instruction, otherwise the system issues a lock
(D) A schedule can be either only conflict serializable -X(Q) instruction, followed by the write Q
or only view-serializable. instruction.
2. Which one is the 2-phase locking rule? (C) All locks obtained by a transaction are unlocked
(A) Two transactions cannot have conflicting locks after that transaction commits or aborts.
(B) No unlock operation can precede a lock operation (D) All of the above
in the same transaction. 8. Which one is correct?
(C) No data is/are affected until all locks are obtained (A) A lock manager can be implemented as a process
and until the transaction is in its locked point. that receives messages from transactions and sends
(D) All of the above messages in reply.
3. If Transaction Ti has obtained an exclusive mode lock (B) It uses linked list of records.
on item Q, then (C) It uses hash table called lock table.
(A) Ti can read Q (D) All of the above
(B) Ti can write Q Common data questions 9 and 10: Transaction T1 has 5
(C) Ti can read and write instructions. Transaction T2 has 3 instructions.
(D) Neither read nor write
9. The number of non-serial transactions will be
4. Phantom phenomenon is (A) 15 (B) 8
(A) A transaction retrieves a collection of objects but (C) 2 (D) 56
sees same result.
10. The number of serial transaction schedules will be
(B) A transaction retrieves a collection of objects but
(A) 15 (B) 8
sees different results.
(C) 2 (D) 56
(C) Transaction T1 waits for T2 and T2 waits for T1
(D) This problem arises when the transaction has not 11. In a heap file system, which of the following function
locked all the objects. finds ‘average number of blocks to be read’?
14. The two-phase locking protocol 18. To have a file, holding a list is necessary to
(A) ensures serializability (i) Identify the records in the list
(B) issues locks in two phases
(ii) Identify the name, and type of the fields of each
(C) unlocks in two phases
record.
(D) All of the above
(iii) Decide which fields will be used as sort of index
15. The point in the schedule where the transaction has obtained
keys.
its final lock (the end of its growing phase) is called the
(A) Only (i) and (ii)
(A) block point (B) critical section
(B) Only (i) and (iii)
(C) growing point (D) lock point
(C) Only (ii) and (iii)
16. Which of the following is not a problem of file manage- (D) All of the above
ment system?
19. Two files may be joined into a third file, if the following
(A) Data redundancy
is true:
(B) Lack of data independence
(A) if they have row in common
(C) Program dependence
(B) if they have a field in common
(D) All of the above
(C) Both (A) and (B)
17. Which of the following is/are true about master list of (D) None
an index file?
20. The minimum number of record movements required to
(i) Is sorted in ascending order merge four files w(with 10 records), x(with 20 records),
(ii) A number is assigned to each record. y(with 15 records) and z(with 5 records) is:
(A) Only (i) (B) Only (ii) (A) 50 (B) 40
(C) Both (i) and (ii) (D) None of the above (C) 30 (D) 35
8. With reference to the B+ tree index of order 1 shown each non-leaf node of the tree is ________.[2015]
below, the minimum number of nodes (including the 10. B+ Trees are considered BALANCED because
Root node) that must be fetched in order to satisfy the [2016]
following query: “Get all records with a search key (A) The lengths of the paths from the root to all leaf
greater than or equal to 7 and less than 15” is _______ nodes are all equal.
[2015] (B) The lengths of the paths from the root to all leaf
9 nodes differ from each other by at most 1.
(C) The number of children of any two non - leaf sib-
5 13 17 ling nodes differ by at most 1.
(D) The number of records in any two leaf nodes dif-
1 3 5 7 9 11 13 15 17
fer by at most 1.
11. In a B+ tree, if the search-key value is 8 bytes long,
9. Consider a B+ tree in which the search key is 12 bytes
the block size is 512 bytes and the block pointer size
long, block size is 1024 bytes, record pointer is 10
is 2 bytes, then the maximum order of the B+ tree is
bytes long and block pointer is 8 bytes long. The max-
__________. [2017]
imum number of keys that can be accommodated in
Answer Keys
Exercises
Practice Problems 1
1. (i) C (ii) A 2. (i) B (ii) D (iii) C (iv) C (v) C 3. C 4. A 5. C 6. B
7. (i) B (ii) D (iii) C 8. (i) C (ii) B (iii) D (iv) C (v) C 9. (i) C (ii) D
10. (i) B (ii) B 11. B 12. D 13. B 14. C 15. B 16. A 17. A 18. B
19. A 20. C
Practice Problems 2
1. A 2. D 3. C 4. B 5. C 6. B 7. D 8. D 9. D 10. C
11. B 12. B 13. D 14. D 15. D 16. D 17. B 18. D 19. B 20. B
Test
(A) Retrieve the name and address of employees who (C) π a1 , a2 ... an σ P ( r1 ∪ r2 ∪×…× ∪rm )
work for the project no ‘Dno’
(B) Retrieve the name and address of all employees (D) π a , a ... a σ P ( r1r2 ×…× rm )
1 2 n
(A) Represents a ternary relationship 28. What does the following relational algebra expression
(B) Represents a binary relationship represent?
(C) Represents a ternary relationship with instances of pid ( pid, mob_no(Employee-Guests))
the form (s, j, p) (A) Id of all employees working with the company
(D) Represents 1 – to – many relationships (B) Id of all permanent employees
26. If two relations R1 and R2 are such that they are of the (C) Id of part time employees
same degree and domain of the corresponding fields (D) None of these
are also the same, then which one of the following is Common data for questions 29 and 30:
true about R1 and R2? 29. Let R1 and R2 be two relations with attributes a1 and a2.
(A) R1 ⊂ R2 P1 and P2 be two predicates.
(B) R1 ∪R2 = R2 ∪ R1 Select the expression from the following which is
(C) R1 and R2 are union compatible wrong:
(D) None of these
(A) σ P1 (σ P1 ( R1 )) → σ P2 (σ P2 ( R1 ))
Common data questions for 27 and 28: Let Employee
(B) σ P1 (π a1 ( R1 )) → π (σ a1 (σ P1 ( R1 )))
and Guests be two relations with attributes (id, mobl_no,
name, address) and (id, mob–no, comps_working, shifts) (C) σ P1 ( R1 ∪ R2 ) → σ P1 ( R1 ) ∪ σ P2 ( R2 )
Relations respectively {id, mob_no} is the key for both. (D) π a2 (σ a1 ( R1 )) → σ P1 (π a2 ( R1 ))
27. Which of the following queries are equivalent? 30. Select from the following corresponding TRC for the
(i) pid (Employee Guests) wrong expression in the above question:
(ii) pid (Employee) pid(Guests)
(A) {t/ ∃u, R1(t[P1]) = R2(u[P1])}
(iii) pid{(Employee-Guest) ∩ Guest-Employee)}
(B) {t/ u, R1(t[P1]) = R1(u[P1])}
A
(iv) pid { pid, mob (Employee) ∩ pid, mob (Guest)}
(A) (ii) and (iii) (B) (ii), (iii) and (iv) (C) {t/ ∃u, R1(t[P1]) ≠ R2(u([P1])}
(C) (i), (ii) and (iv) (D) (ii) and (iv) only (D) {t/(דt∈R1)}
Answer Keys
1. D 2. D 3. C 4. C 5. B 6. B 7. C 8. B 9. B 10. A
11. B 12. C 13. B 14. A 15. C 16. A 17. D 18. C 19. A 20. A
21. C 22. D 23. C 24. B 25. C 26. C 27. C 28. B 29. A 30. B