0% found this document useful (0 votes)
14 views

DBMS

The document discusses relational algebra and calculus. It defines basic operations like selection, projection, joins, and set operations. Examples of queries using these operations on sample relations are also provided.

Uploaded by

Gibrail Zaidi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

DBMS

The document discusses relational algebra and calculus. It defines basic operations like selection, projection, joins, and set operations. Examples of queries using these operations on sample relations are also provided.

Uploaded by

Gibrail Zaidi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT-2

Relational Algebra and Calculus


PRELIMINARIES

In defining relational algebra and calculus, the alternative of referring to fields by position is
more convenient than referring to fields by name: Queries often involve the computation of
intermediate results, which are themselves relation instances, and if we use field names to refer
to fields, the definition of query language constructs must specify the names of fields for all
intermediate relation instances.

We present a number of sample queries using the following schema:

Sailors (sid: integer, sname: string, rating: integer, age: real)


Boats (bid: integer, bname: string, color: string)
Reserves (sid: integer, bid: integer, day: date)

The key fields are underlined, and the domain of each field is listed after the field name.
Thus sid is the key for Sailors, bid is the key for Boats, and all three fields together form the key
for Reserves. Fields in an instance of one of these relations will be referred to by name, or
positionally, using the order in which they are listed above.

RELATIONAL ALGEBRA
Relational algebra is one of the two formal query languages associated with the re-
lational model. Queries in algebra are composed using a collection of operators. A fundamental
property is that every operator in the algebra accepts (one or two) rela-tion instances as
arguments and returns a relation instance as the result.
Each relational query describes a step-by-step procedure for computing the desired
answer, based on the order in which operators are applied in the query.
Selection and Projection

Relational algebra includes operators to select rows from a relation (σ) and to project columns
(π). These operations allow us to manipulate data in a single relation. Con - sider the instance

DATABASE MANGEMENT SYSTEMS Page 23


of the Sailors relation shown in Figure 4.2, denoted as S2. We can retrieve rows corresponding
to expert sailors by using the σ operator. The expression,

σrating>8(S2)
The selection operator σ specifies the tuples to retain through a selection condition. In general,
the selection condition is a boolean combination (i.e., an expression using the logical connectives
∧ and ∨) of terms that have the form attribute op constant or attribute1 op attribute2, where op is
one of the comparison operators <, <=, =, =, >=, or >.
The projection operator π allows us to extract columns from a relation; for example, we can find
out all sailor names and ratings by using π. The expression πsname,rating(S2)
Suppose that we wanted to find out only the ages of sailors. The expression
πage(S2)
a single tuple with age=35.0 appears in the result of the projection. This follows from
the definition of a relation as a set of tuples. However, our discussion of relational algebra and
calculus assumes that duplicate elimination is always done so that relations are always sets of
tuples.
Set Operations

The following standard operations on sets are also available in relational algebra: union (U),
intersection (∩), set-difference (−), and cross-product (×).

 Union: R u S returns a relation instance containing all tuples that occur in either
relation instance R or relation instance S (or both). R and S must be union-compatible, and
the schema of the result is defined to be identical to the schema of R.

 Intersection: R ∩ S returns a relation instance containing all tuples that occur in


both R and S. The relations R and S must be union-compatible, and the schema of the
result is defined to be identical to the schema of R.

 Set-difference: R − S returns a relation instance containing all tuples that occur in R


but not in S. The relations R and S must be union-compatible, and the schema of the result
is defined to be identical to the schema of R.
 Cross-product: R × S returns a relation instance whose schema contains all the fields of
R (in the same order as they appear in R) followed by all the fields of S

DATABASE MANGEMENT SYSTEMS Page 24


(in the same order as they appear in S). The result of R × S contains one tuple 〈r, s〉 (the
concatenation of tuples r and s) for each pair of tuples r ∈ R, s ∈ S. The cross-product
opertion is sometimes called Cartesian product.

sid sname rating age


31 Lubbe 8 55.5
58 Rusty 10 35.0

Figure 4.9 S1 ∩ S2
sid sname rating age
22 Dustin 7 45.0

Figure 4.10 S1 − S2

The result of the cross-product S1 × R1 is shown in Figure 4.11 The fields in S1


× R1 have the same domains as the corresponding fields in R1 and S1. In Figure 4.11 sid is
listed in parentheses to
emphasize that it is not an inherited field name; only the corresponding domain is
inherited.

(sid) sname rating age (sid) bid day


22 Dustin 7 45.0 22 101 10/10/96
22 Dustin 7 45.0 58 103 11/12/96
31 Lubber 8 55.5 22 101 10/10/96
31 Lubber 8 55.5 58 103 11/12/96
58 Rusty 10 35.0 22 101 10/10/96
58 Rusty 10 35.0 58 103 11/12/96
Figure 4.11 S1 × R1
Renaming

We introduce a renaming operator ρ for this purpose. The expression ρ(R(F ), E) takes an
arbitrary relational algebra expression E and returns an instance of a (new) relation called R. R
contains the same tuples as the result of E, and has the same schema as E, but some fields are
renamed. The field names in relation R are the same as in E, except for fields renamed in the
renaming list F.

For example, the expression ρ(C(1 → sid1, 5 → sid2), S1 × R1) returns a relation that contains
the tuples shown in Figure 4.11 and has the followi ng schema: C(sid1: integer, sname: string,
rating: integer, age: real, sid2: integer, bid: integer,day: dates).

DATABASE MANGEMENT SYSTEMS Page 25


Joins

The join operation is one of the most useful operations in relational algebra and is the most
commonly used way to combine information from two or more relations. Although a join can
be defined as a cross-product followed by selections and projections, joins arise much more
frequently in practice than plain cross-products.joins have received a lot of attention, and there
are several variants of the join operation.

Condition Joins

The most general version of the join operation accepts a join condition c and a pair of relation
instances as arguments, and returns a relation instance. The join condition is identical to a
selection condition in form. The operation is defined as follows:
R ⊲⊳c S = σc(R × S)

Thus ⊲⊳ is defined to be a cross-product followed by a selection. Note that the condition c can
(and typically does) refer to attributes of both R and S.
(sid) sname rating age (sid) bid day
22 Dustin 7 45.0 58 103 11/12/96
31 Lubber 8 55.5 58 103 11/12/96
Figure 4.12 S1 ⊲⊳S1.sid<R1.sid R1

Equijoin

A common special case of the join operation R ⊲⊳ S is when the join condition con-sists solely
of equalities (connected by ∧) of the form R.name1 = S.name2, that is, equalities between two
fields in R and S. In this case, obviously, there is some redun-dancy in retaining both attributes
in the result.
Natural Join

A further special case of the join operation R ⊲⊳ S is an equijoin in which equalities are
specified on all fields having the same name in R and S. In this case, we can simply omit the
join condition; the default is that the join condition is a collection of equalities on all common
fields.

DATABASE MANGEMENT SYSTEMS Page 26


Division

The division operator is useful for expressing certain kinds of queries, for example: “Find the
names of sailors who have reserved all boats.” Understanding how to use the basic operators of
the algebra to define division is a useful exercise.

(Q1) Find the names of sailors who have reserved boat 103.

This query can be written as follows:


πsname((σbid=103Reserves) ⊲⊳Sailors)
We first compute the set of tuples in Reserves with bid = 103 and then take the natural join
of this set with Sailors. This expression can be evaluated on instances of Reserves and
Sailors. Evaluated on the instances R2 and S3, it yields a relation

