1. Home
  2. Explore
  3. Computer Science
  4. Foreign Keys and Referential Integrity

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Foreign Keys and Referential Integrity

Referential Integrity, an Academic Database Schema, and Relational Algebra

This lesson develops three connected ideas:

  1. Foreign keys and referential integrity, which keep relationships between tables valid.
  2. An example academic relational database schema, including its relations, attributes, and keys.
  3. The first two relational algebra operators: selection and projection.

The academic database will serve as a common example for understanding later database queries and SQL.

Foreign Keys and Referential Integrity

A foreign key is an attribute, or group of attributes, in one relation that is used to refer to a tuple in another relation. In practical terms, it creates a link between related pieces of information.

For example, a student record may contain a department number. That number identifies the department in which the student studies. The student relation does not need to repeat the department’s name, head, and phone number. Instead, it stores a value that points to the corresponding tuple in the department relation.

A foreign key therefore has two important characteristics:

  • It appears in one relation.
  • Its values refer to identifying values in another relation.

The relation containing the foreign key is the referencing relation. The relation whose tuples are being referred to is the referenced relation.

Referential integrity constraint

A referential integrity constraint requires every foreign-key reference to be valid. If a foreign-key value is not null, it must match an existing identifying value in the referenced relation.

Referential integrity prevents dangling references: a foreign key must refer to an existing tuple, rather than pointing to a record that does not exist.

For instance, if a student has department number 101010, then a department tuple with department identifier 101010 must exist. If no such department exists, the student record contains an invalid reference.

In general, a foreign-key value may be allowed to be null, or it must be a value that exists in the referenced relation. In this academic example, however, every student is required to have an advisor, so the student’s advisor attribute is intended to identify an actual faculty member.

Think About It

If a student record contains an advisor employee identifier that does not occur in the professor relation, what kind of database problem has occurred?

The Academic Database Schema

The example database represents academic information about an institute with:

  • Several departments
  • Students studying for different degrees
  • Professors working in departments
  • Courses offered by departments
  • Students enrolling in courses
  • Professors teaching courses
  • Prerequisite relationships between courses

A relation schema describes the structure of a relation. It lists the relation’s name and attributes. A relation instance is the actual collection of tuples stored according to that schema.

An attribute that is underlined in a relational schema represents a key. If several attributes are underlined together, they form a composite key.

A key is used to uniquely identify a tuple. In other words, no two tuples in the same relation can have the same key value.

The Student Relation

The student relation contains the following attributes:

  • Roll number
  • Name
  • Degree
  • Year
  • Sex
  • Department number
  • Advisor

The roll number is the key.

The reason roll number serves as a key is that each student’s roll number uniquely identifies one student tuple. Even if two students have the same name, their roll numbers distinguish them.

The other attributes describe the student:

  • Name identifies the student’s name.
  • Degree identifies the academic program in which the student is enrolled.
  • Year records the year of admission.
  • Sex records the student’s sex.
  • Department number identifies the student’s department.
  • Advisor stores the employee identifier of the faculty member who advises the student.

The advisor attribute refers to a faculty member’s employee identifier in the professor relation. If more information about the advisor is needed, the database must use that identifier to find the appropriate professor tuple.

Foreign keys in the student relation

Two attributes in the student relation act as foreign keys:

  • Department number refers to the department identifier in the department relation.
  • Advisor refers to the employee identifier in the professor relation.

The names do not have to be identical. For example, department number in the student relation can refer to department Id in the department relation. What matters is that the values correspond to the same kind of identifier.

The Department Relation

The department relation contains:

  • Department identifier
  • Name
  • HOD
  • Phone

The department identifier is used as the key. Although the department name might also be unique, the schema chooses a numerical department identifier because it provides a convenient and stable way to identify departments.

The attributes describe the department:

  • Department identifier uniquely identifies the department.
  • Name gives the department’s name.
  • HOD identifies the faculty member who serves as head of the department.
  • Phone gives the department office telephone number.

The HOD attribute is a foreign key. It stores the employee identifier of a professor and therefore refers to the employee identifier in the professor relation.

