








































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









































One of the most important applications for computers is storing and managing information. The manner in which information is organized can have a profound effect on how easy it is to access and manage. Perhaps the simplest but most versatile way to organize information is to store it in tables. The relational model is centered on this idea: the organization of data into collections of two-dimensional tables called “relations.” We can also think of the relational model as a generalization of the set data model that we discussed in Chapter 7, extending binary relations to relations of arbitrary arity. Originally, the relational data model was developed for databases — that is, Database information stored over a long period of time in a computer system — and for database management systems, the software that allows people to store, access, and modify this information. Databases still provide us with important motivation for understanding the relational data model. They are found today not only in their original, large-scale applications such as airline reservation systems or banking sys- tems, but in desktop computers handling individual activities such as maintaining expense records, homework grades, and many other uses. Other kinds of software besides database systems can make good use of tables of information as well, and the relational data model helps us design these tables and develop the data structures that we need to access them efficiently. For example, such tables are used by compilers to store information about the variables used in the program, keeping track of their data type and of the functions for which they are defined.
There are three intertwined themes in this chapter. First, we introduce you to the design of information structures using the relational model. We shall see that F Tables of information, called “relations,” are a powerful and flexible way to represent information (Section 8.2).
F An important part of the design process is selecting “attributes,” or properties of the described objects, that can be kept together in a table, without introduc- ing “redundancy,” a situation where a fact is repeated several times (Section 8.2). F The columns of a table are named by attributes. The “key” for a table (or relation) is a set of attributes whose values uniquely determine the values of a whole row of the table. Knowing the key for a table helps us design data structures for the table (Section 8.3).
F Indexes are data structures that help us retrieve or change information in tables quickly. Judicious selection of indexes is essential if we want to operate on our tables efficiently (Sections 8.4, 8.5, and 8.6).
The second theme is the way data structures can speed access to information. We shall learn that F Primary index structures, such as hash tables, arrange the various rows of a table in the memory of a computer. The right structure can enhance efficiency for many operations (Section 8.4).
F Secondary indexes provide additional structure and help perform other opera- tions efficiently (Sections 8.5 and 8.6). Our third theme is a very high-level way of expressing “queries,” that is, questions about the information in a collection of tables. The following points are made:
F Relational algebra is a powerful notation for expressing queries without giving details about how the operations are to be carried out (Section 8.7).
F The operators of relational algebra can be implemented using the data struc- tures discussed in this chapter (Section 8.8). F In order that we may get answers quickly to queries expressed in relational algebra, it is often necessary to “optimize” them, that is, to use algebraic laws to convert an expression into an equivalent expression with a faster evaluation strategy. We learn some of the techniques in Section 8.9.
Section 7.7 introduced the notion of a “relation” as a set of tuples. Each tuple of a relation is a list of components, and each relation has a fixed arity, which is the number of components each of its tuples has. While we studied primarily binary relations, that is, relations of arity 2, we indicated that relations of other arities were possible, and indeed can be quite useful. The relational model uses a notion of “relation” that is closely related to this set-theoretic definition, but differs in some details. In the relational model, in- formation is stored in tables such as the one shown in Fig. 8.1. This particular table represents data that might be stored in a registrar’s computer about courses, students who have taken them, and the grades they obtained. Attribute The columns of the table are given names, called attributes. In Fig. 8.1, the attributes are Course, StudentId, and Grade.
As sets, there are a variety of ways to represent relations by data structures. A table looks as though its rows should be structures, with fields corresponding to the column names. For example, the tuples in the relation of Fig. 8.1 could be represented by structures of the type struct CSG { char Course[5]; int StudentId; char Grade[2]; }; The table itself could be represented in any of a number of ways, such as
A collection of relations is called a database. The first thing we need to do when designing a database for some application is to decide on how the information to be stored should be arranged into tables. Design of a database, like all design problems, is a matter of business needs and judgment. In an example to follow, we shall expand our application of a registrar’s database involving courses, and thereby expose some of the principles of good database design. Some of the most powerful operations on a database involve the use of several relations to represent coordinated types of data. By setting up appropriate data structures, we can jump from one relation to another efficiently, and thus obtain information from the database that we could not uncover from a single relation. The data structures and algorithms involved in “navigating” among relations will be discussed in Sections 8.6 and 8.8. The set of schemes for the various relations in a database is called the scheme Database of the database. Notice the difference between the scheme for the database, which scheme tells us something about how information is organized in the database, and the set of tuples in each relation, which is the actual information stored in the database.
{Course, StudentId, Grade} with four other relations. Their schemes and intuitive meanings are:
We saw in Chapter 7 some of the most important operations performed on relations and functions; they were called insert, delete, and lookup, although their appropri- ate meanings differed, depending on whether we were dealing with a dictionary, a function, or a binary relation. There is a great variety of operations one can perform on database relations, especially on combinations of two or more relations, and we shall give a feel for this spectrum of operations in Section 8.7. For the moment, let us focus on the basic operations that we might perform on a single relation. These are a natural generalization of the operations discussed in the previous chapter.
(“CS101”, ∗, ∗), Course-Day-Hour
That operation would delete the first three tuples of the relation in Fig. 8.2(c), because their first components each are the same value as the first component of the specification, and their second and third components all match ∗, as any values do.
database: a) lookup
(“CS101”, 12345 , ∗), Course-StudentId-Grade
finds the grade of the student with ID 12345 in CS101. Formally, the result is the one matching tuple, namely the first tuple in Fig. 8.1. b) lookup
(“CS205”, “CS120”), Course-Prerequisite
asks whether CS120 is a prerequisite of CS205. Formally, it produces as an answer either the single tuple (“CS205”, “CS120”) if that tuple is in the relation, or the empty set if not. For the particular relation of Fig. 8.2(b), the empty set is the answer. c) delete
(“CS101”, ∗), Course-Room
drops the first tuple from the relation of Fig. 8.2(d). d) insert
(“CS205”, “CS120”), Course-Prerequisite
makes CS120 a prerequisite of CS205. e) insert
(“CS205”, “CS101”), Course-Prerequisite
has no effect on the relation of Fig. 8.2(b), because the inserted tuple is already there. F
In much of the rest of this chapter, we are going to discuss the issue of how one selects a data structure for a relation. We have already seen some of the problem when we discussed the implementation of binary relations in Section 7.9. The relation Variety-Pollinizer was given a hash table on Variety as its data structure, and we observed that the structure was very useful for answering queries like lookup
(“Wickson”, ∗), Variety-Pollinizer
because the value “Wickson” lets us find a specific bucket in which to search. But that structure was of no help answering queries like lookup
(∗, “Wickson”), Variety-Pollinizer
because we would have to look in all buckets. Whether a hash table on Variety is an adequate data structure depends on the expected mix of queries. If we expect the variety always to be specified, then a hash table is adequate, and if we expect the variety sometimes not to be specified, as in the preceding query, then we need to design a more powerful data structure. The selection of a data structure is one of the essential design issues we tackle in this chapter. In the next section, we shall generalize the basic data structures for functions and relations from Sections 7.8 and 7.9, to allow for several attributes in either the domain or the range. These structures will be called “primary in- dex structures.” Then, in Section 8.5 we introduce “secondary index structures,” which are additional structures that allow us to answer a greater variety of queries efficiently. At that point, we shall see how both the above queries, and others we might ask about the Variety-Pollinizer relation, can be answered efficiently, that is, in about as much time as it takes to list all the answers.
An important issue when we use the relational data model is how we select an appropriate database scheme. For instance, why did we separate information about courses into five relations, rather than have one table with scheme
{Course, StudentId, Grade, Prerequisite, Day, Hour, Room}
The intuitive reason is that
F If we combine into one relation scheme information of two independent types, we may be forced to repeat the same fact many times.
For example, prerequisite information about a course is independent of day and hour information. If we were to combine prerequisite and day-hour information, we would have to list the prerequisites for a course in conjunction with every meeting of the course, and vice versa. Then the data about EE200 found in Fig. 8.2(b) and (c), if put into a single relation with scheme
{Course, Prerequisite, Day, Hour}
would look like
Course Prerequisite Day Hour EE200 EE005 Tu 10AM EE200 EE005 W 1PM EE200 EE005 Th 10AM EE200 CS100 Tu 10AM EE200 CS100 W 1PM EE200 CS100 Th 10AM
Notice that we take six tuples, with four components each, to do the work previously done by five tuples, with two or three components each.
F Conversely, do not separate attributes when they represent connected informa- tion.
For example, we cannot replace the Course-Day-Hour relation by two relations, one with scheme Course-Day and the other with scheme Course-Hour. For then, we could only tell that EE200 meets Tuesday, Wednesday, and Thursday, and that it has meetings at 10AM and 1PM, but we could not tell when it met on each of its three days.
8.2.1: Give appropriate structure declarations for the tuples of the relations of Fig. 8.2(a) through (d).
8.2.2*: What is an appropriate database scheme for
a) A telephone directory, including all the information normally found in a direc- tory, such as area codes.
Thus it is reasonable to take the StudentId attribute by itself as a key for the StudentId-Name-Address-Phone relation. However, in declaring StudentId a key, we have made a critical assumption, enunciated in item (2) preceding, that we never want to store two names, addresses, or phone numbers for one student. But we could just as well have decided otherwise, for example, that we want to store for each student both a home address and a campus address. If so, we would probably be better off designing the relation to have five attributes, with Address replaced by HomeAddress and LocalAddress, rather than have two tuples for each student, with all but the Address component the same. If we did use two tuples — differing in their Address components only — then StudentId would no longer be a key but {StudentId, Address} would be a key. F
might imagine that Grade was a key, since we see no two tuples with the same grade. However, this reasoning is fallacious. In this little example of six tuples, no two tuples hold the same grade; but in a typical Course-StudentId-Grade relation, which would have thousands or tens of thousands of tuples, surely there would be many grades appearing more than once. Most probably, the intent of the designers of the database is that Course and StudentId together form a key. That is, assuming students cannot take the same course twice, we could not have two different grades assigned to the same student in the same course; hence, there could not be two different tuples that agreed in both Course and StudentId. Since we would expect to find many tuples with the same Course component and many tuples with the same StudentId component, neither Course nor StudentId by itself would be a key. However, our assumption that students can get only one grade in any course is another design decision that could be questioned, depending on the policy of the school. Perhaps when course content changes sufficiently, a student may reregister for the course. If that were the case, we would not declare {Course, StudentId} to be a key for the Course-StudentId-Grade relation; rather, the set of all three attributes would be the only key. (Note that the set of all attributes for a relation can always be used as a key, since two identical tuples cannot appear in a relation.) In fact, it would be better to add a fourth attribute, Date, to indicate when a course was taken. Then we could handle the situation where a student took the same course twice and got the same grade each time. F
tribute by itself is a key, but the two attributes together form a key. F
tributes form the only reasonable key. Perhaps Course and Day alone could be declared a key, but then it would be impossible to store the fact that a course met twice in one day (e.g., for a lecture and a lab). F
Determining a key for a relation is an important aspect of database design; it is used when we select a primary index structure in Section 8.4. F You can’t tell the key by looking at an example value for the relation. That is, appearances can be deceptive, as in the matter of Grade for the Course- StudentId-Grade relation of Fig. 8.1, which we discuss in Example 8.4. F There is no one “right” key selection; what is a key depends on assumptions made about the types of data the relations will hold.
believe that Course is a key; that is, no course meets in two or more different rooms. If that were not the case, then we should have combined the Course-Room relation with the Course-Day-Hour relation, so we could tell which meetings of a course were held in which rooms. F
8.3.1: Suppose we want to store home and local addresses and also home and local phones for students in the StudentId-Name-Address-Phone relation. a) What would then be the most suitable key for the relation? b) This change causes redundancy; for example, the name of a student could be repeated four times as his or her two addresses and two phones are combined in all possible ways in different tuples. We suggested in Example 8.3 that one solution is to use separate attributes for the different addresses and different phones. What would the relation scheme be then? What would be the most suitable key for this relation? c) Another approach to handling redundancy, which we suggested in Section 8.2, is to split the relation into two relations, with different schemes, that together hold all the information of the original. Into what relations should we split StudentId-Name-Address-Phone, if we are going to allow multiple addresses and phones for one student? What would be the most suitable keys for these relations? Hint: A critical issue is whether addresses and phones are inde- pendent. That is, would you expect a phone number to ring in all addresses belonging to one student (in which case address and phone are independent), or are phones associated with single addresses? 8.3.2: The Department of Motor Vehicles keeps a database with the following kinds of information.
domain and the rest as the range. In cases where there is no key (except the set of all attributes, which is not a useful key), we may pick any set of attributes as the domain. For example, we might consider typical operations that we expect to perform on the relation and pick for the domain an attribute we expect will be specified frequently. We shall see some concrete examples shortly. Once we have selected a domain, we can select any of the four data structures just named to represent the relation, or indeed we could select another structure. However, it is common to choose a hash table based on domain values as the index, and we shall generally do so here. Primary index The chosen structure is said to be the primary index structure for the relation. The adjective “primary” refers to the fact that the location of tuples is determined by this structure. An index is a data structure that helps find tuples, given a value for one or more components of the desired tuples. In the next section, we shall discuss “secondary” indexes, which help answer queries but do not affect the location of the data.
typedef struct TUPLE *TUPLELIST; struct TUPLE { int StudentId; char Name[30]; char Address[50]; char Phone[8]; TUPLELIST next; }; typedef TUPLELIST HASHTABLE[1009];
Fig. 8.3. Types for a hash table as primary index structure.
which has key StudentId. This attribute will serve as our domain, and the other three attributes will form the range. We may thus see the relation as a function from StudentId to Name-Address-Phone triples. As with all functions, we select a hash function that takes a domain value as argument and produces a bucket number as result. In this case, the hash function takes student ID numbers, which are integers, as arguments. We shall choose the number of buckets, B, to be 1009,^1 and the hash function to be h(x) = x % 1009 This hash function maps ID’s to integers in the range 0 to 1008. An array of 1009 bucket headers takes us to a list of structures. The structures on the list for bucket i each represent a tuple whose StudentId component is an integer whose remainder, when divided by 1009, is i. For the StudentId-Name- Address-Phone relation, the declarations in Fig. 8.3 are suitable for the structures
(^1) 1009 is a convenient prime around 1000. We might choose about 1000 buckets if there were several thousand students in our database, so that the average number of tuples in a bucket would be small.
· · ·
· · ·
0 1
237
1008
12345 h 12345 C.Brown 12 Apple St. 555- to other tuples in bucket 237
BUCKET HEADERS
Fig. 8.4. Hash table representing StudentId-Name-Address-Phone relation.
in the linked lists of the buckets and for the bucket header array. Figure 8.4 suggests what the hash table would look like. F
Grade relation. We could use as a primary structure a hash table whose hash function took as argument both the course and the student (i.e., both attributes of the key for this relation). Such a hash function might take the characters of the course name, treat them as integers, add those integers to the student ID number, and divide by 1009, taking the remainder. That data structure would be useful if all we ever did was look up grades, given a course and a student ID — that is, we performed operations like lookup
(“CS101”, 12345, ∗), Course-StudentId-Grade
However, it is not useful for operations such as
In either case, we would not be able to compute a value for the hash function. For example, given only the course, we do not have a student ID to add to the sum of the characters converted to integers, and thus have no value to divide by 1009 to get the bucket number. However, suppose it is quite common to ask queries like, “Who is taking CS101?,” that is, lookup
(“CS101”, ∗, ∗), Course-StudentId-Grade
binary relations in Chapter 7. To review the ideas, let us focus on a hash table as the primary index structure. If the operation specifies a value for the domain, then we hash this value to find a bucket.
If the operation does not specify the domain value, we are not so fortunate. An insert operation always specifies the inserted tuple completely, but a delete or lookup might not. In those cases, we must search all the bucket lists for matching tuples and delete or list them, respectively.
8.4.1: The DMV database of Exercise 8.3.2 should be designed to handle the following sorts of queries, all of which may be assumed to occur with significant frequency.
Suggest appropriate primary index structures for the relations you designed in Ex- ercise 8.3.2, using a hash table in each case. State your assumptions about how many drivers and automobiles there are. Tell how many buckets you suggest, as well as what the domain attribute(s) are. How many of these types of queries can you answer efficiently, that is, in average time O(1) independent of the size of the relations?
8.4.2: The primary structure for the Course-Day-Hour relation of Fig. 8.2(c) might depend on the typical operations we intended to perform. Suggest an appropriate hash table, including both the attributes in the domain and the number of buckets if the typical queries are of each of the following forms. You may make reasonable assumptions about how many courses and different class periods there are. In each case, a specified value like “CS101” is intended to represent a “typical” value; in this case, we would mean that Course is specified to be some particular course.
a) lookup
(“CS101”, “M”, ∗), Course-Day-Hour
b) lookup
(∗, “M”, “9AM”), Course-Day-Hour
c) delete
(“CS101”, ∗, ∗), Course-Day-Hour
d) Half of type (a) and half of type (b). e) Half of type (a) and half of type (c). f) Half of type (b) and half of type (c).
Suppose we store the StudentId-Name-Address-Phone relation in a hash table, where the hash function is based on the key StudentId, as in Fig. 8.4. This primary index structure helps us answer queries in which the student ID number is specified. However, perhaps we wish to ask questions in terms of students’ names, rather than impersonal — and probably unknown — ID’s. For example, we might ask, “What is the phone number of the student named C. Brown?” Now, our primary index structure gives no help. We must go to each bucket and examine the lists of records until we find one whose Name field has value “C. Brown.” To answer such a query rapidly, we need an additional data structure that takes us from a name to the tuple or tuples with that name in the Name component of the tuple.^2 A data structure that helps us find tuples — given a value for a certain attribute or attributes — but is not used to position the tuples within the overall structure, is called a secondary index. What we want for our secondary index is a binary relation whose
(^2) Remember that Name is not a key for the StudentId-Name-Address-Phone relation, despite the fact that in the sample relation of Fig. 8.2(a), there are no tuples that have the same Name value. For example, if Linus goes to the same college as Lucy, we could find two tuples with Name equal to “L. Van Pelt,” but with different student ID’s.
0
1
67890 L. Van Pelt 22222 P. Patty •
12345 C. Brown •
L 1 L 2
L 3
BUCKET HEADERS
(a) Primary index structure
C. Brown L 3
L. Van Pelt L 1
P. Patty L 2
(b) Secondary index structure
Fig. 8.6. Example of primary and secondary index structures.
Now, if we want to answer a query like “What is P. Patty’s phone number,” we go to the root of the secondary index, look up the node with Name field “P. Patty,” and follow the pointer in the toTuple field (shown as L2 in Fig. 8.6). That gets us to the record for P. Patty, and from that record we can consult the Phone field and produce the answer to the query. F
It appeared that the attribute Name on which we built a secondary index in Example 8.10 was a key, because no name occurs more than once. As we know, however, it is possible that two students will have the same name, and so Name really is not a key. Nonkeyness, as we discussed in Section 7.9, does not affect the hash table data structure, although it may cause tuples to be distributed less evenly among buckets than we might expect. A binary search tree is another matter, because that data structure does not handle two elements, neither of which is “less than” the other, as would be the case if we had two pairs with the same name and different pointers. A simple fix to the structure of Fig. 8.5 is to use the field toTuple as the header of a linked list of
The existence of secondary indexes generally makes it easier to look up a tuple, given the values of one or more of its components. However,
F Each secondary index we create costs time when we insert or delete information in the relation.
F Thus it makes sense to build a secondary index on only those attributes that we are likely to need for looking up data.
For example, if we never intend to find a student given the phone number alone, then it is wasteful to create a secondary index on the Phone attribute of the
StudentId-Name-Address-Phone
relation.
pointers to tuples, one pointer for each tuple with a given value in the Name field. For instance, if there were several P. Patty’s, the bottom node in Fig. 8.6(b) would have, in place of L2, the header of a linked list. The elements of that list would be the pointers to the various tuples that had Name attribute equal to “P. Patty.”
When there are one or more secondary indexes for a relation, the insertion and deletion of tuples becomes more difficult. In addition to updating the primary index structure as outlined in Section 8.4, we may need to update each of the secondary index structures as well. The following methods can be used to update a secondary index structure for A when a tuple involving attribute A is inserted or deleted.
8.5.1: Show how to modify the binary search tree structure of Fig. 8.5 to allow for the possibility that there are several tuples in the StudentId-Name-Address-Phone relation that have the same student name. Write a C function that takes a name and lists all the tuples of the relation that have that name for the Name attribute.
8.5.2**: Suppose that we have decided to store the
StudentId-Name-Address-Phone