(Q2) Find the names of sailors who have reserved a red boat.
πsname((σcolor=′red′ Boats) ⊲⊳ Reserves ⊲⊳ Sailors
This query involves a series of two joins. First we choose (tuples describing) red boats.

(Q3) Find the colors of boats reserved by Lubber.


πcolor((σsname=′Lubber′ Sailors) ⊲⊳ Reserves ⊲⊳ Boats)
This query is very similar to the query we used to compute sailors who reserved red boats. On
instances B1, R2, and S3, the query will return the colors green and red.

(Q4) Find the names of sailors who have reserved at least one boat.
πsname(Sailors ⊲⊳ Reserves)

(Q5) Find the names of sailors who have reserved a red or a green boat.
ρ(T empboats, (σcolor=′red′ Boats) U (σcolor=′green′ Boats))
πsname(Tempboats ⊲⊳Reserves ⊲⊳Sailors)

(Q6) Find the names of sailors who have reserved a red and a green boat
ρ(T empboats2, (σcolor=′red′ Boats) ∩ (σcolor=′green′ Boats))
πsname(Tempboats2 ⊲⊳ Reserves ⊲⊳ Sailors)

However, this solution is incorrect —it instead tries to compute sailors who have re-served a boat
that is both red and green.
ρ(T empred, πsid((σcolor=′red′ Boats) ⊲⊳ Reserves))
ρ(T empgreen, πsid((σcolor=′green′ Boats) ⊲⊳ Reserves))
πsname((Tempred ∩ Tempgreen) ⊲⊳ Sailors)

(Q7) Find the names of sailors who have reserved at least two boats.

DATABASE MANGEMENT SYSTEMS Page 27


ρ(Reservations, πsid,sname,bid(Sailors ⊲⊳ Reserves))
ρ(Reservationpairs(1 → sid1, 2 → sname1, 3 → bid1, 4 → sid2,

5 → sname2,6 → bid2),Reservations × Reservations)

πsname1σ(sid1=sid2) ∩ (bid1=bid2)Reservationpairs

(Q8) Find the sids of sailors with age over 20 who have not reserved a red boat.
πsid(σage>20Sailors) −πsid((σcolor=′red′ Boats) ⊲⊳ Reserves ⊲⊳ Sailors)
This query illustrates the use of the set-difference operator. Again, we use the fact that sid is the
key for Sailors.

(Q9) Find the names of sailors who have reserved all boats.

The use of the word all (or every) is a good indication that the division operation might be
applicable:
ρ(T empsids, (πsid,bidReserves)/(πbidBoats))
πsname(Tempsids ⊲⊳ Sailors)
(Q10) Find the names of sailors who have reserved all boats called Interlake.
ρ(T empsids, (πsid,bidReserves)/(πbid(σbname=′Interlake′ Boats)))
πsname(Tempsids ⊲⊳ Sailors)

RELATIONAL CALCULUS

Relational calculus is an alternative to relational algebra. In contrast to the algebra, which is


procedural, the calculus is nonprocedural, or declarative, in that it allows us to describe the set of
answers without being explicit about how they should be computed.

Tuple Relational Calculus

A tuple variable is a variable that takes on tuples of a particular relation schema as values. That
is, every value assigned to a given tuple variable has the same number and type of fields.

(Q11) Find all sailors with a rating above 7.


{S I S E Sailors ^ S. rating > 7}
with respect to the given database instance, F
evaluates to (or simply ‘is’) true if one of the
following holds:
 F is an atomic formula R  Rel, and R is assigned a tuple in the instance of relation Rel.

DATABASE MANGEMENT SYSTEMS Page 28


 F is a comparison R.a op S.b, R.a op constant, or constant op R.a, and the tuples
assigned to R and S have field values R.a and S.b that make the comparison true.

 F is of the form ¬p, and p is not true; or of the form p ^ q, and both p and q are true;
or of the form p V q, and one of them is true, or of the form p  q and q is true
whenever4 p is true.

 F is of the form R(p(R)), and there is some assignment of tuples to the free variables
in p(R), including the variable R,5 that makes the formula p(R) true.

 F is of the form R(p(R)), and there is some assignment of tuples to the free
variables in p(R) that makes the formula p(R) true no matter what tuple is assigned to
R.

(Q12) Find the names and ages of sailors with a rating above 7 .

{P | S  Sailors(S.rating > 7  P.name = S.sname  P.age = S.age)}


This query illustrates a useful convention: P is considered to be a tuple variable with exactly
two fields, which are called name and age, because these are the only fields of P that are
mentioned and P does not range over any of the relations in the query; that is, there is no
subformula of the form P  Relname.

(Q13) Find the sailor name, boat id, and reservation date for each reservation
{P | R Reserves S  Sailors
(R.sid = S.sid  P.bid = R.bid  P.day = R.day  P.sname = S.sname)}

(Q1) Find the names of sailors who have reserved boat 103.

{P | S  Sailors R  Reserves(R.sid = S.sid  R.bid = 103 P.sname = S.sname)}

This query can be read as follows: “Retrieve all sailor tuples for which there exists
a tuple in Reserves, having the same value in the sid field, and with bid = 103.”

(Q2) Find the names of sailors who have reserved a red boat.
{P | S  Sailors R  Reserves(R.sid = S.sid  P.sname = S.sname
 B Boats(B.bid = R.bid  B.color =′red′))}

DATABASE MANGEMENT SYSTEMS Page 29


This query can be read as follows: “Retrieve all sailor tuples S for which there exist tuples R in
Reserves and B in Boats such that S.sid = R.sid, R.bid = B.bid, and B.color =′red′.”

(Q7) Find the names of sailors who have reserved at least two boats. {P |
S  Sailors R1  Reserves R2  Reserves (S.sid = R1.sid
 R1.sid = R2.sid  R1.bid ≠ R2.bid  P.sname = S.sname)}
(Q9) Find the names of sailors who have reserved all boats.
{P | S  Sailors B  Boats
(R  Reserves(S.sid = R.sid R.bid = B.bid P.sname = S.sname))}
(Q14) Find sailors who have reserved all red boats.
{S | S  Sailors  B  Boats
(B.color =′red′ (R ∈ Reserves(S.sid = R.sid  R.bid = B.bid)))}

Domain Relational Calculus

A domain variable is a variable that ranges over the values in the domain of some attribute (e.g.,
the variable can be assigned an integer if it appears in an attribute

whose domain is the set of integers). A DRC query has the form {〈 x1, x2, . . . , xn〉 |

p(〈 x1,x2,.. ., xn〉 )}, where each xi is either a domain variable or a constant and p(〈 x1,x2,.. .,

xn〉) denotes a DRC formula whose only free variables are thevari-ables among the xi, 1 ≤ i ≤ n.

The result of this query is the set of all tuples 〈x1, x2,.. .,xn〉 for which the formula evaluates to

true.

(Q1) Find the names of sailors who have reserved boat 103.
{〈N 〉 | I, T, A(〈I, N, T, A〉  Sailors
Ir, Br, D(〈Ir, Br, D〉  Reserves  Ir = I  Br =
103))} (Q2) Find the names of sailors who have reserved a red boat.

{〈N 〉 | I, T, A(〈I, N, T, A〉  Sailors

I, Br, D〉  Reserves  〈Br, BN,′red′〉  Boats)}


(Q7) Find the names of sailors who have reserved at least two boats.
{〈N 〉 | I, T, A(〈I, N, T, A〉  Sailors  Br1, Br2, D1, D2(〈I, Br1, D1〉
Reserves 〈I, Br2, D2〉  Reserves  Br1 = Br2)

DATABASE MANGEMENT SYSTEMS Page 30


(Q9) Find the names of sailors who have reserved all boats.
{〈N 〉 | I, T, A(〈I, N, T, A〉  Sailors 
B, BN, C(¬(〈B, BN, C〉  Boats) 

(〈Ir, Br, D〉 Reserves(I = Ir  Br = B))))}

THE FORM OF A BASIC SQL QUERY

This section presents the syntax of a simple SQL query and explains its meaning through a
conceptual evaluation strategy. A conceptual evaluation strategy is a way to evaluate the query
that is intended to be easy to understand, rather than efficient. A DBMS would typically execute
a query in a different and more efficient way.

Sid sname rating age sid bid day


22 Dustin 7 45.0 22 101 10/10/98
29 Brutus 1 33.0 22 102 10/10/98
31 Lubber 8 55.5 22 103 10/8/98
32 Andy 8 25.5 22 104 10/7/98
58 Rusty 10 35.0 31 102 11/10/98
64 Horatio 7 35.0 31 103 11/6/98
71 Zorba 10 16.0 31 104 11/12/98
74 Horatio 9 35.0 64 101 9/5/98
85 Art 3 25.5 64 102 9/8/98
95 Bob 3 63.5 74 103 9/8/98

Figure 5.1An Instance S 3 of Sailors Figure 5.2 An Instance R2 of Reserves

bid bname color


101 Interlake blue
102 Interlake red
103 Clipper green
104 Marine red

DATABASE MANGEMENT SYSTEMS Page 31


(Q15) Find the names and ages of all sailors.

SELECT DISTINCT S.sname, S.age FROM Sailors S

The answer to this query with and without the keyword DISTINCT on instance S3 of Sailors is
shown in Figures 5.4 and 5.5. The only difference is that the tuple for Horatio appears twice if
DISTINCT is omitted; this is because there are two sailors called Horatio and age 35.

(Q11) Find all sailors with a rating above 7.

SELECT S.sid, S.sname, S.rating, S.age FROM Sailors AS S WHERE S.rating > 7

(Q16) Find the sids of sailors who have reserved a red boat.

SELECT R.sid FROM Boats B, Reserves R WHERE B.bid = R.bid AND B.color = ‘red’

(Q2) Find the names of sailors who have reserved a red boat.

SELECT S.sname FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND
R.bid = B.bid AND B.color = ‘red’

(Q3) Find the colors of boats reserved by Lubber.

SELECT B.color FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid


AND R.bid = B.bid AND S.sname = ‘Lubber’

(Q4) Find the names of sailors who have reserved at least one boat.

SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid = R.sid


Expressions and Strings in the SELECT Command

SQL supports a more general version of the select-list than just a list of columns. Each item in a
select-list can be of the form expression AS column name, where expression is any arithmetic or
string expression over column names (possibly prefixed by range variables) and constants.

(Q5) Compute increments for the ratings of persons who have sailed two different boats on
the same day.

DATABASE MANGEMENT SYSTEMS Page 32


SELECT S.sname, S.rating+1 AS rating FROM Sailors S, Reserves R1, Reserves R2
WHERE S.sid = R1.sid AND S.sid = R2.sid AND R1.day = R2.day AND R1.bid <>
R2.bid
Also, each item in a qualification can be as general as expression1 = expression2.

SELECT S1.sname AS name1, S2.sname AS name2 FROM Sailors S1, Sailors


S2 WHERE 2*S1.rating = S2.rating-1.

(Q6) Find the ages of sailors whose name begins and ends with B and has at least three
characters.

SELECT S.age FROM Sailors S WHERE S.sname LIKE ‘B %B’

The only such sailor is Bob, and his age is 63.5.


UNION, INTERSECT, AND EXCEPT

SQL provides three set-manipulation constructs that extend the basic query form pre-sented
earlier. Since the answer to a query is a multiset of rows, it is natural to consider the use of
operations such as union, intersection, and difference. SQL supports these operations under the
names UNION, INTERSECT, and EXCEPT.4 SQL also provides other set operations: IN (to
check if an element is in a given set),op ANY,op ALL(tocom-pare a value with the elements in a
given set, using comparison operator op), and EXISTS (to check if a set is empty). IN and
EXISTS can be prefixed by NOT, with the obvious modification to their meaning. We cover
UNION, INTERSECT, and EXCEPT in this section. Consider the following query:

(Q1) Find the names of sailors who have reserved both a red and a green boat.

SELECT S.sname FROM Sailors S, Reserves R1, Boats B1, Reserves R2, Boats
B2 WHERE S.sid = R1.sid AND R1.bid = B1.bid AND S.sid = R2.sid AND R2.bid
= B2.bid AND B1.color=‘red’ AND B2.color = ‘green’

(Q2) Find the sids of all sailors who have reserved red boats but not green boats.

SELECT S.sid FROM Sailors S, Reserves R, Boats B


WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = ‘red’ EXCEPT
SELECT S2.sid FROM Sailors S2, Reserves R2, Boats B2 WHERE
S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = ‘green’

DATABASE MANGEMENT SYSTEMS Page 33


NESTED QUERIES

A nested query is a querythat has another query embedded within it; the embedded query is
called a subquery.

(Q1) Find the names of sailors who have reserved boat 103.

SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid = 103 )
(Q2) Find the names of sailors who have reserved a red boat.

SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid IN ( SELECT B.bid
FROM Boats B
WHERE B.color = ‘red’ )

(Q3) Find the names of sailors who have not reserved a red boat.
SELECT S.sname
FROM Sailors S
WHERE S.sid NOT IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid IN ( SELECT B.bid
FROM Boats B
WHERE B.color = ‘red’ )

DATABASE MANGEMENT SYSTEMS Page 34


Correlated Nested Queries

In the nested queries that we have seen thus far, the inner subquery has been completely
independent of the outer query:

(Q1) Find the names of sailors who have reserved boat number 103.
SELECT S.sname
FROM Sailors S
WHERE EXISTS ( SELECT *
FROM Reserves R
WHERE R.bid = 103
AND R.sid = S.sid )

Set-Comparison Operators

(Q1) Find sailors whose rating is better than some sailor called Horatio.

SELECT S.sid
FROM Sailors S
WHERE S.rating > ANY ( SELECT S2.rating
FROM Sailors S2
WHERE S2.sname = ‘Horatio’ )

(Q2) Find the sailors with the highest rating .

SELECT S.sid
FROM Sailors S
WHERE S.rating >= ALL ( SELECT S2.rating
FROM Sailors S2 )

More Examples of Nested Queries

(Q1) Find the names of sailors who have reserved both a red and a green boat.

SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = ‘red’
AND S.sid IN ( SELECT S2.sid
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid
AND B2.color = ‘green’ )

DATABASE MANGEMENT SYSTEMS Page 35


(
Q9) Find the names of sailors who have reserved all boats.

SELECT S.sname
FROM Sailors S
WHERE NOT EXISTS (( SELECT B.bid
FROM Boats B )
EXCEPT
(SELECT R.bid
FROM Reserves R
WHERE R.sid = S.sid ))

AGGREGATE OPERATORS

We now consider a powerful class of constructs for computing aggregate values such as MIN
and SUM.

1. COUNT ([DISTINCT] A): The number of (unique) values in the A column.


2. SUM ([DISTINCT] A): The sum of all (unique) values in the A column.
3. AVG ([DISTINCT] A): The average of all (unique) values in the A column.
4. MAX (A): The maximum value in the A column.
5. MIN (A): The minimum value in the A column.

(Q1) Find the average age of all sailors.

SELECT AVG (S.age)


FROM Sailors S

(Q2) Find the average age of sailors with a rating of 10.

SELECT AVG (S.age)


FROM Sailors S
WHERE S.rating = 10

SELECT S.sname, MAX (S.age)


FROM Sailors S

Q3) Count the number of sailors.


SELECT COUNT (*)
FROM Sailors S

DATABASE MANGEMENT SYSTEMS Page 36


The GROUP BY and HAVING Clauses

we want to apply aggregate operations to each of a number of groups of rows in a relation,


where the number of groups depends on the relation instance (i.e., is not known in advance).
(Q31) Find the age of the youngest sailor for each rating level.

SELECT MIN (S.age)


FROM Sailors S
WHERE S.rating = i

Q32) Find the age of the youngest sailor who is eligible to vote (i.e., is at least 18 years old)
for each rating level with at least two such sailors.