The HOD reference allows the database to connect a department to the complete professor tuple for its head.

The Professor Relation

The professor relation contains:

  • Employee identifier
  • Name
  • Sex
  • Start year
  • Department number
  • Phone

The employee identifier is the key because it uniquely identifies a professor.

The attributes describe the professor:

  • Employee identifier uniquely identifies the faculty member.
  • Name records the professor’s name.
  • Sex records the professor’s sex.
  • Start year records when the professor joined the institute or department.
  • Department number identifies the department in which the professor works.
  • Phone records the professor’s telephone number.

The department number is a foreign key referring to the department identifier in the department relation.

Thus, the database can connect each professor to the department in which that professor is employed.

The Course Relation

A course is a subject of study. The course relation contains:

  • Course identifier
  • Course name
  • Credits
  • Department number

The course identifier is the key.

The attributes describe the course:

  • Course identifier uniquely identifies the course.
  • Course name gives the course’s name.
  • Credits records the number of credits earned after successful completion.
  • Department number identifies the department offering the course.

The department number is a foreign key referring to the department identifier in the department relation.

This allows the database to answer questions such as which department offers a particular course.

The Enrollment Relation

Students enroll in courses, and the database must record more than simply which student takes which course. The same student can take many courses, and the same course can be offered repeatedly in different semesters and years.

The enrollment relation contains:

  • Roll number
  • Course identifier
  • Semester
  • Year
  • Grade

The key is the combination:

(roll number, course identifier, semester, year)(\text{roll number},\ \text{course identifier},\ \text{semester},\ \text{year})(roll number, course identifier, semester, year)

This is a composite key. All four attributes are needed to uniquely identify an enrollment.

Why all four attributes are necessary

A student can enroll in several courses, so roll number alone cannot identify an enrollment.

A course can be taken by many students, so course identifier alone cannot identify an enrollment.

A course may be offered repeatedly over time. Therefore, even the pair consisting of roll number and course identifier is insufficient. The semester and year identify the particular offering in which the student enrolled.

For example, an enrollment in a course during the odd semester of one year is different from an enrollment in the same course during the even semester of another year.

The semester attribute uses the value:

  • odd for the August semester
  • even for the January semester

The grade attribute records the student’s result. For the current semester, grade is assumed to be null because the semester has not yet ended. For previous semesters, the grade contains the appropriate completed-course value.

Foreign keys in the enrollment relation

The enrollment relation contains two important foreign keys:

  • Roll number refers to the roll number in the student relation.
  • Course identifier refers to the course identifier in the course relation.

Although these attributes are also parts of the composite key, they can independently serve as foreign keys.

Think About It

Why would two attributes—roll number and course identifier—not be enough to identify an enrollment when a course can be offered repeatedly?

The Teaching Relation

The teaching relation records which professor teaches which course offering. It contains:

  • Employee identifier
  • Course identifier
  • Semester
  • Year
  • Classroom

The entire combination of employee identifier, course identifier, semester, and year forms the key:

(employee identifier, course identifier, semester, year)(\text{employee identifier},\ \text{course identifier},\ \text{semester},\ \text{year})(employee identifier, course identifier, semester, year)

The classroom records where the course is taught.

Why the teaching key is composite

An employee identifier alone cannot be the key because a professor may teach several courses.

A course identifier alone cannot be the key because a course may be taught by several professors.

The course identifier and employee identifier together may still be insufficient because the same course can be taught in different semesters and years.

Including semester and year identifies the particular offering being described.

For example, a tuple could record that a professor with a particular employee identifier taught course CS3700 during the odd semester of a particular year in a particular classroom.

The key depends on the domain being modeled. Database designers choose keys based on what is necessary to distinguish one real-world event or object from another.

The employee identifier and course identifier in this relation are foreign keys:

  • Employee identifier refers to the professor relation.
  • Course identifier refers to the course relation.

The Prerequisite Relation

The prerequisite relation contains two attributes:

  • Prerequisite course
  • Course identifier

Both attributes are foreign keys referring to the course identifier in the course relation.

