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

Relational Integrity, Example Database Schema, and Relational Algebra

Referential Integrity and Foreign Keys

A foreign key is an attribute or group of attributes in one relation whose values are used to refer to tuples in another relation.

For example, a student relation may contain a department number attribute. That value identifies the department in which the student is enrolled and refers to the corresponding tuple in the department relation.

Referential integrity requires every foreign-key reference to point to an existing tuple in the referenced relation. This prevents dangling references.

A foreign-key value generally must satisfy one of the following conditions:

  • It is null, when the relationship is optional.

  • It matches an existing value of the referenced key in another relation.

If a foreign key is not null, its value must exist in the referenced relation. For example, if a student has department number 333, a department with department ID 333 must exist.


Example Academic Database

The example database models the academic activities of an institute containing:

  • Multiple departments

  • Students enrolled in degree programs

  • Professors employed by departments

  • Courses offered by departments

  • Student enrollments and grades

  • Professors teaching courses

  • Course prerequisite relationships

An attribute or group of attributes written with an underline represents a key. A key uniquely identifies each tuple in a relation.

If more than one distinct group of attributes can uniquely identify tuples, each group may be shown as a candidate key.


Student Relation

The student relation stores information about students.

Student attributes

  • Roll number — uniquely identifies a student and serves as the key.

  • Name — the student’s name.

  • Degree — the academic program in which the student is enrolled.

  • Year — the year in which the student was admitted.

  • Sex — the student’s sex.

  • Department number — identifies the department in which the student studies.

  • Advisor — identifies the faculty member assigned as the student’s advisor.

The relation can be represented conceptually as:

Student(roll number‾,name,degree,year,sex,department number,advisor)\text{Student}(\underline{\text{roll number}}, \text{name}, \text{degree}, \text{year}, \text{sex}, \text{department number}, \text{advisor})Student(roll number​,name,degree,year,sex,department number,advisor)

Keys and references

  • Roll number is the primary key because no two students should have the same roll number.

  • Department number is a foreign key referencing the department’s department ID.

  • Advisor is a foreign key referencing a professor’s employee ID.

Every student is assumed to have an advisor. Therefore, the advisor attribute is expected to contain the employee ID of an appropriate faculty member.

To obtain additional information about a student’s advisor, such as the advisor’s name or department, the professor relation must be consulted using the advisor’s employee ID.


Department Relation

The department relation represents academic departments.

Department attributes

  • Department ID — uniquely identifies a department and serves as the key.

  • Name — the department’s name.

  • HOD — the employee ID of the faculty member who heads the department.

  • Phone — the department office telephone number.

The relation can be represented as:

Department(department ID‾,name,HOD,phone)\text{Department}(\underline{\text{department ID}}, \text{name}, \text{HOD}, \text{phone})Department(department ID​,name,HOD,phone)

Keys and references

  • Department ID is the chosen key.

  • Department name might also be unique and could serve as a key, but a numeric department ID is used instead for convenient identification.

  • HOD is a foreign key referencing the employee ID of a professor.

The HOD attribute allows a department tuple to identify the professor academically responsible for running that department.


Professor Relation

The professor relation stores information about faculty members. Professors are institute employees, so each professor has an employee ID.

Professor attributes

  • Employee ID — uniquely identifies a professor and serves as the key.

  • Name — the professor’s name.

  • Sex — the professor’s sex.

  • Start year — the year in which the professor joined the institute or department.

  • Department number — identifies the department employing the professor.

  • Phone — the professor’s telephone number.

The relation can be represented as:

Professor(employee ID‾,name,sex,start year,department number,phone)\text{Professor}(\underline{\text{employee ID}}, \text{name}, \text{sex}, \text{start year}, \text{department number}, \text{phone})Professor(employee ID​,name,sex,start year,department number,phone)

Keys and references

  • Employee ID is the primary key.

  • Department number is a foreign key referencing the department ID.

  • Professors may teach multiple courses, advise multiple students, or serve as a department head.


Course Relation

A course is a subject of study offered by a department.

Course attributes

  • Course ID — uniquely identifies a course and serves as the key.

  • Course name — the name of the course.

  • Credits — the number of credits earned after successfully completing the course.

  • Department number — identifies the department offering the course.

The relation can be represented as:

Course(course ID‾,course name,credits,department number)\text{Course}(\underline{\text{course ID}}, \text{course name}, \text{credits}, \text{department number})Course(course ID​,course name,credits,department number)

Keys and references

  • Course ID is the primary key.

  • Department number is a foreign key referencing the department ID.

A course may be offered repeatedly across different semesters and years, so the course relation identifies the course itself, while other relations record specific offerings of that course.


Enrollment Relation

The enrollment relation records which students enroll in which course offerings and the grades they receive.

