Database Management SystemUnit 415 min read
Database Constraints & Normalization: Rules, Anomalies & Design
Unit 4 of Database Management System covers constraints (domain, key, referential, check, etc.) and normalization (1NF–BCNF) to eliminate redundancy, ensure data integrity, and optimize relational database design. Learn how to apply these rules to real-world schemas like banking or e-commerce systems, with SQL examples
TAKEAWAYS:
- Constraints enforce data rules (e.g.,
NOT NULL,UNIQUE,FOREIGN KEY) to maintain accuracy and consistency in databases. - Normalization (1NF–BCNF) systematically decomposes tables to eliminate insert/update/delete anomalies while preserving relationships.
- Functional dependencies and partial dependencies are the mathematical foundation for designing efficient schemas.
- Real-world applications: Constraints secure transactions (e.g., bank balances), while normalization speeds up queries (e.g., Daraz’s order processing).
- SQL implementation: Constraints are defined via
CREATE TABLEclauses (e.g.,PRIMARY KEY,CHECK), and normalization requires iterative table restructuring. - Trade-offs: Higher normal forms reduce redundancy but may increase join complexity; denormalization is sometimes used for performance.
1. Database Constraints: Rules to Enforce Data Integrity
Constraints are rules applied to database columns or tables to ensure data validity, consistency, and reliability. They prevent invalid operations (e.g., inserting duplicate records or violating business logic). Constraints can be column-level (applied to a single column) or table-level (applied across columns).
Types of Constraints with Examples
Use this table to compare constraints visually:
| Constraint Type | Definition | Syntax Example | Real-World Use Case |
|---|---|---|---|
| NOT NULL | Ensures a column cannot have NULL values. |
CREATE TABLE Student (SID INT NOT NULL, ...); |
SID in a university database (student IDs must exist). |
| UNIQUE | Ensures all values in a column are distinct. | CREATE TABLE Employee (Email VARCHAR(50) UNIQUE, ...); |
Email in a company database (no two employees share an email). |
| PRIMARY KEY (PK) | Uniquely identifies a row; cannot be NULL or duplicate. |
CREATE TABLE Order (OrderID INT PRIMARY KEY, ...); |
OrderID in an e-commerce system (each order must have a unique identifier). |
| FOREIGN KEY (FK) | Enforces referential integrity by linking to a primary key in another table. | CREATE TABLE OrderDetails (OrderID INT, ProductID INT, FOREIGN KEY (OrderID) REFERENCES Order(OrderID)); |
CustomerID in a Transaction table (must exist in the Customer table). |
| CHECK | Validates data against a boolean condition. | CREATE TABLE Account (Balance DECIMAL(10,2) CHECK (Balance >= 0), ...); |
Balance in a bank account (cannot be negative). |
| DEFAULT | Sets a default value if none is provided. | CREATE TABLE Product (Price DECIMAL(10,2) DEFAULT 0.00, ...); |
Status in an order table (defaults to "Pending" if not specified). |
| Composite Key | A primary key made of multiple columns. | CREATE TABLE Enrollment (SID INT, CID INT, PRIMARY KEY (SID, CID), ...); |
StudentID + CourseID in a university enrollment system (one student can enroll in multiple courses). |
Why Constraints Matter: Real-World Scenarios
eSewa (Nepal’s digital payment system)
- Constraint Used:
FOREIGN KEYandCHECK - How? When a user transfers money, the system checks:
- The
AccountIDexists in theUsertable (FOREIGN KEY). - The
Balanceafter transfer is ≥ 0 (CHECKconstraint).
- The
- Outcome: Prevents fraudulent transactions or overdrafts.
- Constraint Used:
Khalti (Mobile Payment App)
- Constraint Used:
UNIQUEandNOT NULL - How? Every transaction has a unique
TransactionID(UNIQUE), and theAmountcannot beNULL(NOT NULL). - Outcome: Ensures every transaction is traceable and valid.
- Constraint Used:
NTC (Nepal Telecom) Billing System
- Constraint Used:
CHECKandDEFAULT - How? Customer plans have a
ValidityPeriodwith aCHECKto ensure it’s not expired, andStatusdefaults to"Active". - Outcome: Prevents billing errors for expired connections.
- Constraint Used:
2. Anomalies in Databases: Why Normalization is Needed
Before normalization, databases often suffer from anomalies—problems that arise when data is redundant, inconsistent, or inefficient. There are three types:
Types of Anomalies
mindmap
root((Database Anomalies))
Insertion
"Cannot insert data without related data"
Example: Adding a course without any students enrolled.
Update
"Updating one record requires updating multiple records"
Example: Changing a student’s address in multiple tables.
Deletion
"Deleting data unintentionally removes other data"
Example: Deleting a course removes all its enrolled students.Example: Unnormalized University Database
Consider a table StudentCourse storing student-course enrollments without proper design:
| StudentName | CourseName | Grade |
|---|---|---|
| Ram | Math | A |
| Ram | Physics | B |
| Sita | Math | A- |
| Sita | Chemistry | B+ |
Problems:
- Insertion Anomaly: Cannot add a new course (e.g., "Biology") without a student enrolled.
- Update Anomaly: If Ram changes his name to "Ram Prasad," you must update all rows where Ram appears.
- Deletion Anomaly: If Ram drops Physics, his Math record is not deleted, but the data is still duplicated.
3. Normalization: Step-by-Step Rules to Fix Anomalies
Normalization is the process of organizing data into tables to minimize redundancy and dependency. The normal forms (1NF–BCNF) are hierarchical rules.
Normal Forms Summary Table
| Normal Form | Rule | Example Violation | Fix |
|---|---|---|---|
| 1NF | All attributes must contain atomic (indivisible) values; no repeating groups. | A column like Courses = ["Math", "Physics"] in a single cell. |
Split into separate rows: StudentID, CourseID, Grade. |
| 2NF | Must be in 1NF and no partial dependencies (non-key attributes depend on part of PK). | A composite PK StudentID + CourseID where Grade depends only on StudentID. |
Separate Student and Course tables; link via Enrollment. |
| 3NF | Must be in 2NF and no transitive dependencies (non-key attributes depend on other non-key attributes). | Student table with StudentID, Name, Department, DepartmentHead (where DepartmentHead depends on Department). |
Move Department and DepartmentHead to a separate Department table. |
| BCNF | Stricter than 3NF: Every determinant must be a candidate key. | A table where a non-PK attribute determines another non-PK attribute. | Further decompose tables to eliminate all non-trivial dependencies. |
Worked Example: Normalizing a Car Rental Database
Initial Unnormalized Table (Rental):
| CarID | CustomerName | RentalDates | Model | LicensePlate |
|---|---|---|---|---|
| C001 | John | 2023-10-01 to 2023-10-05 | Toyota | KA-01-AB |
| C001 | Alice | 2023-10-10 to 2023-10-15 | Toyota | KA-01-AB |
| C002 | Bob | 2023-10-02 to 2023-10-07 | Honda | KA-02-CD |
Issues:
- Repeating
CarIDandModel(violation of 1NF). CustomerNameandRentalDatesare duplicated for the same car.
Step-by-Step Normalization:
1NF: Atomic Values
- Split
RentalDatesintoStartDateandEndDate. - Remove repeating groups (e.g.,
Modelis repeated forCarID).
- Split
2NF: Remove Partial Dependencies
CarIDis part of the PK (CarID + CustomerName), butModelandLicensePlatedepend only onCarID.- Fix: Create a
Cartable:CREATE TABLE Car ( CarID INT PRIMARY KEY, Model VARCHAR(50) NOT NULL, LicensePlate VARCHAR(20) UNIQUE NOT NULL );
3NF: Remove Transitive Dependencies
- No transitive dependencies exist here, so we stop at 3NF.
Final Normalized Schema:
Real-World Tie-In: Pathao’s Ride Booking System
- Problem: If Pathao stored driver details, ride history, and payment in one table, updating a driver’s license would require multiple edits.
- Solution: Normalization separates:
Driver(ID, Name, License, Vehicle)Ride(RideID, DriverID, StartTime, EndTime, Location)Payment(RideID, Amount, Status)
- Benefit: Faster queries, less redundancy, and easier updates.
4. Functional Dependencies and Dependency Analysis
Functional dependencies (FDs) are the mathematical foundation of normalization. They define how one attribute determines another.
Notation and Examples
- Notation:
X → Ymeans "X functionally determines Y" (each X value maps to exactly one Y value). - Example:
- In a
Studenttable:SID → SName(one student ID maps to one name). SID → Department(one student ID maps to one department).
- In a
Types of Dependencies
- Full Functional Dependency (FFD): A non-key attribute depends on the entire primary key.
- Example:
(SID, CID) → Grade(grade depends on both student and course).
- Example:
- Partial Dependency: A non-key attribute depends on part of the primary key (violates 2NF).
- Example:
(SID, CID) → SName(SName depends only onSID).
- Example:
- Transitive Dependency: A non-key attribute depends on another non-key attribute (violates 3NF).
- Example:
SID → DepartmentandDepartment → DeanimpliesSID → Dean(transitive).
- Example:
Dependency Diagram for a University Database
graph LR
SID["SID"] --> SName["SName"]
SID --> Department["Department"]
Department --> Dean["Dean"]
SID & Department --> Grade["Grade"]Color-coded functional dependencies: Candidate key (yellow), partial dependency (blue), transitive dependency (red) Interpretation:
SID → SName(direct dependency).SID → Department → Dean(transitive dependency).(SID, CID) → Grade(full dependency).
5. Denormalization: When to Break the Rules
While normalization reduces redundancy, denormalization (intentionally introducing redundancy) is sometimes used for performance optimization.
When to Denormalize?
| Scenario | Example |
|---|---|
| Read-heavy workloads | E-commerce product pages (displaying ProductName, Category, Price in one query). |
| Complex joins | Reporting systems where joins slow down queries. |
| Data warehousing | Star schemas in OLAP systems (e.g., NEPSE stock analysis). |
Example: Daraz’s Order Processing
- Normalized Design:
Order(OrderID, CustomerID, OrderDate)Customer(CustomerID, Name, Address)Product(ProductID, Name, Price)OrderItem(OrderID, ProductID, Quantity)
- Denormalized View for Faster Checkout:
Combine
CustomerandOrderinto a single table to avoid joins during checkout:
→ Trade-off: Faster reads but slower writes (updates toSELECT o.OrderID, c.Name, c.Address, o.OrderDate FROM Order o JOIN Customer c ON o.CustomerID = c.CustomerID;Customermust update multiple rows).
6. SQL Implementation of Constraints and Normalization
Creating Tables with Constraints
-- Bank Account Table with Constraints
CREATE TABLE Account (
AccountNumber INT PRIMARY KEY,
CustomerID INT NOT NULL,
Balance DECIMAL(10,2) CHECK (Balance >= 0),
BranchID INT,
FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID),
FOREIGN KEY (BranchID) REFERENCES Branch(BranchID)
);
-- Student-Course Enrollment (3NF)
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);
CREATE TABLE Course (
CourseID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
CreditHours INT
);
CREATE TABLE Enrollment (
StudentID INT,
CourseID INT,
Grade CHAR(2),
PRIMARY KEY (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
FOREIGN KEY (CourseID) REFERENCES Course(CourseID)
);
Modifying Tables to Add Constraints
-- Adding a CHECK constraint to ensure valid grades
ALTER TABLE Enrollment
ADD CONSTRAINT CHK_Grade CHECK (Grade IN ('A', 'A-', 'B+', 'B', 'C', 'D', 'F'));
-- Adding a DEFAULT value for order status
ALTER TABLE Order
ADD COLUMN Status VARCHAR(20) DEFAULT 'Pending';
7. Exam Tip: How to Score Full Marks
For Constraint Questions:
- Always define the constraint first (e.g., "A
FOREIGN KEYensures referential integrity by linking to a primary key in another table"). - Provide a SQL syntax example (e.g.,
FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID)). - Give a real-world analogy (e.g., "Like how a library book must belong to a valid member").
- Always define the constraint first (e.g., "A
For Normalization Questions:
- Step-by-step trace: Show the initial table → anomalies → normalized tables.
- Use 1NF–3NF labels: Clearly state which normal form each step achieves.
- Draw an ER diagram (if allowed) for the final schema.
- Relate to business logic: Explain how normalization prevents anomalies (e.g., "Without 2NF, updating a student’s address would require editing multiple rows").
Common Pitfalls to Avoid:
- ❌ Forgetting to mention partial dependencies in 2NF or transitive dependencies in 3NF.
- ❌ Skipping the initial unnormalized table in worked examples.
- ❌ Using vague language like "remove redundancy" without specifying how (e.g., "separate into tables").
High-Score Formula for SQL Questions:
- Step 1: Write the
CREATE TABLEstatement with all constraints. - Step 2: Insert sample data using
INSERT INTO. - Step 3: Write a query to demonstrate the constraint (e.g.,
SELECT * FROM Account WHERE Balance < 0;should return no rows).
- Step 1: Write the
Based on the TU BBA syllabus for Database Management System (IT232), unit 4.
Discussion
Loading…