A tuple (C1,C2)(C_1,C_2)(C1​,C2​) means that course C1C_1C1​ is a prerequisite for course C2C_2C2​.

In plain language, the first course must be successfully completed before a student enrolls in the second course.

For example, if a tuple indicates that Data Structures is a prerequisite for Database Systems, then a student should complete Data Structures before taking Database Systems.

This relation is an example in which both foreign keys refer to the same relation. The two attributes have different roles:

  • prerequisite course identifies the earlier course.
  • course identifier identifies the later course.

Referential Links in the Academic Schema

The main foreign-key relationships can be summarized as follows:

Relation and attributeReferenced relation and attribute
Student.department numberDepartment.department identifier
Student.advisorProfessor.employee identifier
Department.HODProfessor.employee identifier
Professor.department numberDepartment.department identifier
Course.department numberDepartment.department identifier
Enrollment.roll numberStudent.roll number
Enrollment.course identifierCourse.course identifier
Teaching.employee identifierProfessor.employee identifier
Teaching.course identifierCourse.course identifier
Prerequisite.prerequisite courseCourse.course identifier
Prerequisite.course identifierCourse.course identifier

The schema can be viewed as a network of relations connected by foreign keys. Keys identify tuples within a relation, while foreign keys allow tuples in different relations to be connected.

Attribute names need not match

A foreign key and the key it references do not have to use the same attribute name. For example:

  • department number may refer to department identifier.
  • advisor may refer to employee identifier.
  • prerequisite course may refer to course identifier.

The meaning and domain of the values determine the connection. If identical names create ambiguity, dot notation can identify the intended relation.

For example:

  • Course.course identifier refers to the course identifier in the course relation.
  • Teaching.course identifier refers to the course identifier in the teaching relation.

This notation is important when several relations contain attributes with the same name.

The Relational Schema Diagram

A relational schema diagram presents the database structure in one place. It typically shows:

  • Relation names
  • Attribute names
  • Underlined keys
  • Arrows from foreign keys to the attributes they reference

Such a diagram helps the database user understand how relations connect. It is especially useful when writing relational algebra expressions or SQL queries because it shows which attributes can be used to link relations.

Keys identify tuples within relations; foreign keys connect tuples across relations.

Relational Algebra

After defining the relations and their connections, the next question is how to retrieve information from the database.

A query is a request for data. For example, a query might ask for:

  • The professor with a particular name
  • Professors who joined during a certain period
  • The names of students in a particular degree program

Relational algebra provides a formal way to express such requests.

Relational algebra is an algebra whose operands are relations. Its operators take relation instances as input and produce new relation instances as output.

This property is important: the result of one relational algebra operation can be used as the input to another. Such expressions can therefore be composed into larger expressions.

Relational algebra includes unary and binary operators:

  • A unary operator works on one relation.
  • A binary operator works on two relations.

The important operators include selection, projection, Cartesian product, union, intersection, difference, and join. This lesson focuses on selection and projection.

Relational algebra as a procedural language

Relational algebra is a procedural way of expressing a query. It describes the sequence of operations needed to produce the desired result.

For example, a query expression may say:

  1. Start with a relation.
  2. Keep only tuples satisfying a condition.
  3. Keep only certain attributes.
  4. Use the resulting relation in another operation.

An algebraic expression can be viewed as a tree. Intermediate results flow upward through the tree until the final result appears at the root.

This differs from SQL, which is largely declarative. SQL allows the database user to describe what information is wanted, while the database system determines how to obtain it. Internally, SQL queries are translated into relational algebraic expressions.

That translation allows the database system to optimize the query. Equivalent relational algebra expressions may have different execution costs, so the system can choose a more efficient form.

The Selection Operator

The selection operator chooses tuples that satisfy a specified condition. It is a unary operator because it operates on one relation.

The notation is:

σθ(R)\sigma_{\theta}(R)σθ​(R)

Here:

  • σ\sigmaσ is the selection operator.
  • θ\thetaθ is the selection condition.
  • RRR is the input relation.

