Database Management SystemUnit 319 min read
Relational Model: Tables, Keys, Integrity & Normal Forms
Unit 3 of Database Management System explores the relational model—how data is organized into tables (relations), how keys (primary, foreign) enforce relationships, and how normalization (1NF–BCNF) eliminates redundancy. Learn relational algebra operations, schema design, and real-world applications in banking, e-comme
TAKEAWAYS:
- The relational model represents data as tables (relations) with rows (tuples) and columns (attributes), governed by keys (primary, candidate, foreign) and integrity constraints.
- Relational algebra (select, project, join, etc.) provides a formal way to query and manipulate data without relying on procedural code.
- Normalization (1NF–BCNF) systematically eliminates redundancy by decomposing tables into well-structured forms, improving efficiency and consistency.
- Schema vs. instance: A schema defines the structure (tables, columns, constraints), while an instance is a snapshot of actual data at a given time.
- Real-world systems (e.g., eSewa, Khalti, NEPSE) use relational databases to manage transactions, user accounts, and financial records with ACID properties.
- Foreign keys enforce referential integrity, ensuring relationships between tables (e.g., linking a customer to their orders in Daraz).
Core Concepts of the Relational Model
erDiagram
Student { string student_id PK "Unique ID" string name string email string dept_id FK }
Department { string dept_id PK "Department ID" string dept_name string location }
Enrollment { string student_id FK string course_id FK string grade }
Course { string course_id PK "Course ID" string course_name string credits }
Student ||--o{ Enrollment : enrolls_in
Department ||--o{ Student : belongs_to
Course ||--o{ Enrollment : offers
Enrollment { string student_id, string course_id } ||--|{ Student : "Student ID"
Enrollment { string student_id, string course_id } ||--|{ Course : "Course ID"ER diagram of a university database with primary/foreign keys and relationships1. Tables as Relations
In the relational model, data is stored in tables (called relations), where:
- Each row (tuple) represents a single entity (e.g., a student, order, or account).
- Each column (attribute) holds a specific field (e.g.,
student_id,name,email). - A relation has a name (e.g.,
Student,Course) and a degree (number of attributes) and cardinality (number of tuples).
Why tables? Tables are intuitive, easy to understand, and mathematically rigorous. They allow us to define relationships between entities clearly.
2. Keys: The Backbone of Relationships
Keys ensure uniqueness and enforce relationships between tables.
| Key Type | Definition | Example |
|---|---|---|
| Primary Key (PK) | Uniquely identifies a tuple in a relation. Cannot be NULL. |
student_id in the Student table. |
| Candidate Key | An attribute (or set) that could be a primary key. | email in Student (if no two students share the same email). |
| Foreign Key (FK) | A column in one table that references the PK of another table. Enforces relationships. | course_id in Enrollment references course_id in Course. |
| Superkey | A set of attributes that uniquely identifies tuples (but may be redundant). | {student_id, name} in Student (if student_id alone is PK). |
| Alternate Key | A candidate key not chosen as the primary key. | email in Student (if student_id is PK). |
3. Integrity Constraints
These rules ensure data accuracy and consistency.
| Constraint | Purpose | Example |
|---|---|---|
| Entity Integrity | Ensures no primary key is NULL or duplicate. |
student_id cannot be NULL in Student. |
| Referential Integrity | Ensures foreign keys match valid primary keys in the referenced table. | A student_id in Enrollment must exist in Student. |
| Domain Integrity | Ensures attribute values are from a valid set (data type, range, format). | age in Student must be between 16 and 100. |
| User-Defined Constraints | Custom rules (e.g., salary > 0, email must contain @). |
salary in Employee cannot be negative. |
Relational Algebra: The Formal Query Language
Relational algebra is a procedural query language (unlike SQL, which is declarative). It uses operations to manipulate relations. Here are the key operations:
Basic Operations
| Operation | Symbol | Description | Example |
|---|---|---|---|
| Select (σ) | σ | Filters tuples based on a condition. | σ_{age > 20}(Student) → All students older than 20. |
| Project (π) | π | Selects specific columns (attributes). | π_{name, email}(Student) → Only name and email columns. |
| Union (∪) | ∪ | Combines tuples from two relations (must have the same schema). | R ∪ S → All tuples in R or S (no duplicates). |
| Set Difference (–) | – | Returns tuples in the first relation but not the second. | R – S → Tuples in R but not in S. |
| Cartesian Product (×) | × | Combines every tuple from the first relation with every tuple from the second. | R × S → All possible pairs (R rows × S rows). |
| Rename (ρ) | ρ | Renames a relation or attribute. | ρ_{X}(R) → Renames relation R to X. |
Join Operations
Joins combine tuples from two relations based on a common attribute.
| Join Type | Symbol | Description | Example |
|---|---|---|---|
| Theta Join (⋈) | ⋈ | Joins tuples where a condition is met (general form). | R ⋈_{R.age = S.age} S → Joins R and S where ages match. |
| Equijoin | ⋈ | A theta join where the condition is equality (e.g., R.A = S.B). |
Student ⋈_{Student.dept_id = Department.dept_id} Department. |
| Natural Join (⋈) | ⋈ | Joins on all common attributes (no duplicates). | Student ⋈ Department → Joins on dept_id (common column). |
| Outer Joins | – | Includes all tuples from one relation, even if no match exists. | Left Outer Join: All students, even if not enrolled in any course. |
WORKED EXAMPLE: Joining Tables Suppose we have two tables:
Employee(person_name, company_name, salary)Company(company_name, city)
Question: Find all employees and their company’s city. Relational Algebra Expression:
π_{person_name, city}(Employee ⋈ Company)
Explanation:
- Join (⋈): Combine
EmployeeandCompanywherecompany_namematches. - Project (π): Select only
person_nameandcityfrom the result.
MERMAID DIAGRAM:
erDiagram
Employee ||--o{ Company : "works_at"
Employee {
string person_name PK
string company_name FK
int salary
}
Company {
string company_name PK
string city
}This shows the relationship between Employee and Company via company_name (foreign key).
In the Real World
The relational model powers every major system students interact with daily. Here’s how:
eSewa (Nepal Government)
- Tables Used:
User,Transaction,Service,Payment. - Relational Idea: Foreign keys link a
Transactionto aUser(viauser_id) and to aService(viaservice_id). Normalization ensures no duplicate service records. - Example: When you pay a traffic fine, eSewa’s database:
- Checks if your
user_idexists (entity integrity). - Validates the
service_id(referential integrity). - Updates the
Transactiontable with your payment.
- Checks if your
- Tables Used:
Khalti (Digital Payments)
- Tables Used:
Customer,Account,Transaction,Merchant. - Relational Idea: Foreign keys enforce that every
Transactionmust reference a validCustomerandMerchant. Normalization (3NF) prevents redundant merchant details. - Example: When you transfer money to a friend:
- Khalti’s system checks your
account_id(PK) and your friend’saccount_id(FK). - The
Transactiontable logs the transfer with timestamps and amounts.
- Khalti’s system checks your
- Tables Used:
NEPSE (Nepal Stock Exchange)
- Tables Used:
Company,Shareholder,Trade,Portfolio. - Relational Idea: The
Tradetable has foreign keys toCompany(for stock symbol) andShareholder(for buyer/seller). Normalization ensures no duplicate company profiles. - Example: When you buy shares of Ncell:
- NEPSE’s database checks if
Ncellexists inCompany(PK). - Links your
shareholder_id(FK) to theTraderecord.
- NEPSE’s database checks if
- Tables Used:
Daraz (E-Commerce)
- Tables Used:
Customer,Order,Product,OrderItem. - Relational Idea: An
Ordercan have multipleOrderItemrecords (1:N relationship). Foreign keys ensure everyOrderItemreferences a validOrderandProduct. - Example: When you place an order:
- Daraz’s system creates an
Orderrecord (PK:order_id). - Each product in your cart becomes an
OrderItem(FK:order_id). - The
Producttable ensures stock levels are updated correctly.
- Daraz’s system creates an
- Tables Used:
Normalization: Eliminating Redundancy
Normalization is the process of decomposing tables to reduce redundancy and dependency issues. It follows a hierarchy of normal forms (NF).
Why Normalize?
- Redundancy: Duplicate data wastes storage and causes update anomalies.
- Anomalies:
- Insertion Anomaly: Cannot insert data without violating constraints.
- Update Anomaly: Updating one record requires multiple changes.
- Deletion Anomaly: Deleting data unintentionally removes other data.
Normal Forms
| Normal Form | Rule | Example Violation | Fix |
|---|---|---|---|
| 1NF | All attributes contain atomic (indivisible) values. No repeating groups. | A Student table with courses stored as a comma-separated list ("CS101, MATH201"). |
Split into separate Enrollment table with student_id, course_id. |
| 2NF | Must be in 1NF and no partial dependencies (non-key attributes depend on the whole PK). | A table Enrollment(student_id, course_id, grade) where student_id alone determines grade. |
Separate Grade table with (student_id, course_id) as PK. |
| 3NF | Must be in 2NF and no transitive dependencies (non-key attributes depend on other non-key attributes). | A Student table where city depends on dept_id, which depends on student_id. |
Move city to Department table. |
| BCNF | Stricter than 3NF: Every determinant must be a candidate key. | A Course table where instructor depends on course_id, but course_id is not the only PK. |
Ensure all determinants are candidate keys (e.g., (course_id, semester) as PK). |
WORKED EXAMPLE: Normalizing a Poorly Designed Table
Unnormalized Table: StudentCourse
| student_name | course_name | grade | instructor | dept_name |
|---|---|---|---|---|
| Ram | Database | A | Prof. X | CS |
| Sita | Database | B | Prof. X | CS |
| Ram | OS | B- | Prof. Y | CS |
Problems:
- Redundancy:
instructoranddept_namerepeat for the same course. - Update Anomaly: Changing
Prof. X’s name requires updating multiple rows. - Insertion Anomaly: Cannot add a new course without a student enrolled.
Normalized Design (3NF):
- Student (
student_idPK,student_name) - Course (
course_idPK,course_name,instructor,dept_name) - Enrollment (
student_idFK,course_idFK,grade)
MERMAID DIAGRAM:
erDiagram
Student ||--o{ Enrollment : "takes"
Course ||--o{ Enrollment : "offers"
Student {
int student_id PK
string student_name
}
Course {
int course_id PK
string course_name
string instructor
string dept_name
}
Enrollment {
int student_id PK, FK
int course_id PK, FK
string grade
}Schema vs. Instance: The Big Picture
| Term | Definition | Example |
|---|---|---|
| Schema | The structure of the database: tables, columns, constraints, and relationships. | CREATE TABLE Student (student_id INT PRIMARY KEY, name VARCHAR(50)); |
| Instance | A snapshot of the actual data in the database at a given time. | The Student table with rows: (1, "Ram"), (2, "Sita"). |
| DDL (Data Definition Language) | Commands to define the schema (e.g., CREATE, ALTER, DROP). |
CREATE TABLE Employee (emp_id INT PRIMARY KEY, name VARCHAR(100)); |
| DML (Data Manipulation Language) | Commands to query or modify data (e.g., SELECT, INSERT, UPDATE, DELETE). |
INSERT INTO Employee VALUES (1, "John"); |
| DCL (Data Control Language) | Commands to control access (e.g., GRANT, REVOKE). |
GRANT SELECT ON Student TO Faculty; |
stateDiagram-v2
[*] --> Schema
Schema --> Instance: "Defines structure (tables, keys, constraints)"
Instance --> [*]: "Snapshot of actual data"
Schema --> Schema: "Can evolve (ALTER TABLE)"
Instance --> Instance: "Changes with CRUD operations"State diagram showing schema (structure) vs. instance (data snapshot) lifecycleAdvantages and Disadvantages of the Relational Model
| Advantages | Disadvantages |
|---|---|
| Structured Query Language (SQL): Standardized, powerful, and widely supported. | Performance Overhead: Joins can be slow on large datasets. |
| ACID Compliance: Ensures transactions are Atomic, Consistent, Isolated, and Durable. | Complexity: Requires careful schema design to avoid anomalies. |
| Data Integrity: Constraints (PK, FK, checks) prevent invalid data. | Scalability: Vertical scaling (adding more power to a server) is limited. |
| Self-Describing: Schema metadata is stored in the database itself. | Not Ideal for Hierarchical/Data: Poor fit for nested or graph-like data (use NoSQL instead). |
| Widely Used: Powers 90% of enterprise applications (banks, e-commerce, governments). | Schema Rigidity: Changing schema can be difficult in large systems. |
Exam Tip: How to Score Full Marks
Define Clearly:
- For relational model, start with: "The relational model represents data as a collection of tables (relations) where each table has rows (tuples) and columns (attributes), governed by keys and integrity constraints."
- For normalization, explain the purpose (eliminate redundancy) and steps (1NF → 3NF → BCNF) with examples.
Draw ER Diagrams:
- Always include an ER diagram for relationship questions. Label:
- Entities (rectangles).
- Attributes (ovals).
- Primary keys (underlined).
- Relationships (diamonds or lines with cardinality).
- Always include an ER diagram for relationship questions. Label:
Relational Algebra:
- Break down complex queries into steps (e.g., first join, then project).
- Use symbols (σ, π, ⋈) to show formal expressions.
- Example: For "Find all employees in Kathmandu", write:
σ_{city = 'Kathmandu'}(Employee)
Normalization:
- Identify anomalies in the given table before proposing fixes.
- Show the decomposition step-by-step (e.g., 1NF → 2NF → 3NF).
- Justify each step (e.g., "This eliminates partial dependency on
student_id").
Real-World Links:
- Connect concepts to eSewa, Khalti, or NEPSE in your answers. For example:
"In Khalti’s database, the
Transactiontable has a foreign key toCustomerto ensure referential integrity, similar to how we use foreign keys in relational algebra."
- Connect concepts to eSewa, Khalti, or NEPSE in your answers. For example:
"In Khalti’s database, the
Common Pitfalls:
- Don’t confuse schema and instance. Schema is the structure; instance is the data.
- Don’t forget constraints. Always mention entity integrity (PK) and referential integrity (FK) where relevant.
- Avoid vague answers. Instead of "it’s used for queries", say "relational algebra provides a formal way to express queries like selection (σ) and projection (π)."
Practice Questions (Based on Past Exams)
Differentiate between schema and instance.
- Schema: The blueprint (e.g.,
Student(student_id, name)). - Instance: The actual data (e.g.,
(1, "Ram"),(2, "Sita")).
- Schema: The blueprint (e.g.,
Write relational algebra for: "Find all employees earning more than 50,000 in Kathmandu."
σ_{salary > 50000 ∧ city = 'Kathmandu'}(Employee)Normalize the following table to 3NF: | order_id | customer_name | product_name | quantity | unit_price | customer_city |
- Step 1 (1NF): Already atomic.
- Step 2 (2NF): Remove partial dependency → Separate
CustomerandOrderItem. - Step 3 (3NF): Remove transitive dependency → Move
customer_citytoCustomer.
Draw an ER diagram for a Library Management System.
- Entities:
Book,Member,Loan. - Relationships:
MemberborrowsBook(viaLoan). - Attributes:
Book(isbn, title, author),Member(member_id, name),Loan(loan_id, date, due_date).
- Entities:
In the real world
- eSewa: Uses relational databases to store user accounts (PK: user_id), transactions (FK: user_id, FK: service_id), and service providers (PK: service_id). Foreign keys enforce referential integrity (e.g., a transaction must link to a valid user and service).
- NEPSE (Nepal Stock Exchange): Relational tables track traders (PK: trader_id), shares (PK: share_id), and transactions (FK: trader_id, FK: share_id). Normalization ensures no redundant share data across transactions.
- Daraz (Nepal): Customer orders (FK: customer_id) link to product tables (PK: product_id) via foreign keys, while inventory levels are managed in normalized tables to avoid redundancy.
Based on the PU BE Computer (PU) syllabus for Database Management System, unit 3.
Discussion
Loading…