Enrollment attributes

  • Roll number — identifies the enrolled student.

  • Course ID — identifies the course.

  • Semester — identifies the semester in which the course is offered.

  • Year — identifies the academic year of the course offering.

  • Grade — the grade earned by the student.

The relation can be represented as:

Enrollment(roll number,course ID,semester,year‾,grade)\text{Enrollment}(\underline{\text{roll number}, \text{course ID}, \text{semester}, \text{year}}, \text{grade})Enrollment(roll number,course ID,semester,year​,grade)

Composite key

The key consists of four attributes:

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

All four attributes are necessary because:

  • A student can enroll in several courses.

  • A course can be offered in multiple semesters.

  • The same course can be offered in multiple years.

  • A student may potentially take the same course in different offerings.

Thus, course ID alone cannot identify an enrollment, and roll number alone cannot identify an enrollment.

Semester values and grades

The semester attribute is assumed to have one of two values:

  • Odd — the August semester.

  • Even — the January semester.

The grade for a course currently in progress is represented by a null value. Once the semester ends, the null value is replaced by the student’s actual grade.

Foreign keys

  • Roll number references the student relation.

  • Course ID references the course relation.

These foreign keys ensure that an enrollment cannot refer to a nonexistent student or course.


Teaching Relation

The teaching relation records which professor teaches a particular course offering.

Teaching attributes

  • Employee ID — identifies the professor.

  • Course ID — identifies the course.

  • Semester — identifies the semester of the course offering.

  • Year — identifies the year of the course offering.

  • Classroom — identifies the classroom in which the course is taught.

The relation can be represented as:

Teaching(employee ID,course ID,semester,year‾,classroom)\text{Teaching}(\underline{\text{employee ID}, \text{course ID}, \text{semester}, \text{year}}, \text{classroom})Teaching(employee ID,course ID,semester,year​,classroom)

Composite key

The key is:

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

All four attributes are needed to identify a particular teaching assignment. This is because:

  • A professor may teach several courses.

  • A course may be taught by several professors.

  • A course is offered repeatedly in different semesters.

  • A course offering must be identified by both its semester and year.

For example, a tuple might indicate that a particular professor teaches a particular course during the odd semester of a specific year in a particular classroom.

Foreign keys

  • Employee ID references the professor relation.

  • Course ID references the course relation.


Prerequisite Relation

The prerequisite relation records prerequisite relationships between courses.

Prerequisite attributes

  • Prerequisite course — the course that must be completed first.

  • Course ID — the course that requires the prerequisite.

The relation can be represented as:

Prerequisite(prerequisite course,course ID‾)\text{Prerequisite}(\underline{\text{prerequisite course}, \text{course ID}})Prerequisite(prerequisite course,course ID​)

The pair forms a key because a particular prerequisite relationship should not be recorded more than once.

If the tuple (C1,C2)(C_1, C_2)(C1​,C2​) appears in the relation, it means:

Course C1C_1C1​ must be successfully completed before a student may enroll in course C2C_2C2​.

For example, a tuple could state that Data Structures is a prerequisite for Database Systems.

Foreign keys

Both attributes reference the course relation:

  • Prerequisite course references Course.course ID.

  • Course ID references Course.course ID.

This is an example of two foreign keys in one relation referencing the same relation. The two attributes have different roles even though they refer to the same type of object.


Foreign-Key Relationships in the Schema

The principal foreign-key relationships are:

  • Student.department number references Department.department ID.

  • Student.advisor references Professor.employee ID.

  • Department.HOD references Professor.employee ID.

  • Professor.department number references Department.department ID.

  • Course.department number references Department.department ID.

  • Enrollment.roll number references Student.roll number.

  • Enrollment.course ID references Course.course ID.

  • Teaching.employee ID references Professor.employee ID.

  • Teaching.course ID references Course.course ID.

  • Prerequisite.prerequisite course references Course.course ID.

  • Prerequisite.course ID references Course.course ID.

A foreign key can be part of a relation’s primary or composite key while also independently functioning as a foreign key. For example, Enrollment.roll number is part of the enrollment key and also references the student relation.

Different attribute names may refer to the same concept

A foreign-key attribute does not have to have the same name as the referenced key. For example:

  • Student.department number

  • Professor.department number

  • Course.department number

may all reference Department.department ID.

The names differ, but the values represent the same kind of department identifier.

Dot notation for disambiguation

The same attribute name may occur in multiple relations. Dot notation identifies the relation from which an attribute is being taken.

Examples:

  • Course.course ID refers to the course ID in the course relation.

  • Enrollment.course ID refers to the course ID in the enrollment relation.

  • Teaching.course ID refers to the course ID in the teaching relation.

This notation is especially important when relations are combined in queries.


Relational Schema Diagrams

A relational schema diagram displays:

  • Relation names

  • Attribute names

  • Underlined keys

  • Arrows from foreign keys to the keys they reference

The diagram provides a visual summary of the database structure and the relationships among relations. It is useful when writing queries because it shows how information can be connected across relations.

For example:

  • Student information can be connected to department information through department number.

  • Student information can be connected to advisor information through advisor and employee ID.

  • Enrollment information can be connected to course information through course ID.

  • Teaching information can be connected to professor information through employee ID.


Relational Algebra

Definition and Purpose

Relational algebra is a formal system of operators used to retrieve and manipulate data in relational databases.

Each relational algebra operator:

  1. Takes one or more relation instances as input.

  2. Performs an operation on those relations.

  3. Returns a new relation instance as output.

Because the output is also a relation, operators can be combined to form complex expressions.

Relational algebra is an algebra of relations: it accepts relations and produces relations.

A database retrieval request is called a query. Relational algebra provides a procedural method for expressing queries.

A procedural query describes the operations to perform, such as:

  1. Select certain tuples from one relation.

  2. Select or combine tuples from another relation.

  3. Join or otherwise combine intermediate results.

  4. Produce the final relation.

A relational algebra expression can be viewed as an expression tree. Intermediate results flow upward through the tree, and the final result appears at the root.


Relational Algebra and Query Processing

Relational algebra forms a central part of a relational database system’s query engine.

The query engine:

  • Uses relational algebra operators.

  • Translates logical query requests into algebraic expressions.

  • Implements those operators efficiently.

  • May rewrite algebraic expressions to improve performance.

The implementation details of the operators are separate from their conceptual meaning. At the conceptual level, each operator can be treated as a mathematical operation on relations.

SQL is largely a declarative query language. In SQL, the user specifies what information is needed rather than giving a complete step-by-step procedure for obtaining it.

A database system can internally translate an SQL query into a relational algebra expression. This translation allows the system to optimize the query by finding an efficient way to execute the equivalent algebraic operations.


Main Relational Algebra Operators

Common relational algebra operators include:

  • Selection

  • Projection

  • Cartesian product

  • Union

  • Intersection

  • Set difference

  • Join

Selection and projection are unary operators because they operate on one relation.

Cartesian product, union, intersection, difference, and join are generally binary operators because they combine two relations.

Not every operator is necessarily fundamental. Some operators can be expressed using combinations of others. The minimum set of operators required to express all relational queries can be studied separately.


Selection Operator

Meaning

The selection operator chooses tuples from a relation that satisfy a specified condition.

It is a unary operator because it operates on one input relation.

The notation is:

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

where:

  • σ\sigmaσ is the selection operator.

  • θ\thetaθ is the selection condition.

  • RRR is the input relation.

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

Effect on the relation schema

Selection filters rows but does not remove columns.

Therefore:

  • The output has the same attributes as the input relation.

  • The output has the same attribute order and domains.

  • The output may contain fewer tuples than the input.

  • The output can contain all input tuples, some input tuples, or no input tuples.

Formally, if RRR has a particular schema, then σθ(R)\sigma_{\theta}(R)σθ​(R) has that same schema.


Selection Conditions

A selection condition may be either:

  • A basic condition

  • A composite condition

Basic conditions

A basic condition compares:

  1. One attribute with another attribute.

  2. One attribute with a constant.

Examples include:

Ai=AjA_i = A_jAi​=Aj​
Ai>AjA_i > A_jAi​>Aj​
Ai=cA_i = cAi​=c

where:

  • AiA_iAi​ and AjA_jAj​ are attributes of the input relation.

  • ccc is a constant of an appropriate data type.

The constant must be compatible with the attribute’s domain. For example, a string attribute should be compared with a string, and an integer attribute should be compared with an integer.

Comparison operators

The standard comparison operators are:

  • Less than: <<<

  • Less than or equal to: ≤\leq≤

  • Greater than: >>>

  • Greater than or equal to: ≥\geq≥

  • Equal to: ===

  • Not equal to: ≠\neq=

These comparisons assume that the relevant domains support the corresponding ordering or equality operation.

Composite conditions

Basic conditions can be combined using Boolean operators:

  • AND

  • OR

  • NOT

Examples include:

(Ai>10)∧(Aj=’CS’)(A_i > 10) \land (A_j = \text{'CS'})(Ai​>10)∧(Aj​=’CS’)
(Ai=1)∨(Ai=2)(A_i = 1) \lor (A_i = 2)(Ai​=1)∨(Ai​=2)
¬(Ai=Aj)\neg(A_i = A_j)¬(Ai​=Aj​)

A composite condition may contain several comparisons joined together with these logical operators.


Examples of Selection

Professors named Giridhar

To obtain all professors whose name is exactly “Giridhar”:

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

The result:

  • Has the same schema as Professor.

  • Contains every professor tuple whose name is Giridhar.

  • May contain more than one tuple if several professors have that name.

Professors who joined between 1980 and 1985

To obtain all professors whose start year is between 1980 and 1985, inclusive:

σ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 satisfies both bounds.


Composition and Commutativity of Selection

Relational algebra operators can be nested.

For example:

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

means:

  1. Select from RRR the tuples satisfying c2c_2c2​.

  2. From that intermediate result, select the tuples satisfying c1c_1c1​.

Because both operations ultimately retain tuples satisfying both conditions, the order of two selections does not affect the final result:

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

This property is called commutativity of selection.

The equivalence is useful for query optimization. A database system can reorder selection operations when doing so makes execution more efficient, provided the result remains logically equivalent.


Projection Operator

Meaning

The projection operator chooses specific attributes from a relation and discards the remaining attributes.

It is also a unary operator.

The notation is:

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

where:

  • π\piπ is the projection operator.

  • LLL is a list of desired attributes.

  • RRR is the input relation.

If the desired attributes are A1,A2,…,AkA_1, A_2, \ldots, A_kA1​,A2​,…,Ak​, the expression can be written as:

πA1,A2,…,Ak(R)\pi_{A_1,A_2,\ldots,A_k}(R)πA1​,A2​,…,Ak​​(R)

Selection chooses rows, whereas projection chooses columns.

Selection filters tuples; projection removes unwanted attributes.


Effect on the Relation Schema

Projection produces a relation whose schema consists only of the requested attributes.

If:

R1=πL(R2)R_1 = \pi_{L}(R_2)R1​=πL​(R2​)

then:

  • The schema of R1R_1R1​ is exactly LLL.

  • Attributes not included in LLL are discarded.

  • The order of attributes follows the projection list.

  • The output contains only the selected attribute values.

The projected attributes do not need to be consecutive in the original relation. Any desired subset of attributes may be specified.


Duplicate Elimination

Relations are sets of tuples. Sets do not contain duplicate elements.

Therefore, projection automatically eliminates duplicate projected tuples.

Suppose two distinct tuples in the input relation have the same values for all projected attributes. After projection, those values appear only once in the result.

For example, if two students named Mahesh are projected only on name, the result contains one tuple containing “Mahesh,” not two identical tuples.

This means projection may reduce the number of tuples even though it is conceptually selecting columns rather than filtering rows.


Example: Projecting Student Names

Suppose the database contains several students enrolled in the M.S. degree. First, selection can identify those students:

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

To obtain only their names, projection can be applied:

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

If two M.S. students have the same name, the projected result contains that name only once because duplicate tuples are removed.


Example: Projecting Roll Numbers and Names

To obtain the roll number and name of every student:

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

Because roll number is a key, no two students can have the same roll number. Consequently, no two projected tuples can be identical in their combination of roll number and name.

The result therefore has exactly the same number of tuples as the original student relation, although it contains fewer attributes.


Projection and Keys

The number of tuples in a projection depends on whether the projection list contains a key.

Projection includes a key

If the projection list includes a key of the original relation:

  • Every original tuple remains distinguishable.

  • No projected tuples can become duplicates.

  • The output has exactly as many tuples as the input.

For example:

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

contains the student key, so the number of output tuples equals the number of student tuples.

Projection does not include a key

If the projection list does not include a key:

  • Different input tuples may produce the same projected tuple.

  • Duplicate projected tuples are removed.

  • The number of output tuples may be smaller than the input.

For example:

πname(Student)\pi_{\text{name}}(\text{Student})πname​(Student)

does not include the student key. If multiple students share a name, those tuples collapse into one output tuple.

Thus, if:

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

then:

  • ∣R1∣=∣R2∣|R_1| = |R_2|∣R1​∣=∣R2​∣ when LLL contains a key of R2R_2R2​.

  • ∣R1∣≤∣R2∣|R_1| \leq |R_2|∣R1​∣≤∣R2​∣ when LLL does not contain a key.

  • The inequality may be strict because of duplicate elimination.


Selection and Projection Compared

Selection

  • Uses the symbol σ\sigmaσ.

  • Chooses tuples based on a condition.

  • Retains all attributes.

  • May reduce the number of tuples.

  • Does not change the relation schema.

Projection

  • Uses the symbol π\piπ.

  • Chooses specified attributes.

  • Discards other attributes.

  • May reduce the number of tuples through duplicate elimination.

  • Changes the relation schema.

A query often combines both operators. For example, a query may first select students satisfying a condition and then project only the attributes needed in the final answer:

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

The selection determines which students qualify, while the projection determines which details about those students are returned.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent