Database Management — Week 3
Relational Model and Constraints
Part 1 — Overview of the Relational Model
Evolution from ER Model to Relational Model
The transition from Entity-Relationship modeling to the relational model represents a crucial step in database development where we move from conceptual design to practical implementation. While ER modeling provides us with a visual, intuitive understanding of our data requirements, the relational model gives us the mathematical foundation and practical framework for actually storing and retrieving data. Think of this evolution as similar to moving from architectural blueprints to actual construction, the ER model shows us what we want to build, and the relational model provides the engineering principles for how to build it.
The relational model was first proposed by Edgar F. Codd in 1970 while working at IBM, and it revolutionized data management by introducing a simple yet powerful way to organize data using mathematical set theory. Unlike earlier database models that relied on complex pointer structures or hierarchical arrangements, the relational model organizes data into simple two-dimensional tables called relations. This elegant approach made databases more intuitive to understand and easier to use, which ultimately led to the widespread adoption of relational database management systems that dominate the industry today.
Fundamental Concepts: Relations, Tuples, and Attributes
In the relational model, we use specific terminology that has precise mathematical meanings.
A relation is essentially a table with columns and rows, but with specific properties that distinguish it from a simple spreadsheet. Each attribute corresponds to a column in the table, representing a particular type of information we want to store. For example, in a Student relation, we might have attributes like StudentID, Name, and Major. The set of all possible values that an attribute can take is called its domain, which defines both the data type and any constraints on the values. For instance, the domain for a Grade attribute might be limited to the set {A, B, C, D, F} or numerical values between 0 and 100.
Each row in a relation is called a tuple, which represents a single, complete record of information. Importantly, in proper relational theory, tuples are unordered, there’s no inherent sequence to the rows, and we cannot rely on their physical position in the table. Similarly, attributes are also unordered within a relation. This mathematical foundation is what gives relational databases their flexibility and power, allowing us to manipulate data using logical operations rather than physical navigation.
Characteristics of Relations
Several key characteristics distinguish proper relations from simple tables or spreadsheets.
First, relations contain atomic values, meaning each cell in the table holds a single, indivisible value, we cannot have arrays, lists, or other composite structures within a single attribute. This atomicity ensures that data can be easily searched, sorted, and manipulated using simple operations. Second, every tuple in a relation must be unique; no two rows can be identical in all their attribute values. This uniqueness property is essential for being able to reliably identify and reference specific records.
Another important characteristic is that the order of tuples is insignificant, we can rearrange the rows in any order without changing the meaning of the data. Similarly, the order of attributes is also insignificant, though in practical implementations we typically see columns in a fixed order for human readability. Additionally, each relation has a primary key, one or more attributes whose values uniquely identify each tuple. These characteristics collectively ensure that relations behave predictably and can be manipulated using the mathematical operations of relational algebra.
Schema vs. Instance: The Blueprint and the Building
A crucial distinction in the relational model is between schema and instance. The relational schema is the logical structure or blueprint of the database, it defines the relation names, their attributes, domains, and constraints. For example, a Student schema might be defined as Student(StudentID, Name, Major, GPA), specifying what information we will store but not the actual data. The schema remains relatively stable over time, changing only when we modify the database structure.
In contrast, a relational instance represents the actual data stored in the database at a particular moment in time. It’s the current collection of tuples that populate the relations defined by the schema. While the schema defines that we will store student information, the instance contains the actual records for students like “Alice Smith, ID 12345, Computer Science, 3.8” and “Bob Johnson, ID 67890, Mathematics, 3.5”. This distinction is important because it separates the stable structure of our database from the constantly changing data it contains, allowing us to design robust systems that can handle evolving data while maintaining structural integrity.
Part 2 — Relational Keys
Primary Keys: The Unique Identifiers
Primary keys serve as the fundamental mechanism for uniquely identifying each tuple in a relation. A primary key is an attribute or combination of attributes whose values uniquely identify each record in the table. For example, in a Student table, StudentID would typically serve as the primary key because each student receives a unique identifier. The primary key constraint ensures that no two records can have the same key value, and that every record must have a value for the primary key attribute (it cannot be null).
Choosing an appropriate primary key is one of the most important decisions in database design. A good primary key should be unique, stable (not changing over time), and minimal (containing no unnecessary attributes). Sometimes we use natural keys that have inherent meaning in the business domain, like Social Security Number for persons or ISBN for books. Other times, we use surrogate keys, artificial identifiers like auto-incrementing numbers that have no business meaning but serve the technical purpose of unique identification. Surrogate keys are often preferred because they’re guaranteed to be unique and stable, whereas natural keys sometimes change or prove to be non-unique in practice.
Candidate Keys: Alternative Unique Identifiers
Candidate keys are all the possible attributes or combinations of attributes that could serve as primary keys for a relation. Each candidate key must satisfy the same requirements as a primary key: uniqueness and non-null values for all tuples. For example, in a Student relation, both StudentID and Email might be candidate keys if each student has a unique email address. From the set of candidate keys, we choose one to be the primary key, and the others become alternate keys that we can still use for unique identification when needed.
The concept of candidate keys is important because it helps us identify all the possible ways we might uniquely access records in our table. When we have multiple candidate keys, we choose the one that’s most stable, simplest, and most frequently used for lookups as our primary key. The remaining candidate keys can be enforced using UNIQUE constraints to ensure their uniqueness while not granting them the special status of primary key.
Composite Keys: Multi-Attribute Identifiers
When no single attribute can uniquely identify tuples in a relation, we use a composite key, a primary key made up of two or more attributes. For example, in a CourseRegistration table that records which students take which courses, we might use a composite key consisting of StudentID and CourseID, since the combination of these two attributes uniquely identifies each registration. Composite keys are common in intersection tables that resolve many-to-many relationships.
When working with composite keys, all the attributes in the key collectively must be unique, and none of them can contain null values. The order of attributes in a composite key can be important for performance, as we typically want to put the most selective attribute first. Composite keys also become foreign keys when referenced by other tables, which requires that the referencing table include all the attributes of the composite key, maintaining the same order and data types.
Foreign Keys: Establishing Relationships
Foreign keys are the mechanism that enables relationships between tables in the relational model. A foreign key is an attribute or set of attributes in one relation that references the primary key of another relation. For example, in an Orders table, CustomerID would be a foreign key that references the CustomerID primary key in the Customers table. This creates a logical link between orders and customers, allowing us to relate each order to the customer who placed it.
Foreign keys enforce what we call referential integrity, the idea that these cross-references between tables must always be valid. This means that any value appearing in a foreign key column must already exist as a primary key value in the referenced table, or be null (if the foreign key allows nulls). The database management system automatically maintains this integrity by rejecting any operations that would violate it, such as inserting an order for a non-existent customer or deleting a customer who still has outstanding orders.
Part 3 — Constraints and Integrity Rules
Entity Integrity: Ensuring Unique Identifiability
Entity integrity is a fundamental constraint that ensures every relation has a primary key and that the primary key values are unique and not null. This constraint guarantees that each tuple in a relation can be uniquely identified and referenced. Without entity integrity, we would have no reliable way to distinguish between different records or to establish relationships between tables.
The entity integrity rule has two components: first, no two tuples in a relation can have the same values for all attributes of the primary key; second, no attribute that is part of the primary key can contain a null value. This ensures that every record is complete in terms of its identity and that we can always uniquely reference specific records. When you define a primary key constraint in SQL, the database system automatically enforces entity integrity by rejecting any insert or update operation that would violate these rules.
Referential Integrity: Maintaining Valid Relationships
Referential integrity ensures that relationships between tables remain consistent. Specifically, it requires that any foreign key value must either match a primary key value in the referenced table or be completely null. This prevents what we call “dangling references”, foreign key values that point to non-existent records. For example, referential integrity ensures that we cannot have an order record pointing to a customer who doesn’t exist in the customer table.
When we try to delete a record that’s referenced by foreign keys in other tables, the database system can handle this in several ways, depending on the referential action we specify. We might set up CASCADE DELETE, which automatically deletes all related records; SET NULL, which sets the foreign key to null; SET DEFAULT, which sets the foreign key to a default value; or RESTRICT, which prevents the deletion entirely. Similarly, when updating a primary key value, we can specify whether that change should cascade to all related foreign keys or be restricted. These options give us flexibility in managing how data changes propagate through related tables.
Domain Constraints: Controlling Data Values
Domain constraints restrict the set of valid values that attributes can contain. Every attribute has an associated domain that defines its legal values, and domain constraints enforce these restrictions. The most basic domain constraint is the data type, specifying whether an attribute contains integers, decimal numbers, character strings, dates, or other types of data. For example, defining a Price attribute as DECIMAL(10,2) constrains it to numeric values with two decimal places.
Beyond data types, we can impose additional constraints using CHECK constraints that specify conditions that values must satisfy. For instance, we might constrain an Age attribute to values between 0 and 150, or a Grade attribute to specific letter grades. Domain constraints help ensure data quality by preventing invalid data from entering the database. They act as the first line of defense against data corruption, catching errors at the point of entry rather than allowing problematic data to propagate through the system.
Additional Constraint Types
Beyond the core integrity rules, several other constraint types help us maintain data quality.
The NOT NULL constraint ensures that a particular attribute must always contain a value, it cannot be left empty. This is crucial for attributes that are essential for record identification or business logic.
The UNIQUE constraint ensures that all values in a column are different from one another, similar to a primary key but without the same semantic significance. We often use UNIQUE constraints for alternate candidate keys.
CHECK constraints allow us to define custom conditions that data must satisfy. For example, we might add a CHECK constraint to ensure that a Salary attribute is greater than zero, or that a Status attribute contains only specific values like ‘Active’, ‘Inactive’, or ‘Pending’. CHECK constraints give us fine-grained control over data validity, allowing us to encode business rules directly into the database structure. These constraints work together to create a comprehensive system of data validation that operates at the database level, independent of any application logic.
Part 4 — Translating ER Diagrams to Relational Tables
Mapping Entities to Relations
The process of converting an ER diagram into a relational schema follows systematic rules that preserve the semantics of our conceptual design. Regular entities from the ER model become relations in the relational schema, with each attribute of the entity becoming an attribute of the relation. The primary key of the entity becomes the primary key of the relation. For example, a Student entity with attributes StudentID, Name, and Major becomes a Student relation with the same attributes and StudentID as primary key.
When entities have composite attributes, we have two options: we can represent the composite attribute as a single attribute in the relation, or we can break it down into its component attributes. Typically, we choose to decompose composite attributes into simple attributes for better query capability and normalization. For instance, a Name attribute composed of FirstName, MiddleName, and LastName would typically be stored as three separate attributes in the relation. Multivalued attributes require special handling, we create a separate relation for them, with the primary key of the original entity plus the multivalued attribute.
Handling Relationship Mapping
The mapping of relationships depends on their cardinality in the ER model.
For one-to-many relationships, we add a foreign key to the relation on the “many” side that references the primary key of the relation on the “one” side. For example, in a relationship where one Department has many Employees, we add a DepartmentID foreign key to the Employee relation.
For one-to-one relationships, we can add a foreign key to either relation, typically choosing the relation that participates fully in the relationship or based on query performance considerations.
Many-to-many relationships require the creation of a new intersection relation that contains the primary keys of both participating relations as foreign keys, and these foreign keys together form the primary key of the new relation. For instance, a many-to-many relationship between Students and Courses would require a Registration relation with StudentID and CourseID as foreign keys that together form a composite primary key. This intersection relation can also include additional attributes that describe the relationship, such as RegistrationDate or Grade.
Mapping Special Cases
Weak entities require special handling in the translation process. A weak entity becomes a relation whose primary key is a composite key consisting of the partial key of the weak entity plus the primary key of the owner entity. For example, if we have a Dependent weak entity that depends on an Employee entity, the Dependent relation would have a primary key composed of DependentID (the partial key) and EmployeeID (from the owner entity). We also create a foreign key from the weak entity to the owner entity.
Get Ayoade Akintayo (PhD)’s stories in your inbox
Join Medium for free to get updates from this writer.
Specialization and generalization hierarchies from enhanced ER modeling can be implemented using several strategies. We might create a single relation for the superclass and include all subclass attributes, using a type attribute to distinguish between different subclasses. Alternatively, we might create separate relations for each subclass, including both the specific attributes and the common attributes from the superclass. A third approach creates relations for both the superclass and subclasses, with the subclass relations referencing the superclass via foreign keys. The choice between these strategies depends on factors like query patterns, data distribution, and performance requirements.
Real-Life Example: E-Commerce Database Scenario
Database Design for Online Retail
Let’s examine a comprehensive e-commerce database scenario to see how relational concepts apply in practice. Our online retail platform needs to manage customers, products, orders, and the complex relationships between them.
We design a CUSTOMER relation to store customer information with Customer_ID as the primary key, along with attributes like Name, Email, and Address. The PRODUCT relation tracks our inventory with Product_ID as primary key and attributes including Name, Price, and Stock quantity.
The ORDER relation records each purchase transaction, with Order_ID as primary key and Customer_ID as a foreign key referencing the CUSTOMER relation. This establishes that each order must be associated with an existing customer. Additionally, the ORDER relation includes Order_Date and Total_Amount attributes. Since each order can contain multiple products, we need an ORDER_ITEM relation to resolve this many-to-many relationship between orders and products. This intersection relation uses a composite primary key of Order_ID and Product_ID (both foreign keys), along with Quantity and Subtotal attributes.
Integrity Constraints in Action
The power of relational constraints becomes evident when we consider how they protect data quality in our e-commerce system.
Entity integrity ensures that each customer, product, and order has a unique identifier.
Referential integrity guarantees that we cannot have orders for non-existent customers or order items for non-existent products. If we try to delete a customer who has existing orders, the database will prevent this action unless we specify appropriate referential actions.
Domain constraints ensure that email addresses follow proper format, prices are positive numbers, and quantities are whole numbers.
NOT NULL constraints prevent critical information like customer names or order dates from being omitted.
UNIQUE constraints might ensure that email addresses aren’t duplicated across customers.
CHECK constraints could verify that order totals match the sum of their order item subtotals.
Together, these constraints create a robust system that maintains data quality automatically, regardless of how users or applications interact with the database.
Referential Integrity Consequences
Consider our discussion question: “What might happen to referential integrity if a customer’s record is deleted while their orders still exist?” Without proper constraint handling, this would create orphaned records, orders that reference a non-existent customer. This breaks referential integrity and leads to logical inconsistencies in the database. Queries trying to display order information along with customer details would fail or show incomplete results. Reporting systems might produce incorrect analytics, and application logic could crash when trying to access missing customer data.
In a properly designed database, we prevent this scenario through referential integrity constraints. When setting up the foreign key relationship, we can specify ON DELETE rules that control what happens when a customer is deleted. If we specify RESTRICT, the deletion would be blocked until all the customer’s orders are first deleted. If we specify CASCADE, deleting the customer would automatically delete all their orders. If we specify SET NULL, the Customer_ID in the orders would be set to null, preserving the order records but disassociating them from any customer. The appropriate choice depends on business rules, whether we need to maintain order history for auditing purposes even after customers leave.
Interactive Class Activity: “Find the Broken Link”
Identifying Integrity Violations
In this hands-on activity, you’ll work in small groups to examine a provided relational schema and sample data that intentionally contains referential integrity errors. You’ll be given table definitions and sample data similar to our e-commerce example, but with some inserted records that violate integrity constraints. For instance, you might find an order record that references a customer ID that doesn’t exist in the customer table, or a product reference in order items that points to a deleted product.
Your task is to play “database detective”, examining the relationships between tables, identifying where the integrity rules are broken, and proposing solutions to fix these issues. You’ll need to understand both the structure of the tables (what the foreign key relationships should be) and the actual data content (where those relationships are violated). This exercise will help you develop an intuitive understanding of how relational constraints work and why they’re essential for maintaining data quality.
Problem Resolution Strategies
As you identify integrity violations, consider the different approaches to resolving them. For orphaned foreign keys, you might need to insert missing parent records, update the foreign keys to point to valid parent records, or delete the orphaned child records altogether. The appropriate solution depends on the business context, whether the missing data should be recovered, the references should be corrected, or the invalid records should be purged.
This activity will also help you understand the practical implications of constraint definitions. You’ll see why we must carefully consider our ON DELETE and ON UPDATE rules when designing foreign key constraints. You’ll also gain appreciation for how database constraints serve as a safety net, catching data quality issues that might otherwise go unnoticed until they cause significant problems in reports or application behavior. By the end of this activity, you should be able to look at any relational schema and quickly identify potential integrity issues before they become problematic.
Hands-On Practical: Implementing Hospital System Tables
Creating Tables with Constraints
In this practical session, we’ll implement the hospital management system tables based on your ER diagrams from last week. We begin by creating the PATIENT table with appropriate constraints. The Patient_ID serves as the primary key, uniquely identifying each patient. The Name attribute has a NOT NULL constraint because every patient must have a name. The Gender attribute uses a CHECK constraint to ensure only valid values (‘M’ or ‘F’) are stored, and Contact_Number has a UNIQUE constraint to prevent duplicate phone numbers across patients.
Next, we create the DOCTOR table with Doctor_ID as primary key and attributes for Name and Specialty. While we might add more constraints in a real system, this gives us the basic structure. The APPOINTMENT table serves as the intersection between patients and doctors, with Appt_ID as primary key and both Patient_ID and Doctor_ID as foreign keys referencing their respective tables. These foreign keys ensure that we can only create appointments for existing patients and doctors. The NOT NULL constraints on the foreign keys guarantee that every appointment is properly associated with both a patient and a doctor.
Testing Constraint Enforcement
After creating our tables, we thoroughly test the constraints by attempting various operations that should either succeed or fail based on our defined rules. We start by inserting valid data: first a patient, then a doctor, then an appointment linking them together. These operations should succeed because they comply with all constraints. Next, we test the constraints by attempting invalid operations: trying to insert an appointment with a non-existent patient ID should fail with a foreign key violation error. Trying to insert a patient with a duplicate contact number should fail with a unique constraint violation.
We also test the CHECK constraints by attempting to insert a patient with gender ‘X’, this should be rejected. Testing the NOT NULL constraints by trying to insert a patient without a name should also fail. These tests are crucial for verifying that our constraints work as intended and will protect our data quality in production. The error messages generated by the database during these tests provide valuable information about what went wrong, helping us identify and fix data quality issues.
Database Dictionary Exploration
Oracle provides powerful data dictionary views that allow us to inspect our database structure programmatically. After creating our tables and constraints, we can use the DESC command to view the basic structure of each table. For more detailed information about constraints, we can query views like USER_CONSTRAINTS, which shows all constraints defined in our schema, and USER_CONS_COLUMNS, which shows which columns are involved in each constraint.
These dictionary views help us verify that our physical implementation matches our logical design. We can check that all intended constraints were created correctly, identify any missing constraints, and understand how different constraints relate to each other. This capability is particularly valuable when working with large, complex databases where manually tracking all constraints would be difficult. Learning to navigate the data dictionary is an essential skill for any database professional, enabling you to understand and document database structures effectively.
Group Assignment: Relational Schema Implementation
From ER Model to Physical Database
For this week’s group assignment, you’ll transform your hospital ER diagram from Week 2 into a fully implemented relational schema with comprehensive constraints. Working in your same groups, you’ll create SQL scripts that define all the tables, primary keys, foreign keys, and other constraints needed to implement your hospital management system. This practical exercise will solidify your understanding of how conceptual designs translate into physical databases.
For each entity in your ER diagram, create a corresponding table with appropriate attributes and data types. Define primary keys for each table, choosing the most appropriate identifiers. Establish foreign keys for all relationships, considering the cardinality and participation constraints from your ER diagram. Add relevant CHECK constraints for attributes with limited valid values, NOT NULL constraints for mandatory attributes, and UNIQUE constraints for alternate candidate keys. Your implementation should faithfully represent all the business rules captured in your original ER model.
Comprehensive Testing and Documentation
After implementing your schema, populate each table with at least 10 realistic sample records to demonstrate that your constraints work correctly. Your testing should include both successful operations (showing valid data being inserted) and failed operations (showing how constraints reject invalid data). Capture screenshots of these tests as evidence of your constraint enforcement.
Your final deliverable should be a comprehensive PDF report containing your complete SQL scripts, DESCRIBE output showing table structures, screenshots of successful and failed operations, and a brief explanation of how each constraint enforces important business rules. This assignment will be evaluated based on the completeness of your implementation, the appropriateness of your constraint choices, the quality of your testing, and the clarity of your documentation. This hands-on experience is invaluable for understanding how theoretical database concepts translate into practical implementations.
Reflective Discussion Question
The Partnership Between Database and Application Validation
Our reflective question this week asks: “If constraints can enforce data integrity automatically, why do we still need careful application-level validation?” This is a crucial consideration in database design. While database constraints provide a powerful, non-bypassable safety net for data quality, they operate at a relatively basic level and typically only catch problems after invalid data has been submitted. Application-level validation, in contrast, can provide a more user-friendly, proactive approach to data quality.
Application validation can catch errors before they ever reach the database, providing immediate feedback to users and preventing frustration. For example, an application can validate that an email address looks properly formatted before attempting to insert it, or can ensure that required fields are completed before submitting a form. Applications can also implement more complex business rules that would be difficult or inefficient to enforce at the database level, such as validating that a discount code hasn’t expired or checking inventory availability in real-time.
The most robust systems employ both strategies: application-level validation for user experience and complex business rules, and database constraints as a final safety net. This layered approach ensures data quality even if there are bugs in the application code, if users bypass the application to access the database directly, or if multiple applications access the same database with different validation logic. Database constraints provide the ultimate guarantee of data integrity, while application validation provides the user experience and complex logic that make systems usable and efficient.
Key Terms
Relation — A table storing data about a particular subject, with rows and columns that follow specific mathematical properties.
Tuple — A single row in a relation, representing a complete record about a particular entity instance.
Attribute — A column in a relation, representing a particular characteristic or property of the entity.
Schema — The logical structure of the database, defining relations, attributes, domains, and constraints.
Instance — The actual data stored in the database at a particular moment in time.
Primary Key — An attribute or set of attributes that uniquely identifies each tuple in a relation.
Foreign Key — An attribute in one relation that references the primary key of another relation, establishing a relationship between them.
Candidate Key — Any attribute or set of attributes that could serve as a primary key because they uniquely identify tuples.
Entity Integrity — The constraint that requires every relation to have a primary key and that primary key values be unique and not null.
Referential Integrity — The constraint that requires foreign key values to match existing primary key values in the referenced relation.
Constraints — Rules that restrict what data can be stored in the database, including NOT NULL, UNIQUE, and CHECK constraints.
Summary and Key Takeaways
This week we’ve explored the foundational concepts of the relational model and the crucial role of constraints in maintaining data integrity. We began by understanding the mathematical basis of the relational model and how it evolves from our ER designs. We examined the different types of keys that enable unique identification and relationship establishment between tables. Our deep dive into constraints revealed how entity integrity, referential integrity, and domain constraints work together to automatically enforce data quality rules.
Through our e-commerce case study and hospital implementation exercise, we saw how these theoretical concepts apply in practical scenarios. We learned that while database constraints provide essential protection for data quality, they work best in partnership with application-level validation that offers better user experience and handles more complex business rules. The relational model’s elegant simplicity, organizing data into tables with well-defined relationships and constraints, has proven remarkably durable and powerful, forming the basis for most modern database systems. As we continue through this course, remember that understanding these fundamental principles is essential for designing databases that are not only functionally correct but also maintainable, scalable, and reliable over time.