SELECT S.rating, MIN (S.age) AS minageGROUP BY S.rating


HAVING COUNT (*) > 1

More Examples of Aggregate Queries

Q3) For each red boat, find the number of reservations for this boat.
SELECT B.bid, COUNT (*) AS sailorcount FROM Boats B, Reserves R
WHERE R.bid = B.bid AND B.color = ‘red’ GROUP BY B.bid

SELECT B.bid, COUNT (*) AS sailorcount FROM Boats B, Reserves R


WHERE R.bid = B.bid GROUP BY B.bid HAVING B.color = ‘red’

(Q4) Find the average age of sailors for each rating level that has at least two sailors.

SELECT S.rating, AVG (S.age) AS avgage


FROM Sailors S
GROUP BY S.rating
HAVING COUNT (*) > 1

(Q5) Find the average age of sailors who are of voting age (i.e., at least 18 years old) for each
rating level that has at least two sailors.
SELECT S.rating, AVG ( S.age ) AS avgage
FROM Sailors S
WHERE S. age >= 18
GROUP BY S.rating
HAVING 1 < ( SELECT COUNT (*)

DATABASE MANGEMENT SYSTEMS Page 37


FROM Sailors S2 WHERE S.rating = S2.rating

(Q6) Find the average age of sailors who are of voting age (i.e., at least 18 years old) for
each rating level that has at least two such sailors.
SELECT S.rating, AVG ( S.age ) AS avgage
FROM Sailors S
WHERE S. age > 18
GROUP BY S.rating

HAVING 1 < ( SELECT COUNT (*)


FROM Sailors S2
WHERE S.rating = S2.rating AND S2.age >= 18 )

The above formulation of the query reflects the fact that it is a variant of Q35. The answer to
Q36 on instance S3 is shown in Figure 5.16. It differs from the answer to Q35 in that there is no
tuple for rating 10, since there is only one tuple with rating 10 and age ≥ 18.

SELECT S.rating, AVG ( S.age ) AS avgage


FROM Sailors S
WHERE S. age > 18
GROUP BY S.rating
HAVING COUNT (*) > 1

This formulation of Q36 takes advantage of the fact that the WHERE clause is applied before
grouping is done; thus, only sailors with age > 18 are left when grouping is done. It is
instructive to consider yet another way of writing this query:
SELECT Temp.rating, Temp.avgage
FROM ( SELECT S.rating, AVG ( S.age ) AS
avgage, COUNT (*) AS
ratingcount
FROM Sailors S WHERE S. age > 18 GROUP BY S.rating ) AS Temp
WHERE Temp.ratingcount > 1

NULL VALUES

we have assumed that column values in a row are always known. In practice column values can
be unknown. For example, when a sailor, say Dan, joins a yacht club, he may not yet have a
rating assigned. Since the definition for the Sailors table has a rating column, what row should
we insert for Dan? What is needed here is a special value that denotes unknown.

DATABASE MANGEMENT SYSTEMS Page 38


SQL provides a special column value called null to use in such situations. We use null when
the column value is either unknown or inapplicable. Using our Sailor table definition, we might
enter the row 〈 98, Dan, null, 39〉 to represent Dan. The presence of null values complicates
many issues, and we consider the impact of null values on SQL in this section.
Comparisons Using Null Values

Consider a comparison such as rating = 8. If this is applied to the row for Dan, is this condition
true or false? Since Dan’s rating is unknown, it is reasonable to say that this comparison should
evaluate to the value unknown.

SQL also provides a special comparison operator IS NULL to test whether a column value is
null; for example, we can say rating IS NULL, which would evaluate to true on the row
representing Dan. We can also say rating IS NOT NULL, which would evaluate to false on the
row for Dan.

Logical Connectives AND, OR, and NOT

Now, what about boolean expressions such as rating = 8 OR age < 40 and rating = 8 AND
age < 40? Considering the row for Dan again, because age < 40, the first expression evaluates to
true regardless of the value of rating, but what about the second? We can only say unknown.

INTRODUCTION TO VIEWS

A view is a table whose rows are not explicitly stored in the database but are computed as needed
from a view de nition. Consider the Students and Enrolled relations.

CREATE VIEW B-Students (name, sid, course)

AS SELECT S.sname, S.sid, E.cid


FROM Students S, Enrolled E
WHERE S.sid = E.sid AND E.grade = `B'

This view can be used just like a base table, or explicitly stored table, in de ning new queries or
views.

DATABASE MANGEMENT SYSTEMS Page 39


DESTROYING/ALTERING TABLES AND VIEWS

If we decide that we no longer need a base table and want to destroy it (i.e., delete all the rows
and remove the table de nition information), we can use the DROP TABLE command. For
example, DROP TABLE Students RESTRICT destroys the Students table unless some view or
integrity constraint refers to Students; if so, the command fails. If the keyword RESTRICT is
replaced by CASCADE, Students is dropped and any ref-erencing views or integrity constraints
are (recursively) dropped as well; one of these two keywords must always be speci ed. A view
can be dropped using the DROP VIEW command, which is just like DROP TABLE.

ALTER TABLE modi es the structure of an existing table. To add a column called maiden-name
to Students, for example, we would use the following command:

ALTER TABLE Students


ADD COLUMN maiden-name CHAR(10)

TRIGGERS

A trigger is a procedure that is automatically invoked by the DBMS in response to specified


changes to the database, and is typically specified by the DBA. A database that has a set of
associated triggers is called an active database. A trigger description contains three parts:

Event: A change to the database that activates the trigger.


Condition: A query or test that is run when the trigger is activated.
Action: A procedure that is executed when the trigger is activated and its con-dition is
true.

A trigger action can examine the answers to the query in the condition part of the trigger, refer to
old and new values of tuples modified by the statement activating the trigger, execute new
queries, and make changes to the database.

Examples of Triggers in SQL

DATABASE MANGEMENT SYSTEMS Page 40


The examples shown in Figure 5.19, written using Oracle 7 Server syntax for defining triggers,
illustrate the basic concepts behind triggers. (The SQL:1999 syntax for these triggers is similar;
we will see an example using SQL:1999 syntax shortly.) The trigger called init count initializes a
counter variable before every execution of an INSERT statement that adds tuples to the Students
relation. The trigger called incr count increments the counter for each inserted tuple that satisfies
the condition age < 18.

CREATE TRIGGER init count BEFORE INSERT ON Students /* Event */


DECLARE
count INTEGER;
BEGIN /* Action */
count := 0;
END
CREATE TRIGGER incr count AFTER INSERT ON Students /* Event */
WHEN (new.age < 18) /* Condition; ‘new’ is just-inserted tuple */
FOR EACH ROW
BEGIN /* Action; a procedure in Oracle’s PL/SQL syntax */ count :=
count + 1;
END

(identifying the modified table, Students, and the kind of modifying statement, an
INSERT), and the third field is the number of inserted Students tuples with age < 18.
(The trigger in Figure 5.19 only computes the count; an additional trigger is required to
insert the appropriate tuple into the statistics table.)

CREATE TRIGGER set count AFTER INSERT ON Students /* Event */


REFERENCING NEW TABLE AS InsertedTuples
FOR EACH STATEMENT
INSERT /* Action */
INTO StatisticsTable(ModifiedTable, ModificationType, Count) SELECT
‘Students’, ‘Insert’, COUNT *
FROM InsertedTuples I
WHERE I.age < 18

DATABASE MANGEMENT SYSTEMS Page 41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy