Database Management SystemUnit 522 min read
Database Design & Schema Architecture: 3-Schema Model, ER-to-Relational, SQL Schema, Views, Integrity
Unit 5 of Database Management System covers the three-schema architecture (conceptual, internal, external), logical database design (ER to relational mapping), SQL schema creation (CREATE TABLE, constraints), database views (virtual tables), and schema evolution (ALTER, DROP). Learn how to design scalable databases for
TAKEAWAYS:
- The three-schema architecture (ANSI/SPARC) separates user views (external), logical design (conceptual), and physical storage (internal) to insulate applications from database changes.
- ER-to-relational mapping converts entities, relationships, and attributes into tables, foreign keys, and constraints—critical for designing databases like Ncell’s customer-billing system.
- SQL schema commands (
CREATE TABLE,ALTER TABLE,DROP TABLE) build the database structure, while views (CREATE VIEW) provide customized data access without duplicating data. - Schema evolution (adding/removing columns, renaming tables) must handle backward compatibility—e.g., when Daraz adds a new order status field.
- Normalization vs. denormalization: Normalized schemas reduce redundancy (e.g., NEPSE’s stock tables), but denormalization (e.g., eSewa’s transaction logs) can improve read performance.
- Constraints (primary keys, foreign keys, checks) enforce data integrity—e.g., ensuring a Pathao driver’s
driver_idalways matches theDriverstable.
1. The Three-Schema Architecture: ANSI/SPARC Model
The three-schema architecture is the foundation of database design, introduced by ANSI/SPARC in 1975. It divides the database into three layers to manage complexity and change:
classDiagram
class ExternalSchema {
+User-specific views
+Customized data access
+Insulates from internal changes
}
class ConceptualSchema {
+Logical structure (entities, relationships)
+Independent of storage/access
+Shared by all external schemas
}
class InternalSchema {
+Physical storage details
+File organizations, indexes
+DBMS-specific
}
ExternalSchema --> ConceptualSchema : "Maps to"
ConceptualSchema --> InternalSchema : "Maps to"
note for ExternalSchema "Example: eSewa user sees only their transactions"
note for ConceptualSchema "Example: ER diagram of eSewa’s payment system"
note for InternalSchema "Example: B-tree indexes on eSewa’s transaction table"Three-Schema Architecture: Layers of Abstraction in eSewa’s Database```mermaid
classDiagram
class ExternalSchema {
+User-specific views
+Customized data access
+Insulates from internal changes
}
class ConceptualSchema {
+Logical structure (entities, relationships)
+Independent of storage/access
+Shared by all external schemas
}
class InternalSchema {
+Physical storage details
+File organizations, indexes
+DBMS-specific
}
ExternalSchema --> ConceptualSchema : "Maps to"
ConceptualSchema --> InternalSchema : "Maps to"
note for ExternalSchema "Example: eSewa user sees only their transactions"
note for ConceptualSchema "Example: ER diagram of eSewa’s payment system"
note for InternalSchema "Example: B-tree indexes on eSewa’s transaction table"
Key Components:
| Schema | Purpose | Example (Nepal Context) |
|---|---|---|
| External Schema | Defines views for specific users/applications. | A bank customer sees only their account balance, not internal loan records. |
| Conceptual Schema | Logical design (entities, relationships, constraints). | NEPSE’s stock database: Stock, Trader, Transaction tables with foreign keys. |
| Internal Schema | Physical storage (files, indexes, hashing). | Ncell’s customer data stored in partitioned tables by region (East, West, Kathmandu). |
Why It Matters:
- Insulation: Changing the internal schema (e.g., switching from a flat file to a relational DB) doesn’t break external applications.
- Security: External schemas can hide sensitive data (e.g.,
password_hashin eSewa’sUserstable). - Flexibility: Add new user views without modifying the core database.
2. Logical Database Design: ER to Relational Mapping
Convert an ER diagram into a relational schema using these rules:
erDiagram
STUDENT ||--o{ ENROLLMENT : enrolls
ENROLLMENT ||--o{ COURSE : takes
STUDENT {
string student_id PK
string name
string email
}
COURSE {
string course_id PK
string title
int credit_hours
}
ENROLLMENT {
string student_id PK,FK
string course_id PK,FK
string grade
}ER Diagram: University Enrollment System (Nepal Context)Step-by-Step Mapping Rules:
Entities → Tables
- Each entity becomes a table with attributes as columns.
- Primary Key (PK): Underlined attribute (e.g.,
student_idinStudents).
Relationships → Tables or Foreign Keys
- 1:1 or 1:M: Add the PK of the "1" side as a foreign key (FK) to the "many" side.
- M:N: Create a junction table with PKs of both entities + optional attributes.
- Weak Entities: Include the identifying relationship’s PK as part of their PK.
Attributes
- Simple attributes → columns.
- Composite attributes → split into columns (e.g.,
address→street,city,zip). - Multivalued attributes → separate table (e.g.,
Student_Phones).
Example: University Database (ER to Relational)
ER Diagram (Conceptual):
```mermaid
erDiagram
STUDENT ||--o{ ENROLLMENT : enrolls
ENROLLMENT ||--o{ COURSE : takes
STUDENT {
string student_id PK
string name
string email
}
COURSE {
string course_id PK
string title
int credit_hours
}
ENROLLMENT {
string student_id PK,FK
string course_id PK,FK
string grade
}
**Relational Schema (SQL):**
```sql
CREATE TABLE Student (
student_id VARCHAR(10) PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) UNIQUE
);
CREATE TABLE Course (
course_id VARCHAR(10) PRIMARY KEY,
title VARCHAR(100) NOT NULL,
credit_hours INT CHECK (credit_hours > 0)
);
CREATE TABLE Enrollment (
student_id VARCHAR(10),
course_id VARCHAR(10),
grade CHAR(2),
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES Student(student_id),
FOREIGN KEY (course_id) REFERENCES Course(course_id)
);
Real-World Tie-In: NEPSE’s Stock Trading System
NEPSE’s database must track:
- Traders (with
trader_id,name,balance). - Stocks (with
stock_id,symbol,price). - Transactions (with
trader_id,stock_id,quantity,timestamp).
Problem: A trader can buy/sell multiple stocks → M:N relationship.
Solution: Junction table Transactions with composite PK (trader_id, stock_id, transaction_id).
3. SQL Schema Creation: Tables, Constraints, and Keys
SQL uses CREATE TABLE to define the database schema. Key components:
A. Data Types
| Data Type | Example | Use Case |
|---|---|---|
INT/SMALLINT |
age INT |
Numeric values (e.g., credit_hours). |
VARCHAR(n) |
name VARCHAR(50) |
Variable-length strings (e.g., student_name). |
DATE/TIMESTAMP |
enrollment_date DATE |
Dates (e.g., order_date in Daraz). |
DECIMAL(p,s) |
balance DECIMAL(10,2) |
Financial data (e.g., bank balances). |
BOOLEAN |
is_active BOOLEAN |
Flags (e.g., account_status). |
B. Constraints
| Constraint | Syntax | Example | Real-World Use |
|---|---|---|---|
| Primary Key (PK) | PRIMARY KEY (column) or column INT PRIMARY KEY |
student_id INT PRIMARY KEY |
Unique identifier for each student in TU’s database. |
| Foreign Key (FK) | FOREIGN KEY (col) REFERENCES table(pk) |
enrollment (student_id FK REFERENCES Student(student_id)) |
Ensures Enrollment records link to valid Student IDs. |
| NOT NULL | column datatype NOT NULL |
email VARCHAR(50) NOT NULL |
eSewa requires every user to have an email. |
| UNIQUE | UNIQUE (column) |
UNIQUE (email) |
No two Ncell customers can have the same phone number. |
| CHECK | CHECK (condition) |
CHECK (credit_hours BETWEEN 1 AND 6) |
TU courses must have 1–6 credit hours. |
| DEFAULT | DEFAULT value |
status VARCHAR(20) DEFAULT 'active' |
New Daraz orders default to status = 'pending'. |
C. Worked Example: Daraz Order System
Scenario: Daraz needs to track orders, customers, and products. Schema:
CREATE TABLE Customer (
customer_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
phone VARCHAR(15),
address VARCHAR(200)
);
CREATE TABLE Product (
product_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) CHECK (price > 0),
stock_quantity INT DEFAULT 0
);
CREATE TABLE Order (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(20) CHECK (status IN ('pending', 'shipped', 'delivered', 'cancelled')),
FOREIGN KEY (customer_id) REFERENCES Customer(customer_id)
);
CREATE TABLE OrderItem (
order_id INT,
product_id INT,
quantity INT CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES Order(order_id),
FOREIGN KEY (product_id) REFERENCES Product(product_id)
);
Why This Design?
- Normalization:
OrderandOrderItemavoid redundancy (one order can have many products). - Constraints:
CHECK (price > 0)prevents negative prices;FOREIGN KEYensures valid customer IDs. - Default Values:
order_dateauto-fills to current time;statusdefaults to'pending'.
4. Database Views: Virtual Tables
Views are virtual tables defined by a SQL query. They:
- Provide customized access to data (e.g., hide sensitive columns).
- Simplify complex queries (e.g.,
ActiveCustomersview). - Do not store data—they dynamically fetch data from base tables.
Creating and Using Views
-- Create a view of active students (enrolled in at least one course)
CREATE VIEW ActiveStudents AS
SELECT student_id, name, email
FROM Student
WHERE student_id IN (SELECT student_id FROM Enrollment);
-- Query the view
SELECT * FROM ActiveStudents WHERE email LIKE '%tu.edu.np';
Real-World Example: eSewa Transaction History
eSewa might create views for:
- User-Specific:
UserTransactions(shows only a user’s transactions). - Admin-Only:
FraudulentTransactions(flags suspicious activity). - Analytics:
MonthlyRevenue(aggregates transactions by month).
Advantages:
- Security: Hide
password_hashfrom user views. - Performance: Pre-compute complex joins (e.g.,
CustomerOrders). - Abstraction: Change base tables without breaking views.
Disadvantages:
- No DML: Cannot
INSERT,UPDATE, orDELETEdirectly on most views. - Maintenance: Views depend on base tables—dropping a table breaks dependent views.
5. Schema Evolution: Modifying the Database
Databases change over time. Use these commands to evolve schemas:
| Command | Purpose | Example |
|---|---|---|
ALTER TABLE |
Add/drop columns, rename tables, or modify constraints. | ALTER TABLE Student ADD COLUMN gpa DECIMAL(3,2); |
DROP TABLE |
Delete a table (use with caution!). | DROP TABLE OldEnrollment; |
RENAME TABLE |
Rename a table. | RENAME TABLE Enrollment TO StudentCourses; |
ADD CONSTRAINT |
Add constraints after table creation. | ALTER TABLE Account ADD CONSTRAINT chk_balance CHECK (balance >= 0); |
Worked Example: Adding a Column to Ncell’s Customer Table
Scenario: Ncell wants to track customer loyalty points. SQL:
ALTER TABLE Customer
ADD COLUMN loyalty_points INT DEFAULT 0;
-- Update existing customers (e.g., give 100 points to all)
UPDATE Customer SET loyalty_points = 100 WHERE loyalty_points = 0;
Challenges:
- Backward Compatibility: Old applications may not recognize
loyalty_points. - Data Migration: Existing data may need updates (e.g., setting defaults).
- Downtime: Large tables may require maintenance windows.
6. Normalization vs. Denormalization: Trade-offs
| Aspect | Normalization | Denormalization |
|---|---|---|
| Goal | Reduce redundancy, improve integrity. | Improve read performance, simplify queries. |
| Redundancy | Minimized (e.g., Student data stored once). |
Increased (e.g., duplicate Customer data in Orders). |
| Storage | Higher (due to joins). | Lower (fewer tables). |
| Query Performance | Slower (requires joins). | Faster (pre-joined data). |
| Update Overhead | Lower (data updated in one place). | Higher (updates must propagate to duplicates). |
| Use Case | OLTP (eSewa transactions, NEPSE trades). | OLAP (analytics, reporting). |
When to Denormalize?
- Read-Heavy Systems: e.g., Daraz’s product catalog (denormalize
Product+Categoryinto one table). - Reporting: e.g., NTC’s monthly traffic reports (pre-aggregate data).
- Legacy Systems: Simplify migration from flat files to relational DBs.
Example: Daraz Product Catalog Normalized:
Product (product_id, name, price)
Category (category_id, name)
ProductCategory (product_id, category_id)
Denormalized (for faster searches):
Product (
product_id,
name,
price,
category_name, -- Duplicate data
category_id
)
7. Database Schema Design Best Practices
- Start with ER Diagrams: Model real-world entities and relationships before writing SQL.
- Normalize First: Aim for 3NF (Third Normal Form) to minimize redundancy.
- Document Constraints: Clearly define
NOT NULL,UNIQUE, andCHECKrules. - Plan for Growth: Use
VARCHAR(255)instead ofCHAR(255)for variable-length fields. - Use Views for Security: Restrict access to sensitive data (e.g.,
AdminViewvs.UserView). - Test Schema Changes: Use
ALTER TABLEin a staging environment first. - Backup Before Modifications: Schema changes can break applications.
In the Real World
eSewa’s Payment System
- Schema Architecture: Uses a three-schema model where:
- External Schema: Users see only their transaction history (
UserTransactionsview). - Conceptual Schema: ER model with
User,Transaction,Merchant, andWalletentities. - Internal Schema: Sharded tables by region (Kathmandu, Pokhara, etc.) for performance.
- External Schema: Users see only their transaction history (
- Key Idea: Views hide sensitive data (e.g.,
Walletbalances) from merchants.
- Schema Architecture: Uses a three-schema model where:
NEPSE’s Stock Trading Database
- ER-to-Relational Mapping: Converts the M:N relationship between
TraderandStockinto a junction tableTransactionwith:- PK:
(trader_id, stock_id, transaction_id) - FKs:
trader_id→Trader,stock_id→Stock
- PK:
- Real-World Impact: Ensures no duplicate trades and maintains audit trails.
- ER-to-Relational Mapping: Converts the M:N relationship between
Daraz’s Order Fulfillment
- Schema Evolution: When Daraz added "same-day delivery," they:
- Added a
delivery_optioncolumn toOrder:ALTER TABLE Order ADD COLUMN delivery_option VARCHAR(20) DEFAULT 'standard'; - Created a view for same-day orders:
CREATE VIEW SameDayOrders AS SELECT * FROM Order WHERE delivery_option = 'same_day';
- Added a
- Challenge: Old orders had
NULLindelivery_option—they usedCOALESCEto handle this:SELECT * FROM Order WHERE COALESCE(delivery_option, 'standard') = 'same_day';
- Schema Evolution: When Daraz added "same-day delivery," they:
Ncell’s Customer Database
- Denormalization: For billing reports, Ncell denormalizes
CustomerandPlaninto aBillingSummarytable:CREATE TABLE BillingSummary ( customer_id INT, plan_name VARCHAR(50), monthly_charge DECIMAL(10,2), data_limit MB, FOREIGN KEY (customer_id) REFERENCES Customer(customer_id) ); - Why? Simplifies monthly billing queries (no joins needed).
- Denormalization: For billing reports, Ncell denormalizes
Exam Tip
What Examiners Look For
Three-Schema Architecture:
- Must include: External, conceptual, and internal schemas with one example each (e.g., TU’s student database).
- Common Mistake: Forgetting to explain how changes in one layer affect others (e.g., adding a column to the internal schema may require updating external views).
ER-to-Relational Mapping:
- Show your work: Start with an ER diagram, then write the SQL schema step-by-step.
- Key Points to Cover:
- How 1:1, 1:M, and M:N relationships map to tables/FKs.
- Handling weak entities and multivalued attributes.
- Example Trace: For the
Universitydatabase, explain whyEnrollmentneeds a composite PK.
SQL Schema Questions:
- Syntax: Use proper
CREATE TABLEwith constraints (e.g.,FOREIGN KEY,CHECK). - Realistic Data: Include
NOT NULL,UNIQUE, andDEFAULTwhere appropriate (e.g.,email UNIQUE NOT NULL). - Common Pitfall: Forgetting to reference the PK in
FOREIGN KEYclauses.
- Syntax: Use proper
Views:
- Define: "A virtual table based on a SQL query."
- Use Case: Give an example like
ActiveStudentsorFraudulentTransactions. - Limitations: Mention that views cannot modify data (except in rare cases with
INSTEAD OFtriggers).
Schema Evolution:
- Commands: Know
ALTER TABLE ADD/DROP COLUMN,RENAME TABLE, andDROP TABLE. - Backward Compatibility: Discuss how to handle existing data (e.g.,
DEFAULTvalues,UPDATEstatements).
- Commands: Know
Normalization vs. Denormalization:
- Compare: Use a table (as above) and give one pro/con for each.
- Apply to Nepal: e.g., "NEPSE uses normalization for trades but denormalizes for daily reports."
How to Score Full Marks
- Diagrams: Draw an ER diagram for any database design question (even if not asked).
- SQL Code: Write complete
CREATE TABLEstatements with all constraints. - Real-World Links: Tie examples to Nepali companies (e.g., "Like Daraz’s order system...").
- Step-by-Step: For mapping ER to relational, show each transformation (e.g., "M:N → junction table").
- Exam Language:
- Use terms like "insulation", "abstraction", "data independence", and "referential integrity".
- For views: "dynamic result set", "logical table", "does not store data".
In the real world
- eSewa’s Payment System: Uses the three-schema architecture to separate user views (external schema) from the core transaction database (conceptual schema), allowing new features (e.g., QR payments) without breaking existing apps.
- NEPSE’s Stock Trading Platform: Employs ER-to-relational mapping to convert trader-stock relationships into normalized tables (e.g.,
Traders,Stocks,Transactions), ensuring data integrity with foreign keys. - Daraz’s Order Management: Uses denormalization in transaction logs (e.g., storing
order_id,customer_name,product_detailsin one table) to speed up read-heavy operations during Black Friday sales.
Based on the TU BBA syllabus for Database Management System (IT232), unit 5.
Discussion
Loading…