The result contains only those tuples in RRR that satisfy θ\thetaθ.

Selection filters rows, but it does not remove attributes. Therefore, the result has the same schema as the input relation:

  • The same attributes
  • The same attribute order
  • The same attribute domains

Only the set of tuples changes.

Example: Selecting a professor by name

To obtain information about professors whose name is Giridhar, the expression is:

σname=’Giridhar’(Professor)\sigma_{\text{name}=\text{'Giridhar'}}(\text{Professor})σname=’Giridhar’​(Professor)

The result contains every professor tuple whose name equals Giridhar. If several professors have that name, all matching tuples appear.

The result still contains every Professor attribute, such as employee identifier, sex, start year, department number, and phone. Selection has filtered tuples, not columns.

Example: Selecting professors by start year

To obtain professors who joined between 198019801980 and 198519851985, inclusive, the condition can be written as:

1980≤start year∧start year≤19851980 \leq \text{start year} \land \text{start year} \leq 19851980≤start year∧start year≤1985

The complete expression is:

σ1980≤start year∧start year≤1985(Professor)\sigma_{1980 \leq \text{start year} \land \text{start year} \leq 1985}(\text{Professor})σ1980≤start year∧start year≤1985​(Professor)

The result contains all professor tuples whose start year falls within the specified inclusive range.

Selection conditions

A selection condition may be a basic condition or a composite condition.

A basic condition compares:

  • One attribute with another attribute
  • An attribute with a constant

Examples include:

Ai<AjA_i < A_jAi​<Aj​

and

Ai=cA_i = cAi​=c

The attributes must belong to the relation on which selection is being performed. Any constant used in a comparison must have an appropriate type for the attribute’s domain.

For example, a string attribute should be compared with a string constant, while a numerical attribute should be compared with a numerical constant.

The comparison operators are:

<, ≤, >, ≥, =, ≠<,\ \leq,\ >,\ \geq,\ =,\ \neq<, ≤, >, ≥, =, =

Each basic comparison produces a Boolean result: true or false.

Composite conditions

Basic conditions can be combined using logical operators:

  • AND
  • OR
  • NOT

For example:

(degree=’M.S.’)∧(year=2020)(\text{degree}=\text{'M.S.'}) \land (\text{year}=2020)(degree=’M.S.’)∧(year=2020)

is a composite condition requiring both conditions to be true.

A selection condition can therefore be as simple as one comparison or as complex as a combination of several comparisons.

Selection is commutative

Selection operations can be applied in either order without changing the final set of tuples.

For example:

σc1(σc2(R))=σc2(σc1(R))\sigma_{c_1}\left(\sigma_{c_2}(R)\right) = \sigma_{c_2}\left(\sigma_{c_1}(R)\right)σc1​​(σc2​​(R))=σc2​​(σc1​​(R))

Both expressions return the tuples in RRR that satisfy both c1c_1c1​ and c2c_2c2​.

The reason is that both expressions ultimately retain exactly the tuples satisfying both conditions. The first expression applies c2c_2c2​ and then c1c_1c1​; the second applies c1c_1c1​ and then c2c_2c2​.

This property is useful for query rewriting and optimization. A database system can rearrange equivalent operations when doing so leads to more efficient execution.

The Projection Operator

While selection filters tuples, projection filters attributes. It keeps the requested columns and discards the remaining columns.

The notation is:

πL(R)\pi_{L}(R)πL​(R)

Here:

  • π\piπ is the projection operator.
  • LLL is the list of desired attributes.
  • RRR is the input relation.

Every attribute in LLL must belong to the schema of RRR. The result has a schema consisting only of the attributes in LLL, in the order specified by the projection list.

Example of projection

To obtain only roll numbers and names from the student relation, the expression is:

πroll number, name(Student)\pi_{\text{roll number},\ \text{name}}(\text{Student})πroll number, name​(Student)

The result contains only those two attributes. Information such as degree, year, sex, department number, and advisor is discarded from the result.

Projection can therefore be understood as choosing a vertical slice of a relation, whereas selection chooses a horizontal slice.

Projection eliminates duplicates

Relations are treated as sets of tuples, so duplicate tuples are not retained.

Suppose two different students named Mahesh are enrolled in the same degree program. If a query projects only the name attribute, both original tuples produce the same value, Mahesh. The projected result contains only one Mahesh tuple because duplicate tuples are removed.

This means projection can reduce the number of tuples even though its main purpose is to remove attributes.

Projection and keys

If the projection list contains a key of the original relation, the number of tuples remains the same.

For example:

πroll number, name(Student)\pi_{\text{roll number},\ \text{name}}(\text{Student})πroll number, name​(Student)

includes roll number, which is the key of Student. Since each roll number is unique, no two projected tuples can become identical. Therefore, the result has the same number of tuples as the original Student relation.

If the projection list does not contain a key, the number of tuples may decrease because multiple original tuples can collapse into one identical projected tuple.

Naming an intermediate result

A relational algebra expression produces a relation. If that result will be used later, it can be assigned a relation name.

For example:

R1=πL(R2)R_1 = \pi_L(R_2)R1​=πL​(R2​)

This means that R1R_1R1​ is the new relation produced by projecting the attributes in LLL from R2R_2R2​.

The schema of R1R_1R1​ is exactly LLL, the projection list.

Combining Selection and Projection

Selection and projection can be combined to express more focused requests.

Suppose the database needs the names of students enrolled in the M.S. degree. First, selection keeps only M.S. students:

σdegree=’M.S.’(Student)\sigma_{\text{degree}=\text{'M.S.'}}(\text{Student})σdegree=’M.S.’​(Student)

Then projection keeps only their names:

πname(σdegree=’M.S.’(Student))\pi_{\text{name}}\left( \sigma_{\text{degree}=\text{'M.S.'}}(\text{Student}) \right)πname​(σdegree=’M.S.’​(Student))

The first operation filters rows. The second operation removes unwanted columns.

If roll number is also needed, the expression becomes:

πroll number, name(σdegree=’M.S.’(Student))\pi_{\text{roll number},\ \text{name}}\left( \sigma_{\text{degree}=\text{'M.S.'}}(\text{Student}) \right)πroll number, name​(σdegree=’M.S.’​(Student))

Because roll number is a key, the output retains one tuple for every qualifying student.

Think About It

Which operation is appropriate when the database needs fewer students, and which operation is appropriate when it needs fewer attributes?

Comprehensive Review

A foreign key is an attribute or group of attributes used to refer to tuples in another relation. Referential integrity requires those references to be valid: a non-null foreign-key value must match an existing value in the referenced relation.

In the academic database:

  • Student identifies each student using roll number.
  • Department identifies each department using department identifier.
  • Professor identifies each professor using employee identifier.
  • Course identifies each course using course identifier.
  • Enrollment uses a composite key because the student, course, semester, and year together identify one enrollment event.
  • Teaching uses a composite key because the professor, course, semester, and year together identify one teaching assignment.
  • Prerequisite records directed relationships between courses, with both attributes referring to Course.

Underlined attributes represent keys, while arrows in a schema diagram represent foreign-key references. Attribute names in related relations do not need to match, and dot notation disambiguates repeated names.

Relational algebra provides a mathematical language for expressing database queries. Its operators take relations as inputs and produce new relations as outputs. It is procedural because an expression describes the operations used to obtain the result, and its expressions can be represented as operation trees.

The selection operator is written as:

σθ(R)\sigma_{\theta}(R)σθ​(R)

It keeps tuples satisfying condition θ\thetaθ and preserves the complete schema of RRR. Selection conditions use comparisons and can be combined with AND, OR, and NOT. Selection is commutative, so applying two selections in either order gives the same result.

The projection operator is written as:

πL(R)\pi_L(R)πL​(R)

It keeps only the attributes in list LLL. Projection changes the schema and removes duplicate result tuples because relations are sets. If the projection list contains a key, the number of tuples remains unchanged; otherwise, the number may become smaller. Together, selection and projection form the foundation for expressing many database retrieval requests.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent