• 0

## Database Systems A Practical Approach To Design, Implementation, And Management 6th Edition A+ Global Edition By Thomas Connolly – Solution Manual A+

\$35.00
Database Systems A Practical Approach To Design, Implementation, And Management 6th Edition A+ Global Edition By Thomas Connolly – Solution Manual A+

Discuss each of the following concepts in the context of the relational data model:

(a) Relation A table with columns and rows.

(b) Attribute A named column of a relation.

(c) Domain The set of allowable values for one or more attributes.

(d) Tuple A row of a relation.

(e) Intension The structure of a relation together with a specification of the domains and any other restrictions on possible values.

Extension An instance of the tuples of a relation.

(f) Degree The number of attributes in a relation.

Cardinality The number of tuples in a relation.

Each term defined in Section 4.2.1.

4.2 Describe the relationship between mathematical relations and relations in the relational data model?

Let D1, D2, . . . , Dn be n sets. Their Cartesian product is defined as:

D1 ´ D2 ´ . . . ´ Dn = {(d1, d2, . . . , dn) | d1 Î D1, d2 Î D2, . . . , dn Î Dn}

Any set of n-tuples from this Cartesian product is a relation on the n sets. Now let A1, A2, . . ., An be attributes with domains D1, D2, . . . , Dn. Then the set {A1:D1, A2:D2, . . . , An:Dn} is a relation schema. A relation R defined by a relation schema S is a set of mappings from the attribute names to their corresponding domains. Thus, relation R is a set of n-tuples:

(A1:d1, A2:d2, . . . , An:dn) such that d1 Î D1, d2 Î D2, . . . , dn Î Dn

Each element in the n-tuple consists of an attribute and a value for that attribute.

Discussed fully in Sections 4.2.2 and 4.2.3.

4.3 Describe the term “normalized reaction”. Why are constraints so important in a relational database?

Codd described a normalized relation as a relation that does not contain any repeating groups or multivalued attributes. The attributes are functionally dependent on only the primary key. Constraints enforce data integrity, consistency, and business rules.

4.4 Discuss the properties of a relation.

A relation has the following properties:

• has a name that is distinct from all other relation names in the relational schema;
• each cell contains exactly one atomic (single) value;
• each attribute has a distinct name;
• the values of an attribute are all from the same domain;
• each tuple is distinct; there are no duplicate tuples;
• the order of attributes has no significance;
• the order of tuples has no significance, theoretically. (However, in practice, the order may affect the efficiency of accessing tuples.)

Discussed fully in Section 4.2.4.

4.5 Discuss the differences between the candidate keys and the primary key of a relation. Explain what is meant by a foreign key. How do foreign keys of relations relate to candidate keys? Give examples to illustrate your answer.

The primary key is the candidate key that is selected to identify tuples uniquely within a relation. A foreign key is an attribute or set of attributes within one relation that matches the candidate key of some (possibly the same) relation. Discussed in Section 4.2.5.

4.6 Define the two principal integrity rules for the relational model. Discuss why it is desirable to enforce these rules.

Two rules are Entity Integrity (Section 4.3.2) and Referential Integrity (Section 4.3.3).

4.7 Define “views”. Why are they important in a database approach?

Views can be described as virtual tables that utilize one or more relational operations operating on the base relations to produce another relation. Views data are dynamically assigned by the DBMS through relational operations set by users. Views are useful in a number of ways including those described in section 4.4.2. These include data security, easy data customization, data flexibility, and simplification of complex operations on base relations.

#### Exercises

The following tables form part of a database held in a relational DBMS:-

Hotel (hotelNo, hotelName, city)

Room (roomNo, hotelNo, type, price)

Booking (hotelNo, guestNo, dateFrom, dateTo, roomNo)

where Hotel contains hotel details and hotelNo is the primary key;

Room contains room details for each hotel and (roomNo, hotelNo) forms the primary key;

Booking contains details of the bookings and (hotelNo, guestNo, dateFrom) forms the primary key;

and Guest contains guest details and guestNo is the primary key.

4.8 Identify the foreign keys in this schema. Explain how the entity and referential integrity rules apply to these relations.

For each relation, the primary key must not contain any nulls.

Room is related to Hotel through the attribute hotelNo. Therefore, the hotelNo in Room should either be null or contain the number of an existing hotel in the Hotel relation. In this case study, it would probably be unacceptable to have a hotelNo in Room with a null value.

Booking is related to Hotel through the attribute hotelNo. Therefore, the hotelNo in Booking should either be null or contain the number of an existing hotel in the Hotel relation. However, because hotelNo is also part of the primary key, a null value for this attribute would be unacceptable. Similarly for guestNo. Booking is also related to Room through the attribute roomNo.

4.9 Produce some sample tables for these relations that observe the relational integrity rules. Suggest some general constraints that would be appropriate for this schema.

Student should provide some sample tables, observing entity and referential integrity. In particular, ensure the uniqueness for the composite primary keys of the Room and Booking tables.

Some general constraints may be:

• There can be no two bookings for the same room in the same hotel on the same day.
• For the Booking relation, dateFrom must be before dateTo.
• Room price must be greater than 0 and less than £200.

4.10 Analyze the RDBMSs that you are currently using. Determine the support the system provides for primary keys, alternate keys, foreign keys, relational integrity, and views.

This is a small student project, the result of which is dependent on the system analyzed.

4.11 Implement the above schema in one of the RDBMSs you currently use. Generate two user-views that are accessible and updatable as well as two other user-views that cannot be updated.

Students need to practice implementing the above schema. As described in section 4.4.3, it is possible to update the views provided it fits into the specified criteria. Generated views need to observe criteria outlined in section 4.4.3

# Chapter 5 Relational Algebra and Relational Calculus

#### Review Questions

5.1 What is the difference between a procedural and non-procedural language? How would you classify the relational algebra and relational calculus?

Procedural language: a language that allows user to tell the system what data is needed and exactly how to retrieve the data.

Non-procedural language: a language that allows user to state what data is needed rather than how it is to be retrieved.

Informally, we may describe the relational algebra as a (high-level) procedural language: it can be used to tell the DBMS how to build a new relation from one or more relations in the database. Again, informally, we may describe the relational calculus as a non-procedural language: it can be used to formulate the definition of a relation in terms of one or more database relations.

5.2 Explain the following terms:

• tuple relational calculus

In tuple relational calculus, we are interested in finding tuples for which a predicate is true. The calculus is based on the use of tuple variables. A tuple variable is a variable that “ranges over” a named relation: that is, a variable whose only permitted values are tuples of the relation. (The word “range” here does not correspond to the mathematical use of range, but corresponds to a mathematical domain.) For example, to specify the range of a tuple variable S as the Staff relation, we write: Staff(S)

To express the query “Find the set of all tuples S such that F(S) is true,” we can write:

{S | F(S)}

F is called a formula (well-formed formula, or wff in mathematical logic). See section 5.2.1

• domain relational calculus

Variables are used in domain relational calculus also, but in this case the variables take their values from domains of attributes rather than tuples of relations. An expression in the domain relational calculus has the following general form:

{d1, d2, . . . , dn | F(d1, d2, … , dm)} m \$ n

Where d1, d2, . . . , dn, . . . , dm represent domain variables and F(d1, d2, . . . , dm) represents a formula composed of atoms. See section 5.2.2.

5.3 Define the five basic relational algebra operations. Define the Join, Intersection, and Division operations in terms of these five basic operations.

Five basic operations are:

• Selection and Projection (Unary)
• Cartesian Product, Union, and Set Difference (Binary).

There is also the Join, Intersection, and Division operations:

• Can rewrite q-Join in terms of the basic selection and Cartesian product operations:

R 3 F S = sF (R ´ S)

• Can express the intersection operation in terms of the set difference operation:

R Ç S = R – (R – S)

• Can express the division operation in terms of the basic operations:

T1 = PC(R)

T2 = PC( (S x T1) – R)

T = T1 – T2

5.4 Discuss the differences between the five Join operations: Theta join, Equijoin, Natural join, Outer join, and Semijoin. Give examples to illustrate your answer.

 Theta join R F S Produces a relation that contains tuples satisfying the predicate F from the Cartesian product of R and S. Equijoin R F S Produces a relation that contains tuples satisfying the predicate F (which only contains equality comparisons) from the Cartesian product of R and S. Natural join R S An Equijoin of the two relations R and S over all common attributes x. One occurrence of each common attribute is eliminated. (Left) Outer join R S A join in which tuples from R that do not have matching values in the common attributes of S are also included in the result relation. Semijoin R F S Produces a relation that contains the tuples of R that participate in the join of R with S.

5.5 There are different types of join operations that can be used to retrieve data, based on different relations. Describe the relation between theta and equal join.

The Theta join operation (R F S) defines a relation that contains tuples satisfying the predicate F from the Cartesian product of R and S. The predicate F is of the form R.ai u S.bi, where u may be one of the comparison operators (<,>,=, ≤, ≥, ≠). In the case where the predicate F contains only equality (=), the term Equijoin is used instead. Equal join is one form of theta join.

5.6 Define the structure of a (well-formed) formula in both the tuple relational calculus and domain relational calculus.

Tuple relational calculus

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

• R(Si), where Si is a tuple variable and R is a relation.
• Si.a1 q Sj.a2, where Siand Sj are tuple variables, a1 is an attribute of the relation over which Si ranges, a2 is an attribute of the relation over which Sj ranges, and q is one of the comparison operators (<, £ , >, ³ , =, ¹); the attributes a1 and a2 must have domains whose members can be compared by
• Si.a1 q c, where Siis a tuple variable, a1 is an attribute of the relation over which Si ranges, c is a constant from the domain of attribute a1, and q is one of the comparison operators.

We recursively build up formulae from atoms using the following rules:

• an atom is a formula;
• if F1and F2 are formulae, so are their conjunction F1 Ù F2, their disjunction F1 Ú F2, and the negation ~F1;
• if F is a formula with free variable X, then (\$X)(F) and (“X)(F) are also formulae.

Domain relational calculus

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

• R(d1, d2,…, dn), where R is a relation of degree n and each di is a domain variable.
• di q dj, where diand dj are domain variables and q is one of the comparison operators (<, £ , >, ³ , =, ¹); the domains di and dj must have members that can be compared by
• di q c, where diis a domain variable, c is a constant from the domain of di, and q is one of the comparison operators.

5.7 What is the difference between existential and universal quantifiers in relational calculus? Give examples to elaborate how the two are applied in a statement

See end of Section 5.2.1.

#### Exercises

For the following exercises, use the Hotel schema defined at the start of the Exercises at the end of Chapter 4.

5.8 Describe the relations that would be produced by the following relational algebra operations:

1. PhotelNo(sprice > 50 (Room) )

This will produce a relation with a single attribute (hotelNo) giving the number of those hotels with a room price greater than £50.

1. sHotel.hotelNo= Room.hotelNo(Hotel ´ Room)

This will produce a join of the Hotel and Room relations containing all the attributes of both Hotel and Room (there will be two copies of the hotelNo attribute). Essentially this will produce a relation containing all rooms at all hotels.

1. PhotelName(Hotel Hotel.hotelNo = Room.hotelNo (sprice > 50 (Room)) )

This will produce a join of Hotel and those tuples of Room with a price greater than £50. Essentially this will produce a relation containing all hotel names with a room price above £50.

1. Guest (sdateTo ³ ‘1-Jan-2007’ (Booking))

This will produce a (left outer) join of Guest and those tuples of Booking with an end date (dateTo) greater than or equal to 1-Jan-2007. All guests who don’t have a booking with such a date will still be included in the join. Essentially this will produce a relation containing all guests and show the details of any bookings they have beyond 1-Jan-2002.

1. Hotel Hotel.hotelNo = Room.hotelNo (sprice > 50 (Room)) )

This will produce a (semi) join of Hotel and those tuples of Room with a price greater than £50. Only those Hotel attributes will be listed. Essentially this will produce a relation containing all the details of all hotels with a room price above £50.

1. PguestName, hotelNo(Booking Booking.guestNo = Guest.guestNo Guest) ¸

PhotelNo (scity = ’London’(Hotel))

This will produce a relation containing the names of all guests who have booked all hotels in London.

5.9 Provide the equivalent tuple relational calculus and domain relational calculus expressions for each of the relational algebra queries given in Exercise 4.8.

1. PhotelNo(sprice > 50 (Room) )

TRC: {R.hotelNo | Room(R) Ù R.price > 50}

DRC: {hotelNo | (\$rNo, typ, prce) (Room (rNo, hotelNo, typ, prce) Ù prce > 50)}

1. sHotel.hotelNo= Room.hotelNo(Hotel ´ Room)

TRC: {H, R | Hotel(H) Ù (\$R) (Room(R) Ù (H.hotelNo = R.hotelNo))}

DRC: {hNo, hName, cty, rNo, hNo1, typ, prce | (Hotel(hNo, hName, cty) Ù Room(rNo, hNo1, typ, prce) Ù (hNo = hNo1))}

1. PhotelName(Hotel Hotel.hotelNo = Room.hotelNo (sprice > 50 (Room)) )

TRC: {H.hotelName | Hotel(H) Ù (\$R) (Room(R) Ù (H.hotelNo = R.hotelNo) Ù

(R.price > 50))}

DRC: {hotelName | (\$hNo, cty, rNo, hNo1, typ, prce)

(Hotel(hNo, hotelName, cty) Ù Room(rNo, hNo1, typ, prce) Ù (hNo = hNo1) Ù

(prce > 50))}

1. Guest (sdateTo ³ ‘1-Jan-2007’ (Booking))

TRC: {G.guestNo, G.guestName, G.guestAddress, B.hotelNo, B.dateFrom,

B.dateTo, B.roomNo | Guest(G) Ú (\$B) (Booking(B) Ù

(G.guestNo = B.guestNo) Ù (B.dateTo > ‘1-Jan-2007’))}

DRC: {guestNo, guestName, guestAddress, hotelNo, dateFrom, dateTo, roomNo |

(Booking(hotelNo, gNo1, dateFrom, dateTo, roomNo) Ù

(guestNo = gNo1) Ù (dateTo ³ ‘1-Jan-2007’)))}

1. Hotel Hotel.hotelNo = Room.hotelNo (sprice > 50 (Room)) )

TRC: {H.hotelNo, H.hotelName, H.city | Hotel(H) Ù (\$R) (Room(R) Ù

(H.hotelNo = R.hotelNo) Ù (R.price > 50))}

DRC: {hotelNo, hotelName, city | (\$rNo, hNo1, typ, prce)

(Hotel(hotelNo, hotelName, city) Ù Room(rNo, hNo1, typ, prce) Ù

(hotelNo = hNo1) Ù (prce > 50))}

1. PguestName, hotelNo(Booking Booking.guestNo = Guest.guestNo Guest) ¸

PhotelNo (scity = ’London’(Hotel))

TRC: {G.guestName | Guest(G) Ù(~ (\$H) (Hotel(H) Ù

(H.city = ‘London’) Ù (~(\$B) (Booking(B) Ù

G.guestNo = B.guestNo Ù H.hotelNo = B.hotelNo))))}

DRC: {guestName | (\$gNo, gName, gAddress, hNo, gNo1, dFrom, dTo, rNo,

hName, cty, hNo1, typ, prce) (~(Hotel(hNo, hName, cty) Ù

(cty = ‘London’) Ù Guest(gNo, gName, gAddress) Ù

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

(gNo = gNo1) Ù (hNo = hNo1)))}

5.10 Describe the relations that would be produced by the following tuple relational calculus expressions:

• {hotelName | Hotel(H) Ù H.city = ‘London’}

This will produce a relation containing the names of all hotels in London.

• {hotelName | Hotel(H) Ù (\$R) (Room(R) Ù H.hotelNo = R.hotelNo Ù R.price > 50)}

This will produce a relation containing the names of all hotels that have a room price above £50.

• {hotelName | Hotel(H) Ù (\$B) (\$G) (Booking(B) Ù Guest(G) Ù H.hotelNo = B.hotelNo ÙB.guestNo = G.guestNo Ù G.guestName = ‘John Smith’)}

This will produce a relation containing the names of all hotels that have a booking for a guest called John Smith.

• {hotelName, G.guestName, B1.dateFrom, B2.dateFrom | Hotel(H) Ù Guest(G) Ù

Booking(B1) Ù Booking(B2) Ù H.hotelNo = B1.hotelNo Ù

G.guestNo = B1.guestNo Ù B2.hotelNo = B1.hotelNo Ù

B2.guestNo = B1.guestNo Ù B2.dateFrom ¹ B1.dateFrom}

This will produce a relation containing the names of guests who have more than one booking at the same hotel, along with the hotel number and the dates of the bookings.

5.11 Provide the equivalent domain relational calculus and relational algebra expressions for each of the tuple relational calculus expressions given in Exercise 4.10.

• {hotelName | Hotel(H) Ù H.city = ‘London’}

DRC: {hotelName | (\$hNo, cty) (Hotel(hNo, hotelName, cty) Ù cty = ‘London’)}

RA: PhotelName (scity = ‘London’ (Hotel) )

• {hotelName | Hotel(H) Ù (\$R) (Room(R) Ù H.hotelNo = R.hotelNo Ù R.price > 50)}

DRC: {hotelName | (\$hNo, cty, rNo, hNo1, typ, prce) (Hotel(hNo, hotelName, cty) Ù

Room(rNo, hNo1, typ, prce) Ù (hNo = hNo1) Ù (prce > 50)) }

RA: PhotelName (Hotel Hotel.hotelNo = Room.hotelNo (sprice > 50 (Room)) )

• {hotelName | Hotel(H) Ù (\$B) (\$G) (Booking(B) Ù Guest(G) Ù H.hotelNo = B.hotelNo ÙB.guestNo = G.guestNo Ù G.guestName = ‘John Smith’)}

DRC: {hotelName | (\$hNo, cty, gNo, gName, gAddress, hNo1, gNo1, dFrom, dTo,

rNo) (Hotel(hNo, hotelName, cty) Ù

Booking(hNo1, gNo1, dFrom, dTo, rNo) Ù (gNo = gNo1) Ù

(hNo = hNo1) Ù (gName = ‘John Smith’))}

RA: PhotelName (sguestName = ‘John Smith’ (Guest) Guest.guestNo = guestNo (

Booking .Booking.hotelNo = Hotel.hotelNo Hotel))

• {hotelName, G.guestName, B1.dateFrom, B2.dateFrom | Hotel(H) Ù Guest(G) Ù

Booking(B1) Ù Booking(B2) Ù H.hotelNo = B1.hotelNo Ù

G.guestNo = B1.guestNo Ù B2.hotelNo = B1.hotelNo Ù

B2.guestNo = B1.guestNo Ù B2.dateFrom ¹ B1.dateFrom}

DRC: {hotelName, guestName, dateFrom1, dateFrom2 | (\$hNo, cty,

gNo, gAddress, hNo1, gNo1, dTo1, rNo1, hNo2, gNo2, dTo2, rNo2)

(Hotel(hNo, hotelName, cty) Ù

Booking(hNo1, gNo1, dateFrom1, dTo1, rNo1) Ù

Booking(hNo2, gNo2, dateFrom2, dTo2, rNo2) Ù

(hNo = hNo1) Ù (gNo = gNo1) Ù (hNo2 = hNo1) Ù (gNo2 = gNo1) Ù

(dateFrom1 ¹ dateFrom2))}

RA: Booking2(hotelNo, guestNo, dateFrom2, dateTo2, roomNo2) ¬

PhotelNo, guestNo, dateFrom, dateTo, roomNo (Booking)

PhotelName, guestName, dateFrom, dateFrom2 (Hotel Hotel.hotelNo = hotelNo

(Guest Guest.guestNo = guestNo (Booking Booking.hotelNo = Booking2.hotelNo Ù Booking.guestNo = Booking2.guestNo Ù dateFrom ¹ dateFrom2 Booking2)))

5.12 Generate the relational algebra, tuple relational calculus, and domain relational calculus expressions for the following queries:

(a) List all hotels.

RA: Hotel

TRC: {H | Hotel(H)}

DRC: {hotelNo, hotelName, city | Hotel(hotelNo, hotelName, city)}

(b) List all single rooms with a price below £20 per night.

RA: stype=‘S’ Ù price < 20(Room)

TRC: {R | Room(R) Ù R.type = ‘S’ Ù R.price < 20}

DRC: {roomNo, hotelNo, type, price | (Room(roomNo, hotelNo, type, price) Ù

type = ‘S’ Ù price < 20)}

(c) List the names and cities of all guests.

(d) List the price and type of all rooms at the Grosvenor Hotel.

RA: Pprice, type(Room hotelNo (shotelName = ‘Grosvenor Hotel’(Hotel)))

TRC: {R.price, R.type | Room(R) Ù (\$H) (Hotel(H) Ù (R.hotelNo = H.hotelNo) Ù

(H.hotelName = ‘Grosvenor Hotel’))}

DRC: {price, type | (\$roomNo, hotelNo, hotelNo1, hotelName, city)

(Room(roomNo, hotelNo, type, price) Ù Hotel(hotelNo1, hotelName, city) Ù

(hotelNo = hotelNo1) Ù (hotelName = ‘Grosvenor Hotel’))}

(e) List all guests currently staying at the Grosvenor Hotel.

RA: Guest guestNo (sdateFrom £ ‘01-01-15’ Ù dateTo ³ ‘01-01-15’ (

Booking hotelNo (shotelName = ‘Grosvenor Hotel’(Hotel))))

(substitute ‘01-01-15’ for today’s date).

TRC: {G |Guest(G) Ù ((\$B)(\$H) (Booking(B) Ù Hotel(H) Ù (B.dateFrom £ ‘01-01-15’) Ù

(B.dateTo ³ ‘01-01-15’) Ù (B.guestNo = G.guestNo) Ù

(B.hotelNo = H.hotelNo) Ù (H.hotelName = ‘Grosvenor Hotel’)))}

DRC: {guestNo, guestName, guestAddress | (\$hotelNo, guestNo1, dateFrom, dateTo,

hotelNo1, hotelName, city)

Booking(hotelNo, guestNo1, dateFrom, dateTo) Ù

Hotel(hotelNo1, hotelName, city) Ù (guestNo = guestNo1) Ù

(dateFrom £ ‘01-01-15’ Ù dateTo ³ ‘01-01-15’) Ù

(hotelNo = hotelNo1) Ù (hotelName = ‘Grosvenor Hotel’))}

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

RA: (Room hotelNo (shotelName = ‘Grosvenor Hotel’(Hotel))) // Outer Join

PguestName, hotelNo, roomNo(

(Guest guestNo (sdateFrom £ ‘01-01-15’ Ù dateTo ³ ‘01-01-15’ (

Booking hotelNo (shotelName=‘Grosvenor Hotel’(Hotel))))

(substitute ‘01-01-15’ for today’s date).

TRC: {R, G.guestName | (Room(R) Ù (\$H)(Hotel(H) Ù

(R.hotelNo = H.hotelNo) Ù (H.hotelName = ‘Grosvenor Hotel’))) Ú

(Guest(G) Ù ((\$B)(\$H) (Booking(B) Ù Hotel(H) Ù

(G.guestNo = B.guestNo) Ù (B.hotelNo = H.hotelNo) Ù

(H.hotelName = ‘Grosvenor Hotel’) Ù

(B.dateFrom £ ‘01-01-15’ Ù B.dateTo ³ ‘01-01-15’)))}

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

(\$hNo, hName, city, hNo1, gNo1, dFrom, dTo, rNo)

(Room(roomNo, hotelNo, type, price) Ù Hotel(hNo1, hName, city) Ù

(hotelNo = hNo1) Ù (hName = ‘Grosvenor Hotel’) ) Ú

(Guest(guestNo, guestName, guestAddress) Ù Hotel(hNo, hName, city) Ù

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

(guestNo = gNo1) Ù (hNo1 = hNo) Ù (hName = ‘Grosvenor Hotel’) Ù

(dFrom £ ‘01-01-15’ Ù dTo ³ ‘01-01-15’)))}

(g) List the guest details (guestNo, guestName, and guestAddress) of all guests staying at the Grosvenor Hotel.

RA: PguestNo, guestName, guestAddress(Guest guestNo (sdateFrom £ ‘01-01-15’ Ù dateTo ³ ‘01-01-15’ (

Booking hotelNo (shotelName=‘Grosvenor Hotel’(Hotel)))))

(substitute ‘01-01-15’ for today’s date).

TRC: {G | Guest(G) Ù ((\$B) (\$H) (Booking(B) Ù Hotel(H) Ù (B.guestNo = G.guestNo) Ù

(B.hotelNo = H.hotelNo) Ù (H.hotelName = ‘Grosvenor Hotel’) Ù

(B.dateFrom £ ‘01-01-15’ Ù B.dateTo ³ ‘01-01-15’) ))}

((\$hNo, gNo, dFrom, dTo, rNo, hNo1, hName, city)

Booking(hNo, gNo, dFrom, dTo, rNo) Ù Hotel(hNo1, hName, city) Ù

(guestNo = gNo) Ù (hNo = hNo1) Ù (hName = ‘Grosvenor Hotel’) Ù

(dFrom £ ‘01-01-15’ Ù dTo ³ ‘01-01-15’) ))}

5.13 Using relational algebra, produce a report of all employees from the IT and planning departments who are born after 1990.

The report can be obtained through union operator by combining results of a query that retrieves employees born after 1990 from IT and the query of the employees born after 1990 from planning.

sdeptNo=‘IT’Ù dob>’31-12-1990’(employee) υ sdeptNo=‘PL’Ù dob>’31-12-1990’(employee)

The report could also be produced by a query that uses OR (V) operator to combine result of the employees born after 1990 from IT and the result of employees born after 1990 and from Planning department.

s((deptNo=‘IT’Ù dob>’31-12-1990’) Ú (deptNo=‘PL’Ù dob>’31-12-1990’)) (employee)

5.14 List all employees.

RA: Employee

TRC: {E | Employee(E)}

DRC: {empNo, fName, lName, address, DOB, sex, position, deptNo | Employee(empNo, fName, lName, address, DOB, sex, position, deptNo)}

5.15 List all the details of employees who are female and born after 1990.

RA: sex=‘F’Ù dob>’31-12-1990’(Employee)

TRC: {E | Employee(E) Ù (E.sex = ‘F’ÙE.dob>’31-12-1990’)}

DRC: {empNo, fName, lName, address, DOB, sex, position, deptNo | Employee(empNo, fName, lName, address, DOB, sex, position, deptNo) Ù (sex=’F’ ÙE.dob>’31-12-1990’)}

5.16 List all employees who are not managers and are paid more than \$1500.

RA: sposition ≠ ‘manager’Ù salary>1500 (Employee)

TRC: {E. | Employee(E) Ù (E.position ≠ ‘manager’ Ù E.salary>500)}

DRC: { fName, lName, address | Employee(empNo, fName, lName, address, DOB, sex, position, deptNo) Ù (position≠’manager’ Ù salary>1500)}

5.17 Produce a list of the names and addresses of all employees who work for the IT department.

TRC: {E.fName, E.lName, E.address | Employee(E) Ù (\$D) (Dept(D) Ù (E.deptNo = D.deptNo) Ù (D.deptName = ‘IT’))}

DRC: {fName, lName, address | (\$empNo, DOB, sex, position, deptNo, deptNo1, deptName, mgrEmpNo) (Empoyee(empNo, fName, lName, address, DOB, sex, position, deptNo) Ù Department (deptNo1, deptName, mgrEmpNo) Ù (deptNo = deptNo1) Ù (deptName = ‘IT’))}

5.18 Produce a list of the names of all employees who work on the SCCS project.

RA: P fName, lName (Employee empNo (WorksOn projNo (s projName = ‘SCCS’(Project)))

TRC: {E.fName, E.lName | Employee(E) Ù (\$W) (\$P) (WorksOn(W) Ù Project(P) Ù (P.projName = ‘SCCS’) Ù (P.projNo = W.projNo) Ù (E.empNo = W.empNo))

DRC: {fName, lName | (\$empNo, address, DOB, sex, position, deptNo, projNo, projName, deptNo1, empNo1, projNo1, dateWorked, hoursWorked) (Employee (empNo, fName, lName, address, DOB, sex, position, deptNo) Ù Project (projNo, projName, deptNo1) Ù WorksOn (empNo1, projNo1, dateWorked, hoursWorked) Ù (empNo = empNo1) Ù (projNo = projNo1) Ù (projName = ‘SCCS’))}

5.19 Produce a complete list of all managers who are due to retire this year, in alphabetical order of surname.

Formulate the following queries in relational algebra.

5.20 Find out how many managers are female.

ÁCOUNT empNo(ssex = ‘F’ Ù position = ‘manager’(Employee))

5.21 Produce a report of all projects under the IT department.

sdepno=‘IT’(project)

5.22 Using the union operator, retrieve the list of employees who are neither managers nor supervisors. Attributes to be retrieved are first name, last name, position, sex and department number.

sposition = ‘manager’(Pfname, lName, sex,position,depno( Employee))

U

sposition = ‘supervisor’(Pfname, lName, sex,position,depno( Employee))

5.23 List the total number of employees in each department for those departments with more than 10 employees. Create an appropriate heading for the columns of the results table.

(sempCount > 10(rR(deptNo, empCount) deptNoÁCOUNT empNo(Employee)))))

The following tables form part of a Library database held in an RDBMS:

Book (ISBN, title, edition, year)

BookCopy (copyNo, ISBN, available)

BookLoan (copyNo, dateOut, dateDue, borrowerNo)

where Book contains details of book titles in the library and the ISBN is the key.

BookCopy contains details of the individual copies of books in the library and copyNo is the key. ISBN is a foreign key identifying the book title.

Borrower contains details of library members who can borrow books and borrowerNo is the key.

BookLoan contains details of the book copies that are borrowed by library members and copyNo/dateOut forms the key. borrowerNo is a foreign key identifying the borrower.

Formulate the additional queries in relational algebra, tuple relational calculus, and domain relational calculus.

5.24 List all book titles.

RA: Ptitle(Book)

TRC: {B.title | Book(B)}

DRC: {title | (\$ISBN, edn, yr) (Book(ISBN, title, edn, yr) }

5.25 List all borrower details.

RA: Borrower

TRC: {B | Borrower(B)}

5.26 List all book titles published in the year 2012.

RA: Ptitle(syear=‘2012’(Book))

TRC: {B.title | Book(B) Ù B.year=’2012’}

DRC: {title | (\$ISBN, edn, yr) (Book(ISBN, title, edn, yr) Ù yr=’2012’}

5.27 List all copies of book titles that are available for borrowing.

RA: PcopyNo, title(Book ISBN (savailable=‘Y’(BookCopy)))

TRC: {BC.copyNo, B.title | Book(B) Ù (\$BC) (BookCopy(BC) Ù (B.ISBN = BC.ISBN) Ù (BC.available=‘Y’))}

DRC: {copyNo, title | (\$ISBN, edn, yr, ISBN, avail) (Book(ISBN, title, edn, yr) Ù BookCopy(copyNo, ISBN, avail) Ù avail=’Y’)}

5.28 List all copies of the book title “Lord of the Rings” that are available for borrowing.

RA: PcopyNo(stitle=‘Lord of the Rings (Book) ISBN (savailable=‘Y’(BookCopy)))

TRC: {BC.copyNo | BookCopy(BC) Ù (\$B) (Book(B) Ù (B.ISBN = BC.ISBN) Ù (BC.available=‘Y’) Ù (B.title= ‘Lord of the Rings’))}

DRC: {copyNo | (\$ISBN, edn, yr, ISBN, avail) (Book(ISBN, title, edn, yr) Ù BookCopy(copyNo, ISBN, avail) Ù avail=’Y’ Ù title= ‘Lord of the Rings’)}

5.29 List the names of borrowers who currently have the book title “Lord of the Rings” on loan.

RA: PborrowerName( ( (stitle=‘Lord of the Rings (Book)) ISBN (savailable=‘N’(BookCopy)) )

copyNo (BookLoan) borrowerNo (Borrower) )

TRC: {BW.borrowerName | Borrower(BW) Ù (\$BL) (\$B) (\$BC) (Book(B) Ù

BookCopy(BC) Ù BookLoan(BL) Ù (BC.ISBN = B.ISBN) Ù

(BW.borrowerNo = BL.borrowerNo) Ù (BL.copyNo = BC.copyNo) Ù

(BC.available=‘N’) Ù (B.title= ‘Lord of the Rings’))}

DRC: {borrowerName | (\$ISBN, title, edn, yr, copyNo, avail, bNo, bAddress, dOut, dDue) (Book(ISBN, title, edn, yr) Ù BookCopy(copyNo, ISBN, avail) Ù

Borrower(bNo, borrowerName, bAddress) Ù BookLoan(copyNo, dOut, dDue, bNo) Ù avail=’N’ Ù title= ‘Lord of the Rings’)}

5.30 List the names of borrowers with overdue books.

RA: PborrowerName(Borrower borrowerNo (sdateDue>‘today’s date’(BookLoan)))

TRC: {BW.borrowerName | Borrower(BW) Ù (\$BL) (BookLoan(BL) Ù

(BW.borrowerNo = BL.borrowerNo) Ù (BL.dateDue> ‘today’s date’))}

DRC: {borrowerName | (\$bNo, bAddress, copyNo, dOut, dDue)

(Borrower(bNo, borrowerName, bAddress) Ù BookLoan(copyNo, dOut, dDue, bNo) Ù dDue>‘today’s date’)}

Formulate the following queries in relational algebra.

5.31 How many copies of ISBN “0-321-52306-7” are there?

ÁCOUNT copyNo(sISBN = ‘0-321-52306-7’ (BookCopy ))

5.32 How many copies of ISBN “0-321-52306-7” are currently available?

ÁCOUNT copyNo(savailable = ‘Y’ Ù ISBN = ‘0-321-52306-7’ (BookCopy ))

5.33 How many times has the book title with ISBN “0-321-52306-7” been borrowed?

ÁCOUNT copyNo((sISBN = ‘0-321-52306-7’ (BookCopy) copyNo BookLoan)

5.34 Produce a report of book titles that have been borrowed by “Peter Bloomfield”.

Ptitle(Book ISBN ((BookCopy copyNo BookLoan) borrowerNo

(sborrowerName = ‘Peter Bloomfield’(Borrower)) ))

5.35 For each book title with more than 3 copies, list the names of library members who have borrowed them.

5.36 Produce a report with the details of borrowers who currently have books overdue.

5.37 Produce a report detailing how many times each book title has been borrowed.

ISBNÁCOUNT copyNo(BookCopy copyNo BookLoan)

5.38 Analyze the RDBMSs that you are currently using. What types of relational languages does the system provide? For each of the languages provided, what are the equivalent operations for the eight relational algebra operations defined in Section 5.1?

This is a small student project, the result of which is dependent on the system analyzed. However, it is likely that the supported languages will be based around SQL and QBE, in which case, the student should attempt to map the various SQL clauses to the algebra and calculus. See also Exercise 5.31.

# Chapter 6 SQL: Data Manipulation

#### Review Questions

6.1 Briefly describe the four basic SQL DML statements and explain their use.

Section 6.3 describes the usage of basic data manipulation SQL statements; SELECT INSERT, UPDATE and DELETE.

6.2 Explain the importance and application of the WHERE clause in the UPDATE and DELETE statements.

Application

• Optionally used in the UPDATE and DELETE statements.
• Used when update or delete is done to some few rows
• Not used if the updates is to reflect all the available rows

Importance

• It controls where updates needs to be effected
• Protects data from being changed and deleted unnecessarily
• Enforces data quality

6.3 Explain the function of each of the clauses in the SELECT statement. What restrictions are imposed on these clauses?

FROM Specifies the table or tables to be used.

WHERE Filters the rows subject to some condition.

GROUP BY Forms groups of rows with the same column value.

HAVING Filters the groups subject to some condition.

SELECT Specifies which columns are to appear in the output.

ORDER BY Specifies the order of the output.

If the SELECT list includes an aggregate function and no GROUP BY clause is being used to group data together, then no item in the SELECT list can include any reference to a column unless that column is the argument to an aggregate function.

When GROUP BY is used, each item in the SELECT list must be single-valued per group. Further, the SELECT clause may only contain:

• Column names.
• Aggregate functions.
• An expression involving combinations of the above.

All column names in the SELECT list must appear in the GROUP BY clause unless the name is used only in an aggregate function.

6.4 What restrictions apply to the use of the aggregate functions within the SELECT statement? How do nulls affect the aggregate functions?

An aggregate function can be used only in the SELECT list and in the HAVING clause.

Apart from COUNT(*), each function eliminates nulls first and operates only on the remaining non-null values. COUNT(*) counts all the rows of a table, regardless of whether nulls or duplicate values occur.

6.5 How can results from two SQL queries be combined? Differentiate how the INTERSECT and EXCEPT commands work.

There are number of relational operators that can be used to combine results of two queries. Some of them are UNION, INTERSECT, and EXCEPT. For the two results to be semanticaly combined, order and number of columns from both results should be identical, and the combining columns should be of the same domain.

The difference between the two is well explained in section 6.3.9 where the intersect returns the rows that are common to both result sets, and except returns rows that are available in the first result set and not in the second result set.

6.6 Differentiate between the three types of subqueries. Why is it important to understand the nature of a subquery result before you write an SQL statement?

The subquery types are scalar, row, and table subquery. The main difference is on the nature of results they return; scalar subquery returns a single column and single row that is a single value, row subquery returns multiple columns and single row, while table subquery returns multiple columns and multiple rows. It is so import to understand the nature of subquery result so that you can make the best choice about the operator to be used

#### Exercises

For the Exercises 6.7 – 6.28, use the Hotel schema defined at the start of the Exercises at the end of Chapter 3.

Simple Queries

6.7 List full details of all hotels.

SELECT * FROM Hotel;

6.8 List full details of all hotels in London.

SELECT * FROM Hotel WHERE city = ‘London’;

6.9 List the names and addresses of all guests in London, alphabetically ordered by name.

ORDER BY guestName;

Strictly speaking, this would also find rows with an address like: ‘10 London Avenue, New York’.

6.10 List all double or family rooms with a price below £40.00 per night, in ascending order of price.

SELECT * FROM Room WHERE price < 40 AND type IN (‘D’, ‘F’)

ORDER BY price;

(Note, ASC is the default setting).

6.11 List the bookings for which no dateTo has been specified.

SELECT * FROM Booking WHERE dateTo IS NULL;

Aggregate Functions

6.12 How many hotels are there?

SELECT COUNT(*) FROM Hotel;

6.13 What is the average price of a room?

SELECT AVG(price) FROM Room;

6.14 What is the total revenue per night from all double rooms?

SELECT SUM(price) FROM Room WHERE type = ‘D’;

6.15 How many different guests have made bookings for August?

SELECT COUNT(DISTINCT guestNo) FROM Booking

WHERE (dateFrom <= DATE’2004-08-01’ AND dateTo >= DATE’2004-08-01’) OR

(dateFrom >= DATE’2004-08-01’ AND dateFrom <= DATE’2004-08-31’);

Subqueries and Joins

6.16 List the price and type of all rooms at the Grosvenor Hotel.

SELECT price, type FROM Room

WHERE hotelNo =

(SELECT hotelNo FROM Hotel

WHERE hotelName = ‘Grosvenor Hotel’);

6.17 List all guests currently staying at the Grosvenor Hotel.

SELECT * FROM Guest

WHERE guestNo =

(SELECT guestNo FROM Booking

WHERE dateFrom <= CURRENT_DATE AND

dateTo >= CURRENT_DATE AND

hotelNo =

(SELECT hotelNo FROM Hotel

WHERE hotelName = ‘Grosvenor Hotel’));

6.18 List the details of all rooms at the Grosvenor Hotel, including the name of the guest staying in the room, if the room is occupied.

SELECT r.* FROM Room r LEFT JOIN

(SELECT g.guestName, h.hotelNo, b.roomNo FROM Guest g, Booking b, Hotel h

WHERE g.guestNo = b.guestNo AND b.hotelNo = h.hotelNo AND

hotelName= ‘Grosvenor Hotel’ AND

dateFrom <= CURRENT_DATE AND

dateTo >= CURRENT_DATE) AS XXX

ON r.hotelNo = XXX.hotelNo AND r.roomNo = XXX.roomNo;

6.19 What is the total income from bookings for the Grosvenor Hotel today?

SELECT SUM(price) FROM Booking b, Room r, Hotel h

WHERE (dateFrom <= CURRENT_DATE AND

dateTo >= CURRENT_DATE) AND

r.hotelNo = h.hotelNo AND r.roomNo = b.roomNo AND

hotelName = ‘Grosvenor Hotel’;

6.20 List the rooms that are currently unoccupied at the Grosvenor Hotel.

SELECT * FROM Room r

WHERE roomNo NOT IN

(SELECT roomNo FROM Booking b, Hotel h

WHERE (dateFrom <= CURRENT_DATE AND

dateTo >= CURRENT_DATE) AND

b.hotelNo = h.hotelNo AND hotelName = ‘Grosvenor Hotel’);

6.21 What is the lost income from unoccupied rooms at the Grosvenor Hotel?

SELECT SUM(price) FROM Room r

WHERE roomNo NOT IN

(SELECT roomNo FROM Booking b, Hotel h

WHERE (dateFrom <= CURRENT_DATE AND

dateTo >= CURRENT_DATE) AND

b.hotelNo = h.hotelNo AND hotelName = ‘Grosvenor Hotel’);

Grouping

6.22 List the number of rooms in each hotel.

SELECT hotelNo, COUNT(roomNo) AS count FROM Room

GROUP BY hotelNo;

6.23 List the number of rooms in each hotel in London.

SELECT hotelNo, COUNT(roomNo) AS count FROM Room r, Hotel h

WHERE r.hotelNo = h.hotelNo AND city = ‘London’

GROUP BY hotelNo;

6.24 What is the average number of bookings for each hotel in August?

SELECT AVG(X)

FROM ( SELECT hotelNo, COUNT(hotelNo) AS X

FROM Booking b

WHERE (dateFrom <= DATE’2004-08-01’ AND

dateTo >= DATE’2004-08-01’) OR

(dateFrom >= DATE’2004-08-01’ AND

dateFrom <= DATE’2004-08-31’)

GROUP BY hotelNo);

Yes – this is legal in SQL-92!

6.25 What is the most commonly booked room type for each hotel in London?

SELECT MAX(X)

FROM ( SELECT type, COUNT(type) AS X

FROM Booking b, Hotel h, Room r

WHERE r.roomNo = b.roomNo AND b.hotelNo = h.hotelNo AND

city = ‘London’

GROUP BY type);

6.26 What is the lost income from unoccupied rooms at each hotel today?

SELECT hotelNo, SUM(price) FROM Room r

WHERE roomNo NOT IN

(SELECT roomNo FROM Booking b, Hotel h

WHERE (dateFrom <= CURRENT_DATE AND

dateTo >= CURRENT_DATE) AND

b.hotelNo = h.hotelNo)

GROUP BY hotelNo;

Populating Tables

6.27 Insert records into each of these tables.

INSERT INTO Hotel

VALUES (‘H111’, ‘Grosvenor Hotel’, ‘London’);

INSERT INTO Room

VALUES (‘1’, ‘H111’, ‘S’, 72.00);

INSERT INTO Guest

VALUES (‘G111’, ‘John Smith’, ‘London’);

INSERT INTO Booking

VALUES (‘H111’, ‘G111’, DATE’2005-01-01’, DATE’2005-01-02’, ‘1’);

6.28 Update the price of all rooms by 5%.

UPDATE Room SET price = price*1.05;

General

6.29 Investigate the SQL dialect on any DBMS that you are currently using. Determine the compliance of the DBMS with the ISO standard. Investigate the functionality of any extensions the DBMS supports. Are there any functions not supported?

This is a small student project, the result of which is dependent on the dialect of SQL being used.

6.30 Demonstrate that queries written using the UNION operator can be rewritten using the OR operator to produce the same result.

Hint: students should explain a query that can be written in two ways by using UNION and OR operators.

6.31 Apply the syntax for inserting data into a table.

Description of the data insert can be found in section 6.3.10. Studenst should simulate data entry by using the provided syntax

Case Study 2

For Exercises 6.32–6.40, use the Projects schema defined in the Exercises at the end of Chapter 5.

6.32 List all employees from BRICS countries in alphabetical order of surname.

SELECT * FROM Employee WHERE address LIKE ‘%Brazil%’ OR address LIKE ‘%Rusia%’ OR address LIKE ‘%India%’ OR address LIKE ‘%China%’ OR address LIKE ‘%South Africa%’ ORDER BY lName, fName;

6.33 List all the details of employees born between 1980–90.

SELECT * FROM Employee WHERE DOB like ‘%198%’;

6.34 List all managers who are female in alphabetical order of surname, and then first name.

SELECT * FROM Employee where position=‘Manager’ and sex=‘F’ ORDER BY lName, fName;

6.35 Remove all projects that are managed by the planning department.

DELETE FROM Project p

WHERE projNo IN (SELECT p.projNo

FROM project p, workson w

WHERE P.projno=w.projno);

6.36 Assume the planning department is going to be merged with the IT department. Update employee records to reflect the proposed change.

UPDATE employee

SET deptNO=”IT”

WHERE deptNo=”PL”;

6.37 Using the UNION command, list all projects that are managed by the IT and the HR department.

SELECT * FROM PROJECT

WHERE deptNo=”IT”

UNION

SELECT * FROM PROJECT

WHERE deptNo=”HR”;

6.38 Produce a report of the total hours worked by each female employee, arranged by department number and alphabetically by employee surname within each department.

SELECT e.lName, e.fName, hoursWorked

FROM WorksOn w, Employee e, Department d

WHERE e.deptNo = d.deptNo

AND e.empNo = w.empNo

AND e.sex=’F’

ORDER by d.deptNo, e.lName;

6.39 Remove all project from the database on which no employees worked.

DELETE FROM Project p

WHERE projNo IN (SELECT p.projNo

FROM project p, workson w

WHERE P.projno=w.projno);

6.40 List the total number of employees in each department for those departments with more than 10 employees. Create an appropriate heading for the columns of the results table.

SELECT COUNT(empNo) AS empCount, deptNo

FROM Employee

GROUP BY deptNo

HAVING COUNT(empNo) > 10;

Case Study 3

For Exercises 6.41–6.54, use the Library schema defined in the Exercises at the end of Chapter 5.

6.41 List all book titles.

SELECT title FROM Book;

6.42 List all borrower details.

SELECT * FROM Borrower;

6.43 List all books titles published between 2010 and 2014.

SELECT *

FROM book

WHERE year BETWEEN ‘2010’ AND ‘2014’;

6.44 Remove all books published before 1950 from the database.

DELETE FROM book

WHERE year < ‘1950’;

6.45 List all book titles that have never been borrowed by any borrower.

SELECT *

FROM BOOK

WHERE ISBN NOT IN (SELECT ISBN

FROM BOOKCOPY C, BOOKLOAN L

WHERE L.copyno=C.copyno);

6.46 List all book titles that contain the word ‘database’ and are available for loan.

SELECT b.ISBN, b.title, b.edition, b.year, c.available

FROM book b, bookcopy c

WHERE b.ISBN=c.ISBN AND b.title like ‘%database%’ AND c.available=’yes’;

6.47 List the names of borrowers with overdue books.

SELECT borrowerName

From Borrower bw, BookLoan bl

WHERE bw.borrowerNo = bl.borrowerNo and dateDue > today’s date;

6.48 How many copies of each book title are there?

SELECT b.title, count (b.copyno) AS numberOfcopies

FROM book b, bookcopy c

WHERE b.ISBN=c.ISBN

Group by b.title;

6.49 How many copies of ISBN “0-321-52306-7” are currently available?

SELECT COUNT(copyNo)

FROM BookCopy

WHERE available = ‘Y’ AND ISBN = ‘0-321-52306-7’;

6.50 How many times has the book with ISBN “0-321-52306-7” been borrowed?

SELECT COUNT(*)

FROM BookCopy bc, BookLoan bl

WHERE bc.copyNo = bl.copyNo AND ISBN = ‘0-321-52306-7’;

6.51 Produce a report of book titles that have been borrowed by “Peter Bloomfield”.

SELECT DISTINCT title

FROM Borrower bw, Book b, BookCopy bc, BookLoan bl

WHERE bw.borrowerNo = bl.borrowerNo AND bl.copyNo = bc.copyNo

AND bc.ISBN = b.ISBN AND borrowerName = ‘Peter Bloomfield’;

6.52 For each book title with more than 3 copies, list the names of library members who have borrowed them.

SELECT title, borrowerName

FROM Borrower bw, Book b, BookCopy bc, BookLoan bl

WHERE bw.borrowerNo = bl.borrowerNo AND bl.copyNo = bc.copyNo

AND bc.ISBN = b.ISBN AND EXISTS

(SELECT ISBN, COUNT(bc1.copyNo)

FROM BookCopy bc1

WHERE bc1.ISBN = bc.ISBN

GROUP BY bc1.ISBN

HAVING COUNT(bc1.copyNo) > 3);

6.53 Produce a report with the details of borrowers who currently have books overdue.

From Borrower bw, BookLoan bl

WHERE bw.borrowerNo = bl.borrowerNo and dateDue > today’s date;

6.54 Produce a report detailing how many times each book title has been borrowed.

SELECT ISBN, COUNT(*)

FROM BookCopy bc, BookLoan bl

WHERE bc.copyNo = bl.copyNo

GROUP BY ISBN;

# Chapter 7 SQL: Data Definition

#### Review Questions

7.1 What are the main SQL DDL statements?

The key SQL DDL statements are CREATE, ALTER and DROP. These statements are used for creating, modifying, and destroying database objects. See Section 7.3 for a detailed description.

7.2 Discuss the functionality and importance of the Integrity Enhancement Feature (IEF).

Required data: NOT NULL of CREATE/ALTER TABLE.

Domain constraint: CHECK clause of CREATE/ALTER TABLE and CREATE

DOMAIN.

Entity integrity: PRIMARY KEY (and UNIQUE) clause of CREATE/ALTER

TABLE.

Referential integrity: FOREIGN KEY clause of CREATE/ALTER TABLE.

General constraints: CHECK and UNIQUE clauses of CREATE/ALTER TABLE and

(CREATE) ASSERTION.

See Section 7.2.

7.3 What are the privileges commonly granted to database users?

Common privileges are:

• SELECT
• INSERT
• DELETE
• UPDATE
• REFERENCE
• USAGE

See Section 7.6.1 for a detailed description.

See Section 7.4.7.

7.5 Discuss the ways by which a transaction can complete.

Described in Section 7.5

7.6 What restrictions are necessary to ensure that a view is updatable?

ISO standard specifies the views that must be updatable in a system that conforms to the standard. Definition given in SQL standard is that a view is updatable if and only if:

• DISTINCT is not specified; that is, duplicate rows must not be eliminated from the query results.
• Every element in the SELECT list of the defining query is a column name (rather than a constant, expression, or aggregate function) and no column appears more than once.
• The FROM clause specifies only one table; that is, the view must have a single source table for which the user has the required privileges. If the source table is itself a view, then that view must satisfy these conditions. This, therefore, excludes any views based on a join, union (UNION), intersection (INTERSECT), or difference (EXCEPT).
• The WHERE clause does not include any nested SELECTs that reference the table in the FROM clause.
• There is no GROUP BY or HAVING clause in the defining query.

In addition, every row that is added through the view must not violate the integrity constraints of the base table (Section 7.4.5).

7.7 What is a materialized view and what are the advantages of a maintaining a materialized view rather than using the view resolution process?

Materialized view is a temporary table that is stored in the database to represent a view, which is maintained as the base table(s) are updated.

Advantages – may be faster than trying to perform view resolution.

– may also be useful for integrity checking and query optimisation.

See Section 7.4.8.

7.8 Describe the difference between discretionary and mandatory access control. What type of control mechanism does SQL support.

Discretionary – each user is given appropriate access rights (or privileges) on specific database objects.

Mandatory – each database object is assigned a certain classification level (e.g. Top Secret, Secret, Confidential, Unclassified) and each subject (e.g. user, application) is given a designated clearance level (Top Secret > Secret > Confidential > Unclassified).

SQL security mechanism is based on discretionary access control.

7.9 Discuss how the Access Control mechanism of SQL works.

Each user has an authorization identifier (allocated by DBA).

Each object has an owner. Initially, only owner has access to an object but the owner can pass privileges to carry out certain actions on to other users via the GRANT statement and take away given privileges using REVOKE.

#### Exercises

Answer the following questions using the relational schema from the Exercises at the end of Chapter 4.

7.10 Create the Hotel table using the integrity enhancement features of SQL.

CREATE DOMAIN HotelNumber AS CHAR(4);

CREATE TABLE Hotel(

hotelNo HotelNumber NOT NULL,

hotelName VARCHAR(20) NOT NULL,

city VARCHAR(50) NOT NULL,

PRIMARY KEY (hotelNo));

7.11 Now create the Room, Booking, and Guest tables using the integrity enhancement features of SQL with the following constraints:

(a) Type must be one of Single, Double, or Family.

(b) Price must be between £10 and £100.

(c) roomNo must be between 1 and 100.

(d) dateFrom and dateTo must be greater than today’s date.

(e) The same room cannot be double booked.

(f) The same guest cannot have overlapping bookings.

CREATE DOMAIN RoomType AS CHAR(1)

CHECK(VALUE IN (‘S’, ‘F’, ‘D’));

CREATE DOMAIN HotelNumbers AS HotelNumber

CHECK(VALUE IN (SELECT hotelNo FROM Hotel));

CREATE DOMAIN RoomPrice AS DECIMAL(5, 2)

CHECK(VALUE BETWEEN 10 AND 100);

CREATE DOMAIN RoomNumber AS VARCHAR(4)

CHECK(VALUE BETWEEN ‘1’ AND ‘100’);

CREATE TABLE Room(

roomNo RoomNumber NOT NULL,

hotelNo HotelNumbers NOT NULL,

type RoomType NOT NULL DEFAULT ‘S’

price RoomPrice NOT NULL,

PRIMARY KEY (roomNo, hotelNo),

FOREIGN KEY (hotelNo) REFERENCES Hotel

CREATE DOMAIN GuestNumber AS CHAR(4);

CREATE TABLE Guest(

guestNo GuestNumber NOT NULL,

guestName VARCHAR(20) NOT NULL,

CREATE DOMAIN GuestNumbers AS GuestNumber

CHECK(VALUE IN (SELECT guestNo FROM Guest));

CREATE DOMAIN BookingDate AS DATETIME

CHECK(VALUE > CURRENT_DATE);

CREATE TABLE Booking(

hotelNo HotelNumbers NOT NULL,

guestNo GuestNumbers NOT NULL,

dateFrom BookingDate NOT NULL,

dateTo BookingDate NULL,

roomNo RoomNumber NOT NULL,

PRIMARY KEY (hotelNo, guestNo, dateFrom),

FOREIGN KEY (hotelNo) REFERENCES Hotel

FOREIGN KEY (guestNo) REFERENCES Guest

ON DELETE NO ACTION ON UPDATE CASCADE,

FOREIGN KEY (hotelNo, roomNo) REFERENCES Room

ON DELETE NO ACTION ON UPDATE CASCADE,

CONSTRAINT RoomBooked

CHECK (NOT EXISTS ( SELECT *

FROM Booking b

WHERE b.dateTo > Booking.dateFrom AND

b.dateFrom < Booking.dateTo AND

b.roomNo = Booking.roomNo AND

b.hotelNo = Booking.hotelNo)),

CONSTRAINT GuestBooked

CHECK (NOT EXISTS ( SELECT *

FROM Booking b

WHERE b.dateTo > Booking.dateFrom AND

b.dateFrom < Booking.dateTo AND

b.guestNo = Booking.guestNo)));

7.12 Create a separate table with the same structure as the Booking table to hold archive records. Using the INSERT statement, copy the records from the Booking table to the archive table relating to bookings before 1st January 2013. Delete all bookings before 1st January 2013 from the Booking table.

CREATE TABLE BookingOld( hotelNo CHAR(4) NOT NULL,

guestNo CHAR(4) NOT NULL,

dateFrom DATETIME NOT NULL,

dateTo DATETIME NULL,

roomNo VARCHAR(4) NOT NULL);

INSERT INTO BookingOld

(SELECT * FROM Booking

WHERE dateTo < DATE’2013-01-01’);

DELETE FROM Booking

WHERE dateTo < DATE’2013-01-01’;

7.13 Assume that all hotels are loaded. Create a view containing the cheapest hotels in the world.

CREATE VIEW cheapesthotels (hotelNo, hotelName, city) AS select h.hotelNo, h.hotelName, h.city

FROM hotel h,room r WHERE h.hotelNo = r.hotelNo AND

price = (SELECT MIN (price) FROM room);

7.14 Create a view containing the guests who are from BRICS countries.

CREATE VIEW GuestFrombrics

AS Select *

FROM Guest

ORDER BY guestName;

7.15 Give the users Manager and Deputy full access to these views, with the privilege to pass the access on to other users.

GRANT ALL PRIVILEGES ON HotelData

TO Manager, Director WITH GRANT OPTION;

GRANT ALL PRIVILEGES ON BookingOutToday

TO Manager, Director WITH GRANT OPTION;

7.16 Give the user Accounts SELECT access to these views. Now revoke the access from this user.

GRANT SELECT ON HotelData TO Accounts;

GRANT SELECT ON BookingOutToday TO Accounts;

REVOKE SELECT ON HotelData FROM Accounts;

REVOKE SELECT ON BookingOutToday FROM Accounts;

7.17 Consider the following view defined on the Hotel schema:

CREATE VIEW HotelBookingCount (hotelNo, bookingCount)

AS SELECT h.hotelNo, COUNT(*)

FROM Hotel h, Room r, Booking b

WHERE h.hotelNo = r.hotelNo AND r.roomNo = b.roomNo

GROUP BY h.hotelNo;

For each of the following queries, state whether the query is valid and for the valid ones should how each of the queries would be mapped onto a query on the underling base tables.

(a) SELECT *

FROM HotelBookingCount;

SELECT h.hotelNo, COUNT(*)

FROM Hotel h, Room r, Booking b

WHERE h.hotelNo = r.hotelNo AND r.roomNo = b.roomNo

GROUP BY h.hotelNo;

(b) SELECT hotelNo

FROM HotelBookingCount

WHERE hotelNo = ‘H001’;

SELECT h.hotelNo

FROM Hotel h, Room r, Booking b

WHERE h.hotelNo = r.hotelNo AND r.roomNo = b.roomNo AND

h.hotelNo = ‘H001’

GROUP BY h.hotelNo;

(c) SELECT MIN(bookingCount)

FROM HotelBookingCount;

Invalid – bookingCount is based on an aggregate function, so cannot be used within another aggregate function.

(d) SELECT COUNT(*)

FROM HotelBookingCount;

Invalid for reason given above.

(e) SELECT hotelNo

FROM HotelBookingCount

WHERE bookingCount > 1000;

Invalid – bookingCount is based on an aggregate function, so cannot be used in the WHERE clause.

(f) SELECT hotelNo

FROM HotelBookingCount

ORDER BY bookingCount;

SELECT h.hotelNo, COUNT(*) AS bookingCount

FROM Hotel h, Room r, Booking b

WHERE h.hotelNo = r.hotelNo AND r.roomNo = b.roomNo

GROUP BY h.hotelNo

ORDER BY bookingCount;

7.19 Assume that we also have a table for suppliers:

Supplier (supplierNo, partNo, price)

and a view SupplierParts, which contains the distinct part numbers that are supplied by at least one supplier:

CREATE VIEW SupplierParts (partNo)

AS SELECT DISTINCT partNo

FROM Supplier s, Part p

WHERE s.partNo = p.partNo;

Discuss how you would maintain this as a materialized view and under what circumstances you would be able to maintain the view without having to access the underlying base tables Part and Supplier.

7.20 Analyze three different DBMSs of your choice. Identify objects that are available in the system catalog. Compare and contrast the object organization, name scheme, and the ways used to retrieve object description.

Upon successful analysis, student will be conversant with data dictionary and catalog found in different DBMSs. The report should indicate the student’s recommended DBMS.

7.21 Create the DreamHome rental database schema defined in Section 4.2.6 and insert the tuples shown in Figure 4.3.

This is a small student project, the result of which is dependent on the DBMS being used.

7.22 Use the view you created in exercise 7.13 to discuss how you would improve the performance of the SQL command

The SQL statement: ALTER TABLE hotel Add column address varchar (50) not null;

7.23 You are contracted to investigate queries with degraded performance to improve them. Based on the schemas created in previous exercises, discuss the criteria to decide for or against indexing.

Indexing is useful for attributes that are frequently retrieved; not for those used for data insertion

Case Study 2

7.24 Create the Projects schema using the integrity enhancement features of SQL with the following constraints:

(a) sex must be one of the single characters ‘M’ or ‘F’.

(b) position must be one of ‘Manager’, ‘Team Leader’, ‘Analyst’, or ‘Software Developer’.

(c) hoursWorked must be an integer value between 0 and 40.

CREATE SCHMEA Projects;

CREATE DOMAIN TableKey AS CHAR(5);

CREATE DOMAIN Name AS VARCHAR(20);

CREATE DOMAIN EmpDate AS DATE;

CREATE DOMAIN Sex AS CHAR(1) CHECK(VALUE IN (‘M’, ‘F’));

CREATE DOMAIN Position AS VARCHAR2(20) CHECK(VALUE IN (Manager’, ‘Team Leader’, ‘Analyst’, ‘Software Developer’));

CREATE DOMAIN DeptNo AS CHAR(5) CHECK (VALUE IN (SELECT deptNo FROM Department));

CREATE DOMAIN EmpNo AS CHAR(5) CHECK (VALUE IN (SELECT empNo FROM Employee));

CREATE DOMAIN hoursWorked AS SMALLINT CHECK(VALUE BETWEEN 0 AND 40);

CREATE TABLE Employee (

empNo TableKey NOT NULL,

fName Name NOT NULL,

lName Name NOT NULL,

DOB EmpDate NOT NULL,

sex Sex NOT NULL,

position Position NOT NULL,

deptNo DeptNo NOT NULL,

PRIMARY KEY (empNo)

FOREIGN KEY (deptNo) REFERENCES Department ON DELETE NO ACTION ON UPDATE NO ACTION);

CREATE TABLE Department (

deptNo TableKey NOT NULL,

deptName Name NOT NULL,

mgrEmpNo EmpNo NOT NULL,

PRIMARY KEY (deptNo),

FOREIGN KEY (empNo) REFERENCES Employee ON DELETE NO ACTION, ON UPDATE NO ACTION);

CREATE TABLE Project (

projNo TableKey NOT NULL,

projName Name NOT NULL,

deptNo DeptNo NOT NULL,

PRIMARY KEY (projNo),

FOREIGN KEY (deptNo) REFERENCES Department ON DELETE NO ACTION ON UPDATE NO ACTION);

CREATE TABLE WorksOn (

empNo EmpNo NOT NULL,

projNo ProjNo NOT NULL,

dateWorked EmpDate NOT NULL,

hoursWorked HoursWorked NOT NULL,

PRIMARY KEY (empNo, projNo, dateWorked),

FOREIGN KEY (empNo) REFERENCES Employee ON DELETE NO ACTION, ON UPDATE NO ACTION,

FOREIGN KEY (projNo) REFERENCES Project ON DELETE NO ACTION ON UPDATE NO ACTION);

7.25 Create a view consisting of projects managed by female managers and ordered by project number.

CREATE VIEW femalemanagedprojects (projNo, projName, fname, surname, deptName)

AS SELECT p.projNO, p.projName, e.fname, e.surname, d.deptName

FROM project p, department d, employee e

WHERE p.deptNo=d.deptNo AND d.deptNo=e.deptNo AND sex=’F’

ORDER BY projNo

7.26 Create a view consisting of the attributes empNo, fName, lName, projName, and hoursWorked attributes.

CREATE VIEW EmpWorksOn (empNo, fName, lName, projName, hoursWorked)

AS SELECT e.empNo, e.fName, e.lName, p.projName, w.hoursWorked

FROM Employee e, Project p, WorksOn w

WHERE e.empNo = w.empNo

AND p.projNo = w.projNo;

7.27 Consider the following view defined on the Projects schema:

CREATE VIEW EmpProject(empNo, projNo, totalHours)

AS SELECT w.empNo, w.projNo, SUM(hoursWorked)

FROM Employee e, Project p, WorksOn w

WHERE e.empNo _ w.empNo AND p.projNo _ w.projNo

GROUP BY w.empNo, w.projNo;

(a) SELECT *

FROM EmpProject;

(b) SELECT projNo

FROM EmpProject

WHERE projNo _ ‘SCCS’;

(c) SELECT COUNT(projNo)

FROM EmpProject

WHERE empNo _ ‘E1’;

(d) SELECT empNo, totalHours

FROM EmpProject

GROUP BY empNo;

General

7.28 Consider the following table:

Part (partNo, contract, partCost)

which represents the cost negotiated under each contract for a part (a part may have a different price under each contract). Now consider the following view ExpensiveParts, which contains the distinct part numbers for parts that cost more than £1000:

CREATE VIEW ExpensiveParts (partNo)

AS SELECT DISTINCT partNo

FROM Part

WHERE partCost > 1000;

Discuss how you would maintain this as a materialized view and under what circumstances you would be able to maintain the view without having to access the underlying base table Part.

If a row is inserted into Part with a partCost less than or equal to £1000, the view would not have to be updated. If a partNo is inserted into Part that is already in the view, no new record has to be inserted into the view (because of the DISTINCT keyword). Similarly for update. If a partNo is deleted from Part have to access the underlying base table to check if there is another partNo with same value, to determine whether row should be deleted from the view.

#### Review Questions

8.1 Advanced SQL deals with SQL/PSM and PL/SQL. What led to the introduction of SQL/PSM?

Section 8.1 provides history behind SQL/PSM introduction. The initial vertions of SQL had no programming constructs. SQL/PSM is an extension to SQL that supports the declaration of variables , has assignment statements and flow of control statements (IF-THEN ELSE-END IF; LOOP-EXIT WHEN-END LOOP; FOR-END LOOP; WHILE-END LOOP), and exceptions.

8.2 Describe the general structure of a PL/SQL block.

A PL/SQL block has up to three parts:

• An optional declaration part, in which variables, constants, cursors, and exceptions are defined and possibly initialized;
• A mandatory executable part, in which the variables are manipulated;
• An optional exception part, to handle any exceptions raised during execution.

8.3 Describe the control statements in PL/SQL. Give examples to illustrate your answers.

PL/SQL supports the usual conditional, iterative, and sequential flow-of-control mechanisms including:

Conditional IF statement

IF (position = ‘Manager’) THEN

salary := salary*1.05;

ELSE

salary := salary*1.03;

END IF;

Conditional CASE statement

CASE lowercase(x)

WHEN ‘a’ THEN x := 1;

WHEN ‘b’ THEN x := 2;

y := 0;

WHEN ‘default’ THEN x := 3;

END CASE;

Iteration statement (LOOP)

x:=1;

myLoop:

LOOP

x := x+1;

IF (x > 3) THEN

EXIT myLoop; — exit loop immediately

END LOOP myLoop;

— control resumes here

y := 2;

Iteration statement (WHILE and REPEAT)

WHILE (condition) LOOP

<SQL statement list>

END LOOP [labelName];

Iteration statement (FOR)

DECLARE

numberOfStaff NUMBER;

SELECT COUNT(*) INTO numberOfStaff FROM PropertyForRent

WHERE staffNo = ‘SG14’; myLoop1:

FOR iStaff IN 1 .. numberOfStaff LOOP

…..

END LOOP

myLoop1;

8.4 Describe how the PL/SQL statements differ from the SQL standard. Give examples to illustrate your answers.

PL/SQL (Procedural Language/SQL) is Oracle’s procedural extension to SQL.

There are two versions of PL/SQL: one is part of the Oracle server, and the other is a separate engine embedded in a number of Oracle tools. They are very similar toeach other and have the same programming constructs, syntax, and logic mechanisms, although PL/SQL for Oracle tools has some extensions to suit the requirementsof the particular tool (for example, PL/SQL has extensions for Oracle Forms).

PL/SQL has concepts similar to modern programming languages, such as variable and constant declarations, control structures, exception handling, and modularization. PL/SQL is a block-structured language: blocks can be entirely separate or nested within one another. The basic units that constitute a PL/SQL program are procedures, functions, and anonymous (unnamed) blocks.

8.5 What are SQL cursors? Give an example of the use of an SQL cursor.

PL/SQL uses cursors to allow the rows of a query result to be accessed one at a time. In effect, the cursor acts as a pointer to a particular row of the query result. The cursor can be advanced by 1 to access the next row. A cursor must be declared and opened before it can be used, and it must be closed to deactivate it after it is no longer required. Once the cursor has been opened, the rows of the query result can be retrieved one at a time using a FETCH statement, as opposed to a SELECT statement.

Only 0 units of this product remain