Database Management Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to Database Systems & Relational Model
Module 2
Structured Query Language (SQL)
Module 3
Database Design Using the ER Model
Module 4
Normalization and Database Design Process
Module 5
Security, Transactions, NoSQL & SQL Lab
Read Module Notes Online
Module I: Introduction to Database Systems & Relational Model
Chapter 1: Database Systems, Architecture, and View of Data
1.1 Database Systems and the Purpose of a DBMS
A database is an organized, persistent, and self-describing collection of logically related data designed to model some real-world enterprise—such as university enrollments, banking ledgers, hospital patient records, or railway reservations. A Database Management System (DBMS) is a general-purpose software suite that enables users and application programs to define, construct, manipulate, share, and protect databases across concurrent workloads. Together, the stored database, the DBMS engine, associated application programs, and operational governance procedures constitute a complete Database System.
Before the adoption of modern DBMS platforms, organizations stored enterprise records in isolated file-processing systems managed directly through operating-system file APIs. Each department maintained its own flat files and custom procedural programs written in COBOL, C, or Pascal. While simple for isolated single-user tasks, file-processing architectures suffered from seven severe structural deficiencies that directly motivated the invention of the DBMS:
- Data Redundancy and Inconsistency: Storing student addresses separately in the registrar file, library file, and hostel file wastes disk capacity and causes contradictory updates when one file is modified while others remain stale.
- Difficulty in Accessing Data: Generating an ad-hoc report—such as listing all students enrolled in a specific course who owe library fines—required writing, compiling, and testing a brand-new application program rather than issuing a declarative query.
- Data Isolation: Because data was scattered across incompatible file formats (fixed-width ASCII text, binary records, indexed sequential files), combining information across subsystems was slow and error-prone.
- Integrity Problems: Business constraints (for example, account balances must remain non-negative or semester credits must not exceed 28) were buried inside procedural application code, making them difficult to enforce uniformly when new programs were added.
- Atomicity Problems: In a funds transfer debiting Account A and crediting Account B, a power failure between the two file writes left the database in a corrupted, partially updated state.
- Concurrent-Access Anomalies: When two clerks simultaneously withdrew from the same bank account using uncoordinated file reads and writes, lost updates occurred.
- Security Problems: Operating-system file permissions are coarse-grained; restricting a payroll clerk to view employee names without seeing executive salaries required custom application filtering.
A DBMS eliminates these drawbacks by centralizing metadata in a system catalog, enforcing declarative integrity rules, coordinating concurrent transactions through locking and logging, and providing a high-level declarative query interface.
| Comparison Dimension | Traditional File-Processing System | Database Management System (DBMS) |
|---|---|---|
| Data Redundancy | High; duplicated across departmental files leading to update inconsistencies. | Controlled; normalized schemas eliminate unnecessary duplication. |
| Data Independence | Absent; changing file record layout breaks every application program. | High; physical and logical data independence shield applications. |
| Concurrency Control | Minimal OS file locks; concurrent writes risk lost updates. | Full ACID transactions, row-level locking, and MVCC isolation. |
| Crash Recovery | Manual restoration from periodic file backups; partial writes corrupt files. | Automated Write-Ahead Logging (WAL) and checkpoint recovery. |
| Security & Views | Coarse OS-level read/write permissions on entire files. | Fine-grained RBAC, SQL GRANT/REVOKE, and column/row views. |
1.2 View of Data: Abstraction, Instances, Schemas, and Data Independence
A primary goal of a DBMS is to provide users with an abstract view of data, hiding low-level storage details such as disk blocks, cylinder alignments, byte offsets, and B+ tree pointers. This abstraction is structured into the three-level ANSI/SPARC architecture:
- Physical Level (Internal Level): The lowest level of abstraction, describing how data is physically stored on secondary storage. It defines file organizations (heap, sequential, hash), page/block sizes, compression, encryption, and index structures.
- Logical Level (Conceptual Level): The middle level describing what data is stored in the database and what relationships exist among those data items. It defines tables, columns, data types, primary/foreign keys, and integrity constraints without specifying disk layout.
- View Level (External Level): The highest level of abstraction, exposing customized subsets of the logical schema to specific user groups or applications. A student portal view hides faculty salaries and disciplinary logs while displaying course grades.
Two fundamental concepts govern how database structure evolves over time:
- Database Schema: The overall logical design and structural blueprint of the database (analogous to variable type declarations in a programming language). Schemas change infrequently. Physical schema describes storage layout; logical schema describes tables and constraints; subschemas describe external views.
- Database Instance (State): The actual collection of data stored in the database at a particular moment in time (analogous to the runtime values held by variables). Every insertion, deletion, or update transitions the database from one valid instance to another.
Because applications interact with higher abstraction levels, a DBMS provides Data Independence—the capacity to modify a schema at one level without rewriting schemas or applications at the next higher level:
- Physical Data Independence: The ability to modify the physical schema (adding a B+ tree index, migrating from HDD to NVMe SSD, changing hash buckets, or partitioning tables) without altering the logical schema or breaking application queries.
- Logical Data Independence: The ability to modify the logical schema (adding a new column, splitting a table into two normalized relations, or merging tables) without rewriting existing external views or application programs, provided the view definitions are updated to preserve the expected interface.
1.3 Database Languages
A DBMS provides specialized sub-languages (unified in SQL) to define schemas, manipulate records, control access, and manage transactions:
- Data Definition Language (DDL): Specifies the database schema, tables, domains, constraints, indexes, and views. DDL statements (such as
CREATE,ALTER,DROP,TRUNCATE) compile schema definitions into metadata stored in the Data Dictionary (system catalog). - Data Manipulation Language (DML): Enables users to retrieve, insert, update, and delete data. Procedural DML (like embedded cursors or PL/SQL) specifies what data is needed and how to retrieve it step by step; Declarative (non-procedural) DML (like SQL
SELECT) specifies only what data is needed, leaving access-path selection to the query optimizer. - Data Control Language (DCL): Governs authorization and privilege management through commands such as
GRANTandREVOKE. - Transaction Control Language (TCL): Manages logical units of work to ensure atomicity and durability using
COMMIT,ROLLBACK, andSAVEPOINT.
1.4 Database Design, Database Engine, and System Architecture
Database Design translates enterprise requirements into an efficient, anomaly-free schema through four systematic phases: (1) requirements collection and analysis, (2) conceptual design using an Entity-Relationship (ER) model, (3) logical design mapping ER diagrams to relational schemas and normalizing them, and (4) physical design choosing indexes, clustering, and storage parameters.
The internal Database Engine comprises two major subsystems that bridge user queries and disk storage:
- Storage Manager: Interfaces with the operating-system file system to store, retrieve, and update raw bytes. Its components include the Authorization and Integrity Manager (checks user privileges and integrity constraints), Transaction Manager (ensures ACID properties across crashes and concurrency), File Manager (allocates disk space and page structures), and Buffer Manager (caches disk pages in main memory and decides page replacement using LRU or Clock policies).
- Query Processor: Translates high-level SQL into low-level physical execution plans. Its components include the DDL Interpreter (records schema definitions in the data dictionary), DML Compiler and Optimizer (parses SQL, translates it into relational algebra trees, estimates I/O and CPU cost using table statistics, and selects the cheapest execution plan), and Query Evaluation Engine (executes the chosen plan against the storage manager).
Modern database systems are deployed under two primary client-server network architectures:
| Architectural Dimension | Two-Tier Architecture | Three-Tier Architecture |
|---|---|---|
| Topology | Client machine communicates directly with the Database Server over a network (ODBC/JDBC). | Client (browser/mobile) → Application Server (business logic) → Database Server. |
| Business Logic Placement | Embedded inside thick desktop client applications or stored procedures on the DB server. | Centralized on the middle-tier Application Server (REST APIs, microservices, JVM/.NET). |
| Scalability & Security | Limited; each client holds a direct DB connection; DB credentials/ports exposed to clients. | High; connection pooling on app server; DB isolated behind firewall; thin clients need zero drivers. |
| Typical Use Case | Internal LAN desktop tools, legacy ERP clients, administrative utilities. | Web applications, e-commerce portals, cloud SaaS, mobile banking backends. |
1.5 Database Users and Database Administrator (DBA)
Database systems serve four distinct user categories alongside a specialized administrative role:
- Naive (Parametric) Users: Unspecialized end-users who interact with the database exclusively through pre-written forms, mobile apps, or ATM menus (for example, bank tellers, railway ticket clerks, or students checking exam results).
- Application Programmers: Software engineers who write client or middleware programs in Java, Python, C#, or Node.js that embed SQL queries or invoke stored procedures.
- Sophisticated Users: Data analysts, scientists, and engineers who interact directly with the database by writing ad-hoc SQL queries or using BI/OLAP tools without writing application code.
- Specialized Users: Developers who build non-traditional database applications such as CAD systems, spatial/GIS engines, and multimedia repositories.
- Database Administrator (DBA): The central custodian with superuser privileges responsible for schema definition, storage structure and access-method definition, schema/physical-organization modification, granting authorization, routine maintenance (backups, index rebuilding, statistics gathering, performance tuning), and disaster recovery.
Chapter 2: Data Models and the Relational Model
2.1 Classification of Data Models
A data model is a collection of conceptual tools for describing data, data relationships, data semantics, and consistency constraints. Five classic and modern data models shape database engineering:
- Hierarchical Model: Organizes records as an upside-down tree (parent-child pointers) where each child record has at most one parent (1:N). Early systems such as IBM IMS offered fast top-down traversal but suffered from rigid navigation, difficulty representing many-to-many relationships without duplicate records, and lack of data independence.
- Network Model: Generalizes the hierarchical model into a directed graph (CODASYL DBTG standard) where a member record can have multiple owner records, supporting M:N relationships via pointer sets. While more flexible, programmers still had to navigate low-level currency pointers manually.
- Entity-Relationship (ER) Model: A high-level conceptual model representing real-world entities, their attributes, and relationships among them. Used primarily during conceptual database design before mapping to relational tables.
- Relational Model: Represents all data and relationships uniformly as mathematical relations (two-dimensional tables of rows and columns). Introduced by E.F. Codd, it decouples logical queries from physical pointers and dominates enterprise computing.
- Object-Oriented Data Model: Extends object-oriented programming concepts—encapsulation, classes, methods, object identity (OID), and inheritance—directly into persistent storage, suited for complex engineering, CAD, and multimedia objects.
| Data Model | Core Structure | Relationship Support | Primary Strength / Limitation |
|---|---|---|---|
| Hierarchical | Tree of parent-child records | 1:N only (without duplication) | Fast fixed hierarchy; rigid navigation, poor M:N support. |
| Network | Directed graph of record sets | 1:N and M:N via owner-member sets | Flexible links; complex pointer-based procedural queries. |
| Entity-Relationship | Entities, attributes, relationships | 1:1, 1:N, M:N, n-ary, EER | Intuitive conceptual design; not directly executed by RDBMS. |
| Relational | 2D tables (relations) & keys | Logical via Foreign Keys | Declarative SQL, strong theory; joins needed for complex objects. |
| Object-Oriented | Objects, classes, OIDs, methods | Direct object references & inheritance | Matches OOP languages; lacks universal declarative query standard. |
2.2 Structure of Relational Databases
In the relational model, a database consists of a finite set of named relations. Informally, a relation is a table; formally, it is a subset of the Cartesian product of a list of domains.
- Relation (Table): A named two-dimensional structure consisting of a heading (schema) and a body (set of tuples).
- Tuple (Row / Record): A single horizontal entry representing one entity instance or relationship instance. Because a relation is mathematically a set, duplicate tuples are forbidden in pure relational theory, and row order is immaterial.
- Attribute (Column / Field): A named property of a relation. Column order is semantically irrelevant when attributes are referenced by name.
- Domain: The set of permitted atomic values for an attribute (for example,
INTEGER,VARCHAR(50), or positive decimals). Every attribute value in a tuple must be atomic (indivisible) and drawn from its domain or be the special markerNULL(representing missing or inapplicable information). - Degree (Arity): The number of attributes in a relation schema.
- Cardinality: The number of tuples currently present in a relation instance.
Formally, given domains , a relation is a subset of the Cartesian product:
2.3 Database Schema, Schema Diagrams, Keys, and Integrity Rules
A relation schema specifies the relation name and its attribute list. A database schema is the collection of all relation schemas in the database. For example, a university database schema includes:
STUDENT(StudentID, Name, DeptName, TotalCredits), DEPARTMENT(DeptName, Building, Budget), COURSE(CourseCode, Title, DeptName, Credits), and ENROLLMENT(StudentID, CourseCode, Semester, Grade).
A schema diagram visually depicts each relation as a rectangular box listing its attributes, with primary key attributes underlined and directed arrows pointing from foreign key attributes in referencing relations to primary key attributes in referenced relations. Relational databases enforce three foundational integrity rules: Domain Integrity (every value belongs to its declared type/range), Entity Integrity (no primary key attribute may ever contain NULL), and Referential Integrity (every non-null foreign key value must match an existing primary key value in the referenced parent relation).
| Key Type | Formal Definition | Example (in STUDENT / ENROLLMENT) |
|---|---|---|
| Superkey | Any set of one or more attributes whose values uniquely identify a tuple in a relation. | {StudentID}, {StudentID, Name}, {Email, Phone} |
| Candidate Key | A minimal superkey—no proper subset of it is also a superkey. | {StudentID}, {Email} (assuming unique email) |
| Primary Key (PK) | The candidate key chosen by the database designer as the principal tuple identifier; cannot contain NULL. |
StudentID in STUDENT; (StudentID, CourseCode) in ENROLLMENT |
| Alternate Key | Any candidate key that was not selected as the primary key. | {Email} if StudentID is chosen as PK |
| Foreign Key (FK) | An attribute (or set) in relation R1 whose values must match the primary key of relation R2 (or be NULL), enforcing referential integrity. |
DeptName in STUDENT referencing DEPARTMENT(DeptName) |
Chapter 3: Relational Algebra and Query Trees
3.1 Fundamental Unary and Binary Operations
Relational Algebra is a procedural query language that takes one or two relations as input and produces a new relation as output. Because the output is always a relation, operations can be nested arbitrarily (closure property). The six fundamental operations—Selection, Projection, Union, Set Difference, Cartesian Product, and Rename—form a complete basis from which all other relational algebra operators can be derived.
- Selection (): A unary operation that selects tuples from relation satisfying predicate . Predicate uses comparison operators () and Boolean connectives (). Selection filters rows horizontally without changing columns.
- Projection (): A unary operation that extracts only the specified attributes from and automatically eliminates duplicate tuples. Projection filters columns vertically.
- Rename (): Assigns a new relation name and optional attribute names to the result of expression , essential for self-joins.
- Union (): Combines tuples appearing in , in , or in both, removing duplicates. Requires union compatibility: and must have the same arity and compatible attribute domains.
- Set Difference (): Returns tuples present in that are not in . Also requires union compatibility.
- Cartesian Product (): Combines every tuple of with every tuple of . If has tuples and has tuples, produces tuples.
3.2 Derived and Extended Operations: Joins, Division, and Aggregation
Additional operations simplify common multi-table queries without adding expressive power beyond the six fundamental operators, while extended operations add arithmetic and grouping:
- Set Intersection (): Returns tuples present in both and , defined as .
- Theta Join (): Combines Cartesian product and selection: . When uses only equality comparisons, it is called an Equijoin.
- Natural Join (): Automatically pairs tuples from and that have equal values on all common attributes, projecting out duplicate common columns.
- Outer Joins (): Preserve unmatched tuples from the left, right, or both relations by padding missing attributes with
NULL. - Division (): Used for "for all" universal-quantification queries (such as finding students who have completed all core courses). If has attributes and has attributes , then returns tuples over such that for every tuple , .
- Generalized Projection & Aggregation (): Groups tuples by attributes and computes aggregate functions (
sum,avg,count,min,max) over each group.
3.3 Worked Relational Algebra Examples
Consider a Banking Schema: BRANCH(BName, BCity, Assets), ACCOUNT(AccNo, BName, Balance), CUSTOMER(CID, CName, CCity), and DEPOSITOR(CID, AccNo).
- Find names of all customers having an account at the 'Kollam' branch with balance > 25,000:
- Find customers who have an account in 'Kollam' branch OR 'Kochi' branch, but NOT both:
Let and . The symmetric difference is . - Find the average balance per branch for branches whose average balance exceeds 50,000:
- Find the largest account balance using Theta-Join (without aggregate functions):
Compute all non-maximum balances via self-join , then subtract from all balances: .
3.4 Query Tree Optimization Using Relational Algebra Equivalence
When a user submits an SQL query, the DML compiler translates it into an initial relational algebra expression tree. Because Cartesian products followed by selections are prohibitively expensive on large tables, the query optimizer applies algebraic equivalence rules—such as pushing selections down beneath joins ( when references only 's attributes) and pushing projections down—to shrink intermediate relation sizes dramatically before physical execution.
| Equivalence Rule | Algebraic Identity | Optimization Benefit |
|---|---|---|
| Cascade of Selection | Allows individual predicates to be pushed independently below joins. | |
| Commutativity of Selection | Enables applying the most selective (smallest output) filter first. | |
| Cascade of Projection | (if ) | Eliminates redundant intermediate projections. |
| Associativity of Natural Join | Lets the optimizer join smaller relations first to minimize intermediate memory. |
3.5 Worked Relational Algebra Execution Trace on Sample Tables
To solidify how relational algebra operators transform actual table instances, consider two small relations: EMP(EID, EName, Dept, Salary) with tuples (1, 'Arun', 'CS', 55000), (2, 'Binu', 'CS', 42000), (3, 'Chitra', 'EC', 60000), (4, 'Deepa', 'ME', 48000), and DEPT(Dept, Location) with tuples ('CS', 'Block A'), ('EC', 'Block B'), ('CE', 'Block C').
- Selection + Projection: first filters rows 1 and 3, then projects
{('Arun', 55000), ('Chitra', 60000)}. - Natural Join: matches on common attribute
Dept, yielding 4 tuples (sinceMEhas no match inDEPT, row 4 is dropped;CEhas no match inEMP, so it is dropped). - Left Outer Join: retains row 4
(4, 'Deepa', 'ME', 48000, NULL)by paddingLocationwithNULL. - Right Outer Join: retains
('CE', 'Block C')withNULLvalues forEID,EName, andSalary. - Division Example: Suppose
SKILLS_REQ(Skill)={'SQL', 'Python'}andEMP_SKILL(EID, Skill)={(1, 'SQL'), (1, 'Python'), (2, 'SQL')}. Then returns{(1)}because only employee 1 possesses every required skill.
3.6 Tuple Relational Calculus and Domain Relational Calculus (Overview)
Alongside procedural relational algebra, Codd defined two declarative query formalisms that inspired SQL:
- Tuple Relational Calculus (TRC): Expresses queries as , meaning "the set of all tuples such that predicate is true." For example, CS employees earning above 50,000 are written . Existential () and universal () quantifiers bind tuple variables.
- Domain Relational Calculus (DRC): Uses domain variables ranging over individual attribute values rather than whole tuples: . Any safe TRC or DRC expression has an exact equivalent in relational algebra (Codd's Theorem).
3.7 Complete Relational Database Schema Case Study: University Portal
To synthesize schemas, keys, integrity constraints, and relational algebra in a single end-to-end example, consider a University Academic Portal consisting of five interrelated relations:
DEPARTMENT(DeptCode, DeptName, Building, Budget)— Primary Key:DeptCode; Alternate Key:DeptName.FACULTY(FacID, FacName, Designation, Salary, DeptCode [FK])— Foreign KeyDeptCodereferencesDEPARTMENT(DeptCode).COURSE(CourseCode, Title, Credits, DeptCode [FK])— Foreign KeyDeptCodereferencesDEPARTMENT(DeptCode).STUDENT(RegNo, SName, Email, AdmissionYear, DeptCode [FK])— Candidate Keys:{RegNo}and{Email}.REGISTRATION(RegNo [FK], CourseCode [FK], Semester, GradePoint)— Composite Primary Key:(RegNo, CourseCode, Semester).
Using this schema, complex administrative questions translate cleanly into relational algebra expressions:
- List all 4-credit courses offered by the 'BCA' department: .
- Find names of students who have never registered for any course: .
- Find faculty members earning more than every faculty member in 'EC': Let ; subtract faculty whose salary is less than or equal to some EC faculty member using a theta-join.
- Compute department-wise average faculty salary: .
3.8 Codd's Twelve Rules for Relational DBMS (Overview)
To prevent vendors from marketing legacy file or hierarchical systems as "relational," E.F. Codd formulated twelve evaluation rules (numbered 0 through 12) that a true RDBMS must satisfy:
- Rule 0 (Foundation Rule): A relational system must manage databases entirely through its relational capabilities.
- Rule 1 (Information Rule): All information (including metadata) is represented explicitly as values in tables.
- Rule 2 (Guaranteed Access): Every atomic value is logically accessible via table name, primary key value, and column name.
- Rule 3 (Systematic Treatment of Nulls): Missing or inapplicable values are represented uniformly as
NULL, distinct from zero or empty strings. - Rule 4 (Dynamic Online Catalog): The database description (data dictionary) is stored in relational tables queryable with the same language as user data.
- Rule 5 (Comprehensive Data Sublanguage): At least one relational language (such as SQL) must support DDL, DML, views, integrity, authorization, and transactions.
- Rules 6–12 (View Updating, High-Level Set Operations, Physical/Logical/Integrity/Distribution Independence, Non-Subversion): Ensure set-at-a-time manipulation, full data independence, declarative integrity, and protection against bypassing constraints via low-level APIs.
Module II: Structured Query Language (SQL)
Chapter 4: SQL Foundations, Classification, and Basic Query Operations
4.1 Overview and Classification of SQL
Structured Query Language (SQL) is the universal declarative language for relational database management systems, standardized jointly by ANSI and ISO. Unlike imperative programming languages where the developer specifies step-by-step loops and pointer traversals, SQL lets the user declare what result set is desired, while the DBMS query optimizer determines the optimal physical execution plan.
SQL statements are grouped into four functional sub-languages:
| Classification | Full Name | Primary Purpose | Core Commands |
|---|---|---|---|
| DDL | Data Definition Language | Define, alter, and remove schemas, tables, constraints, views, and indexes. | CREATE, ALTER, DROP, TRUNCATE, RENAME |
| DML | Data Manipulation Language | Query and modify data stored inside existing tables. | SELECT, INSERT, UPDATE, DELETE, MERGE |
| DCL | Data Control Language | Manage user access rights and security privileges on database objects. | GRANT, REVOKE |
| TCL | Transaction Control Language | Control transaction boundaries, atomicity, and rollback points. | COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION |
4.2 SQL Data Types, DDL Constraints, DCL, and TCL
Every relational table created via DDL specifies column names, standard SQL data types, and declarative integrity constraints enforced automatically on every write:
| SQL Data Type | Storage Semantics | Typical Usage |
|---|---|---|
INT / BIGINT |
Exact signed 32-bit or 64-bit integer. | Primary keys (EmpID), quantities, counts. |
DECIMAL(p, s) / NUMERIC(p, s) |
Exact fixed-point number with p total digits and s fractional digits. | Salaries, currency amounts, tax rates (avoids float rounding). |
CHAR(n) vs. VARCHAR(n) |
Fixed-length space-padded string vs. variable-length string up to n chars. | CHAR(2) for state codes; VARCHAR(100) for names/emails. |
DATE / TIMESTAMP |
Calendar date (YYYY-MM-DD) / date with time-of-day precision. | Birth dates, join dates, audit log timestamps. |
BOOLEAN |
Logical truth values TRUE, FALSE, or UNKNOWN. |
Active status flags, verification indicators. |
NOT NULL: Forbids missing values in the column.UNIQUE: Ensures all non-null values in the column (or column combination) are distinct.PRIMARY KEY: CombinesNOT NULLandUNIQUEto uniquely identify each row.FOREIGN KEY ... REFERENCES: Enforces referential integrity against a parent table's primary or unique key, optionally specifyingON DELETE CASCADE,ON DELETE SET NULL, orON UPDATE CASCADE.CHECK (condition): Enforces arbitrary row-level predicates (for example,CHECK (Salary > 0)).DEFAULT value: Supplies an automatic value when anINSERTomits that column.
CREATE TABLE DEPARTMENT (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL UNIQUE,
Building VARCHAR(30) DEFAULT 'Main Block'
);
CREATE TABLE EMPLOYEE (
EmpID INT PRIMARY KEY,
EmpName VARCHAR(80) NOT NULL,
Email VARCHAR(100) UNIQUE,
Salary DECIMAL(10, 2) CHECK (Salary >= 15000),
JoinDate DATE NOT NULL,
DeptID INT,
CONSTRAINT fk_emp_dept FOREIGN KEY (DeptID)
REFERENCES DEPARTMENT(DeptID) ON DELETE SET NULL
);
ALTER TABLE EMPLOYEE ADD COLUMN Phone VARCHAR(15);
-- DML & TCL Example
INSERT INTO DEPARTMENT VALUES (10, 'Computer Science', 'IT Block');
INSERT INTO EMPLOYEE (EmpID, EmpName, Email, Salary, JoinDate, DeptID)
VALUES (101, 'Ananya Nair', '[email protected]', 52000.00, '2024-07-01', 10);
SAVEPOINT sp_before_raise;
UPDATE EMPLOYEE SET Salary = Salary * 1.10 WHERE DeptID = 10;
-- Undo only the raise if needed: ROLLBACK TO sp_before_raise;
COMMIT;
-- DCL Example
GRANT SELECT, UPDATE (Salary) ON EMPLOYEE TO hr_manager;
REVOKE UPDATE ON EMPLOYEE FROM hr_manager;4.3 Basic Structure of SQL Queries and Additional Operations
The fundamental SQL query follows the SELECT-FROM-WHERE structure, corresponding closely to relational algebra projection, Cartesian product/join, and selection:
SELECTspecifies the target columns or computed expressions. UseDISTINCTto eliminate duplicate rows (SQL uses multiset/bag semantics by default, unlike pure relational algebra).FROMlists the source tables and join specifications.WHEREfilters individual rows before grouping using comparison operators,AND,OR,NOT,BETWEEN low AND high(inclusive range), andIN (list).- Renaming (
AS): Assigns readable aliases to columns or tables (essential for self-joins and computed expressions). - String Operations: Pattern matching via
LIKEuses%(matches zero or more characters) and_(matches exactly one character). Standard string functions includeUPPER(),LOWER(),SUBSTRING(),LENGTH(),TRIM(), and concatenation (||orCONCAT()). - Sorting (
ORDER BY): Sorts the final result set in ascending (ASC, default) or descending (DESC) order across one or more columns. - Conditional Expressions (
CASE&COALESCE):CASE WHEN cond THEN val1 ELSE val2 ENDimplements inline branching, whileCOALESCE(a, b, 0)returns the first non-null argument.
4.4 Set Operations and Null Values
SQL provides three set operations matching relational algebra, each requiring union-compatible SELECT lists (same column count and compatible types). By default, set operators eliminate duplicates; appending ALL preserves duplicates:
UNION/UNION ALL: Combines rows from both queries.INTERSECT/INTERSECT ALL: Returns rows appearing in both queries.EXCEPT(orMINUSin Oracle) /EXCEPT ALL: Returns rows in the first query not present in the second.
Null Values represent unknown, missing, or inapplicable data. SQL evaluates comparisons involving NULL using three-valued logic (TRUE, FALSE, UNKNOWN). Any arithmetic operation involving NULL yields NULL, and any comparison with = or <> against NULL yields UNKNOWN. Consequently, queries must test nulls using IS NULL or IS NOT NULL. In a WHERE clause, only rows evaluating to TRUE are retained; rows evaluating to UNKNOWN are discarded. Aggregate functions ignore NULL values, except COUNT(*) which counts all rows.
| P | Q | P AND Q | P OR Q | NOT P |
|---|---|---|---|---|
| TRUE | UNKNOWN | UNKNOWN | TRUE | FALSE |
| FALSE | UNKNOWN | FALSE | UNKNOWN | TRUE |
| UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN |
Chapter 5: Aggregation, Joins, and Nested Subqueries
5.1 Aggregate Functions, GROUP BY, and HAVING
Aggregate functions summarize multiple rows into a single scalar value: COUNT(*) (total rows), COUNT(col) (non-null values), SUM(col), AVG(col), MIN(col), and MAX(col). When combined with GROUP BY, rows sharing identical values in the grouping columns are partitioned into groups, and aggregates are computed once per group.
A critical distinction exists between WHERE and HAVING: WHERE filters individual rows before grouping occurs, whereas HAVING filters entire groups after aggregation. Every non-aggregated column appearing in the SELECT list must appear in the GROUP BY clause. Logical SQL execution order is: FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY.
5.2 SQL Joins
Joins combine rows from two or more tables based on related columns:
| Join Type | Behavior on Unmatched Rows | Primary Use Case |
|---|---|---|
| INNER JOIN | Discards unmatched rows from both tables. | Standard parent-child matching (orders with valid customers). |
| NATURAL JOIN | Joins on all identically named columns; drops duplicate columns. | Quick ad-hoc joins when foreign key names match primary keys. |
| LEFT OUTER JOIN | Keeps all left rows; pads unmatched right columns with NULL. |
Finding entities with zero children (departments with 0 staff). |
| RIGHT OUTER JOIN | Keeps all right rows; pads unmatched left columns with NULL. |
Symmetric counterpart to Left Outer Join. |
| FULL OUTER JOIN | Keeps all rows from both tables, padding both sides with NULL. |
Reconciling two datasets (budgeted vs. actual expenses). |
| CROSS JOIN / SELF JOIN | Cartesian product / joining a table to itself via aliases. | Generating combinations; hierarchical manager-employee queries. |
5.3 Nested Subqueries and CTEs
A subquery is a SELECT statement nested inside another query's SELECT, FROM, WHERE, or HAVING clause:
- Set Membership (
IN/NOT IN): Tests whether a scalar or tuple belongs to the subquery's result set. Warning: if a subquery returns anyNULL,NOT INevaluates toUNKNOWNfor all rows and returns zero results—preferNOT EXISTSwhen nulls are possible. - Set Comparison (
ANY/SOMEandALL): Compares a value against some or every value returned by a subquery (for example,Salary > ALL (SELECT Salary FROM ...)). - Existence Testing (
EXISTS/NOT EXISTS): ReturnsTRUEif the subquery produces at least one row. Widely used with correlated subqueries, where the inner query references a column from the outer query and executes logically once per outer row. - Common Table Expressions (
WITH): Named temporary result sets scoped to a single query, improving readability and enabling recursive hierarchical queries.
-- 1. Department-wise average salary for departments with >= 3 staff and avg > 40000
SELECT d.DeptName, COUNT(e.EmpID) AS StaffCount, AVG(e.Salary) AS AvgSalary
FROM DEPARTMENT d
LEFT JOIN EMPLOYEE e ON d.DeptID = e.DeptID
WHERE e.JoinDate >= '2020-01-01'
GROUP BY d.DeptName
HAVING COUNT(e.EmpID) >= 3 AND AVG(e.Salary) > 40000
ORDER BY AvgSalary DESC;
-- 2. Correlated subquery: employees earning above their own department's average
SELECT e1.EmpName, e1.Salary, e1.DeptID
FROM EMPLOYEE e1
WHERE e1.Salary > (
SELECT AVG(e2.Salary)
FROM EMPLOYEE e2
WHERE e2.DeptID = e1.DeptID
);
-- 3. CTE (WITH clause) and Self-Join example
WITH DeptTotals AS (
SELECT DeptID, SUM(Salary) AS TotalPayroll
FROM EMPLOYEE
GROUP BY DeptID
)
SELECT d.DeptName, COALESCE(dt.TotalPayroll, 0) AS Payroll
FROM DEPARTMENT d
LEFT JOIN DeptTotals dt ON d.DeptID = dt.DeptID;Chapter 6: Views, Triggers, Cursors, Routines, and Embedded SQL
6.1 Views and Materialized Views
A view is a virtual relation defined by a stored SELECT query using CREATE VIEW view_name AS SELECT .... Unlike base tables, a standard view stores no physical tuples; whenever queried, the DBMS merges the view definition with the user's query (view expansion). Views provide three major benefits: (1) logical data independence when base tables are refactored, (2) security by hiding sensitive columns or rows, and (3) query simplification by encapsulating complex joins.
A view is updatable (permitting INSERT, UPDATE, DELETE) only if it is derived from a single base table without DISTINCT, GROUP BY, HAVING, aggregate functions, or set operators, and includes all NOT NULL columns without defaults. Complex multi-table views are read-only unless backed by INSTEAD OF triggers. Dropping a view via DROP VIEW view_name removes only the definition, leaving base table data intact. Materialized views physically cache query results on disk for fast analytical reads and are refreshed periodically.
6.2 Triggers
A trigger is an Event-Condition-Action (ECA) stored program automatically executed by the DBMS in response to a data modification event (INSERT, UPDATE, or DELETE) on a specified table:
- Timing:
BEFOREtriggers execute prior to the modification (ideal for validating or normalizing incoming values);AFTERtriggers execute after the modification (ideal for audit logging or cascading summary updates). - Granularity:
FOR EACH ROW(row-level) fires once per affected tuple with access toOLDandNEWrow values;FOR EACH STATEMENTfires once per SQL statement.
6.3 Cursors, Functions, and Stored Procedures
Because SQL queries return sets of rows whereas procedural host languages process one record at a time, a cursor acts as a server-side pointer over a query result set. Explicit cursor lifecycle follows four steps: DECLARE (binds cursor name to a SELECT), OPEN (executes query and positions before first row), FETCH (retrieves current row into variables and advances pointer), and CLOSE (releases buffer resources).
| Feature | Stored Procedure | User-Defined Function (UDF) |
|---|---|---|
| Invocation | Invoked explicitly via CALL ProcName(...). |
Invoked inline inside SQL expressions (SELECT Fn(col)). |
| Parameters & Return | Supports IN, OUT, INOUT parameters; return optional. |
Supports IN parameters; must return a scalar or table value. |
| Side Effects & TCL | May execute DML, DDL, and COMMIT/ROLLBACK. |
Pure computation; generally forbids side effects and TCL. |
CREATE VIEW CS_FACULTY AS
SELECT EmpID, EmpName, Email FROM EMPLOYEE WHERE DeptID = 10;
CREATE TABLE SALARY_AUDIT (
EmpID INT, OldSal DECIMAL(10,2), NewSal DECIMAL(10,2), ChangedAt TIMESTAMP
);
DELIMITER //
CREATE TRIGGER trg_salary_audit
AFTER UPDATE ON EMPLOYEE
FOR EACH ROW
BEGIN
IF OLD.Salary <> NEW.Salary THEN
INSERT INTO SALARY_AUDIT VALUES (NEW.EmpID, OLD.Salary, NEW.Salary, NOW());
END IF;
END //
CREATE FUNCTION ComputeTax(p_sal DECIMAL(10,2)) RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
IF p_sal <= 50000 THEN RETURN p_sal * 0.05;
ELSE RETURN p_sal * 0.15;
END IF;
END //
CREATE PROCEDURE GiveRaise(IN p_dept INT, IN p_pct DECIMAL(5,2))
BEGIN
DECLARE v_done INT DEFAULT 0;
DECLARE v_id INT;
DECLARE v_sal DECIMAL(10,2);
DECLARE emp_cur CURSOR FOR SELECT EmpID, Salary FROM EMPLOYEE WHERE DeptID = p_dept;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = 1;
OPEN emp_cur;
read_loop: LOOP
FETCH emp_cur INTO v_id, v_sal;
IF v_done = 1 THEN LEAVE read_loop; END IF;
UPDATE EMPLOYEE SET Salary = v_sal * (1 + p_pct / 100.0) WHERE EmpID = v_id;
END LOOP;
CLOSE emp_cur;
END //
DELIMITER ;6.4 Embedded SQL and Dynamic SQL
Embedded SQL allows SQL statements to be written directly inside general-purpose host languages such as C, C++, or COBOL. A vendor precompiler translates EXEC SQL ... blocks into native library calls before host compilation. Host variables prefixed by a colon (for example, :emp_id) exchange data between C variables and SQL columns, while the SQLCA (SQL Communications Area, including SQLCODE and SQLSTATE) reports execution status such as 0 (success) or 100 (end of data). While static embedded SQL optimizes plans at compile time, Dynamic SQL (PREPARE and EXECUTE) constructs queries at runtime, and modern applications predominantly use driver APIs like ODBC and JDBC.
EXEC SQL BEGIN DECLARE SECTION;
int v_emp_id;
char v_name[80];
double v_salary;
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE SQLCA;
void print_cs_staff() {
EXEC SQL DECLARE c1 CURSOR FOR
SELECT EmpID, EmpName, Salary FROM EMPLOYEE WHERE DeptID = 10;
EXEC SQL OPEN c1;
while (1) {
EXEC SQL FETCH c1 INTO :v_emp_id, :v_name, :v_salary;
if (SQLCODE == 100) break; /* No more rows */
printf("%d | %s | %.2f\n", v_emp_id, v_name, v_salary);
}
EXEC SQL CLOSE c1;
}6.5 Comprehensive Multi-Concept SQL Query Cookbook
To bridge theoretical SQL syntax with practical enterprise reporting, the following consolidated listing demonstrates string functions, date arithmetic, multi-table joins, outer-join anti-patterns (finding unmatched records), window ranking, and multi-condition CASE aggregation on a University Academic Schema.
-- 1. String manipulation & formatting
SELECT EmpID,
UPPER(EmpName) AS UpperName,
SUBSTRING(Email, 1, POSITION('@' IN Email) - 1) AS Username,
CONCAT(EmpName, ' (Dept ', DeptID, ')') AS DisplayLabel
FROM EMPLOYEE
WHERE EmpName LIKE '_n%'; -- Second character is 'n'
-- 2. Anti-Join: Departments with ZERO employees (using LEFT JOIN + IS NULL)
SELECT d.DeptID, d.DeptName
FROM DEPARTMENT d
LEFT JOIN EMPLOYEE e ON d.DeptID = e.DeptID
WHERE e.EmpID IS NULL;
-- 3. Conditional Aggregation with CASE WHEN
SELECT d.DeptName,
COUNT(CASE WHEN e.Salary >= 60000 THEN 1 END) AS SeniorCount,
COUNT(CASE WHEN e.Salary < 60000 THEN 1 END) AS JuniorCount,
COALESCE(SUM(e.Salary), 0) AS TotalBudgetUsed
FROM DEPARTMENT d
LEFT JOIN EMPLOYEE e ON d.DeptID = e.DeptID
GROUP BY d.DeptName
ORDER BY TotalBudgetUsed DESC;
-- 4. Set Operations: Employees in Dept 10 OR earning > 70000 (without duplicates)
SELECT EmpID, EmpName FROM EMPLOYEE WHERE DeptID = 10
UNION
SELECT EmpID, EmpName FROM EMPLOYEE WHERE Salary > 70000;
-- 5. Scalar & EXISTS Subquery: Departments having at least one high earner
SELECT d.DeptName
FROM DEPARTMENT d
WHERE EXISTS (
SELECT 1 FROM EMPLOYEE e
WHERE e.DeptID = d.DeptID AND e.Salary > 65000
);6.6 Common SQL Pitfalls and Best Practices
Even experienced developers encounter subtle logical bugs in SQL due to bag semantics, three-valued logic, and grouping rules. Five essential best practices prevent production defects:
- Avoid
NOT INwith Nullable Subqueries: If a subquery returns even a singleNULL,x NOT IN (subquery)evaluates toUNKNOWNfor every row and returns an empty set. Always filterWHERE col IS NOT NULLinside the subquery or useNOT EXISTS. - Filter Early in
WHERERather ThanHAVING: Place row-level conditions (such asDeptID = 10) inWHEREso the engine discards irrelevant rows before sorting and grouping; reserveHAVINGstrictly for aggregate predicates (such asCOUNT(*) > 5). - Be Explicit with Join Conditions: Prefer explicit
INNER JOIN ... ONsyntax over comma-separated tables inFROMto avoid accidental Cartesian products when a join predicate is forgotten, and avoidNATURAL JOINin production code where adding a same-named column (likeUpdatedAt) silently alters join semantics. - Use
UNION ALLWhen Duplicates Are Impossible:UNIONperforms an expensive sort or hash deduplication across all rows; if two branches are mutually exclusive,UNION ALLavoids unnecessary overhead. - Index Foreign Keys and Join Columns: While
PRIMARY KEYconstraints automatically create an index in most RDBMS engines,FOREIGN KEYcolumns often do not; indexing foreign keys accelerates both parent-child joins and cascading deletes.
6.7 Window Functions and Recursive Queries in Modern SQL
Modern ANSI SQL extends standard GROUP BY aggregation with Window (Analytic) Functions using the OVER (PARTITION BY ... ORDER BY ...) clause. Unlike GROUP BY, which collapses multiple rows into a single output row per group, a window function computes an aggregate or ranking value across a sliding frame of related rows while preserving every individual input row.
- Ranking Functions:
ROW_NUMBER()assigns a unique sequential integer (1, 2, 3, ...);RANK()assigns identical ranks to ties with gaps (1, 1, 3);DENSE_RANK()assigns identical ranks without gaps (1, 1, 2). - Value Functions:
LAG(col, 1)andLEAD(col, 1)access values from preceding or following rows within the same partition—ideal for computing month-over-month growth without self-joins. - Running Totals:
SUM(Salary) OVER (PARTITION BY DeptID ORDER BY JoinDate)computes cumulative department payroll ordered chronologically.
-- 1. Rank employees within each department by salary (Top-N per group)
SELECT DeptID, EmpName, Salary,
DENSE_RANK() OVER (PARTITION BY DeptID ORDER BY Salary DESC) AS DeptRank
FROM EMPLOYEE;
-- 2. Recursive CTE: Traverse an organizational manager-subordinate hierarchy
WITH RECURSIVE OrgHierarchy AS (
SELECT EmpID, EmpName, ManagerID, 1 AS Level
FROM STAFF WHERE ManagerID IS NULL
UNION ALL
SELECT s.EmpID, s.EmpName, s.ManagerID, oh.Level + 1
FROM STAFF s
JOIN OrgHierarchy oh ON s.ManagerID = oh.EmpID
)
SELECT EmpID, EmpName, Level FROM OrgHierarchy ORDER BY Level, EmpName;
-- 3. TRUNCATE vs DELETE & DROP
-- DELETE FROM TEMP_LOG WHERE CreatedAt < '2025-01-01'; -- Row-by-row logged, rollbackable
-- TRUNCATE TABLE TEMP_LOG; -- Fast page deallocation, keeps schema
-- DROP TABLE TEMP_LOG; -- Removes data AND schema definition6.8 Comparing DDL Truncation, Deletion, and Dropping
Understanding the operational differences among DELETE, TRUNCATE, and DROP is vital for both SQL exams and production database administration:
| Operation | Language | Row Filtering | Schema & Rollback Behavior |
|---|---|---|---|
DELETE |
DML | Supports WHERE clause for selective deletion. |
Fires row triggers; logs each deleted row; fully rollbackable before COMMIT. |
TRUNCATE |
DDL | Removes all rows unconditionally. | Deallocates data pages rapidly; preserves empty table structure; resets auto-increment. |
DROP |
DDL | Destroys entire table unconditionally. | Removes rows, indexes, triggers, constraints, and catalog entry permanently. |
6.9 SQL Indexes, Sequences, and Integrity Assertions
Beyond basic tables and views, SQL provides auxiliary schema objects that accelerate retrieval and automate key generation:
- Indexes (
CREATE INDEX): Although not part of the pure ANSI relational model, every commercial RDBMS supportsCREATE INDEX idx_emp_dept ON EMPLOYEE(DeptID)andCREATE UNIQUE INDEXto build B+ tree lookup structures over non-primary-key columns. Composite indexes (for example,(DeptID, Salary)) follow the leftmost prefix rule, accelerating queries filtering onDeptIDalone or bothDeptIDandSalary. - Sequences and Auto-Increment Keys:
CREATE SEQUENCE seq_emp START WITH 1000 INCREMENT BY 1(orAUTO_INCREMENT/SERIAL/IDENTITY) generates monotonic surrogate primary keys safely under high concurrency without locking entire tables. - Assertions and Domains: Standard SQL defines
CREATE ASSERTIONfor database-wide multi-table constraints (such as ensuring total department salaries never exceed department budget) andCREATE DOMAINfor reusable constrained scalar types.
6.10 Worked SQL Query Trace: University Course Enrollment
Consider three tables: STUDENT(SID, SName, Sem, GPA), COURSE(CID, CTitle, Credits), and ENROLL(SID, CID, Grade). The following queries demonstrate how nested subqueries, set division in SQL, and materialized views solve complex university reporting requirements:
-- 1. Find students enrolled in ALL 4-credit courses (Double NOT EXISTS = Relational Division)
SELECT s.SID, s.SName
FROM STUDENT s
WHERE NOT EXISTS (
SELECT c.CID FROM COURSE c WHERE c.Credits = 4
AND NOT EXISTS (
SELECT 1 FROM ENROLL e WHERE e.SID = s.SID AND e.CID = c.CID
)
);
-- 2. Updateable View with WITH CHECK OPTION (prevents inserting Sem <> 3)
CREATE VIEW SEM3_STUDENTS AS
SELECT SID, SName, Sem, GPA
FROM STUDENT
WHERE Sem = 3
WITH CHECK OPTION;
-- 3. Scalar Subquery in SELECT List: Show each student's GPA vs overall average
SELECT SName, GPA,
ROUND(GPA - (SELECT AVG(GPA) FROM STUDENT), 2) AS DiffFromAvg
FROM STUDENT
ORDER BY GPA DESC;Module III: Database Design Using the ER Model
Chapter 7: The Entity-Relationship (ER) Model and Attribute Taxonomy
7.1 Overview of the Database Design Process
Designing a large enterprise database requires systematic conceptual modeling before writing a single CREATE TABLE statement. The database design lifecycle progresses through six structured phases:
- Requirements Collection and Analysis: Interviewing stakeholders, examining existing paper forms, reports, and workflows, and documenting both data requirements and functional operations (queries and updates).
- Conceptual Design: Building a high-level, DBMS-independent conceptual schema using the Entity-Relationship (ER) Model. This diagram serves as a shared communication contract between business analysts and database architects.
- Choice of a DBMS: Evaluating relational, object-relational, or NoSQL engines based on consistency, scalability, licensing, and query workload.
- Logical Design (Data Model Mapping): Transforming the conceptual ER diagram into an implementation-ready relational schema (relations, primary keys, foreign keys) and applying normalization.
- Physical Design: Selecting file organizations, B+ tree or hash indexes, partitioning, and storage parameters to meet throughput and latency targets.
- Implementation and Tuning: Executing DDL scripts, loading initial data, enforcing security policies, and continuously monitoring query plans.
7.2 Core Concepts: Entities, Entity Sets, and Relationships
Introduced by Peter Chen, the Entity-Relationship (ER) model views the real world as a collection of basic objects called entities and associations among them:
- Entity: A distinguishable real-world object or concept—either physical (a specific student, a hospital bed, a locomotive) or abstract (a university course, a bank loan, a railway booking).
- Entity Set: A collection of entities of the same type sharing identical properties (for example, the set of all
STUDENTentities). Drawn as a rectangle in Chen ER notation. - Relationship: An association among two or more specific entities (for example, student Asha is enrolled in course Database Management).
- Relationship Set: A mathematical relation among entity sets. Drawn as a diamond connected by lines to participating entity sets. A relationship set can also carry descriptive attributes (for example,
EnrollmentDateorGradeon theENROLLSrelationship). - Degree of a Relationship Set: The number of participating entity sets. Most relationships are binary (degree 2), while ternary (degree 3, e.g.,
SUPPLIERsuppliesPARTtoPROJECT) and higher n-ary relationships model simultaneous multi-entity facts. - Role: The function an entity plays in a relationship. Role labels are mandatory in recursive (self-referencing) relationships—for example, an
EMPLOYEEentity set participating twice inREPORTS_TOwith roles Subordinate and Manager.
7.3 Types of Attributes and Latest Representations
Each entity is described by a set of attributes, each drawing values from a domain. Attributes fall into six structural categories across classic Chen and modern UML / Crow's Foot representations:
| Attribute Type | Definition & Semantics | Classic Chen / Modern ER Notation | Example |
|---|---|---|---|
| Simple (Atomic) | Indivisible into smaller meaningful sub-parts. | Single solid oval (or plain line in Crow's Foot / UML attribute box). | RollNo, Gender, Credits |
| Composite | Can be subdivided into smaller independent component attributes with distinct meanings. | Oval branching to component ovals; indented hierarchy in modern Crow's Foot / UML tools. | Name(First, Middle, Last); Address(Street, City, PIN) |
| Single-Valued | Holds at most one value for a given entity instance. | Standard single oval (default in modern CASE tools). | DateOfBirth, AadhaarNo |
| Multivalued | May hold zero, one, or multiple values simultaneously for a single entity. | Double-bordered oval in Chen; {Attr} or Attr[1..*] in UML / modern ER. |
PhoneNumbers, DegreesEarned |
| Derived | Value is computed dynamically from other stored attributes or current date rather than stored physically. | Dashed-border oval in Chen; /Attr prefix in UML / modern ER representations. |
Age (derived from DOB); TotalFee |
| Complex | Arbitrary nesting of composite and multivalued attributes together. | Parentheses () for composite + braces {} for multivalued: {AddressHistory(City, {Phones})}. |
Multiple previous residences, each with multiple phone numbers |
7.4 Weak Entity Sets
A strong entity set possesses enough attributes to form a primary key independently. A weak entity set lacks sufficient attributes to form a primary key on its own and depends for its existence and identification on a related identifying (owner) entity set. For example, a university SECTION(SectionNo, Semester, Year) cannot exist or be uniquely identified without its owner COURSE(CourseID, Title); similarly, an employee's DEPENDENT(DepName, Relation) depends on EMPLOYEE. In ER diagrams, a weak entity set is drawn as a double rectangle, its identifying relationship as a double diamond with total participation on the weak side, and its discriminator (partial key) is underlined with a dashed line.
Chapter 8: Mapping Cardinalities, Constraints, and EER Features
8.1 Mapping Cardinalities and Participation Constraints
Mapping cardinality (cardinality ratio) specifies the maximum number of entities to which another entity can be associated via a binary relationship set between entity sets and :
- One-to-One (1:1): An entity in is associated with at most one entity in , and an entity in with at most one in (for example,
DEPARTMENT—HOD). - One-to-Many (1:N): An entity in can associate with any number of entities in , while each entity in associates with at most one in (for example,
DEPARTMENT—STUDENT). - Many-to-One (N:1): Reverse of 1:N; many students belong to one department.
- Many-to-Many (M:N): An entity in can associate with many in , and vice versa (for example,
STUDENT—COURSE).
Participation constraints specify whether an entity's existence depends on participating in the relationship: Total participation (drawn as a double line) requires every entity in the set to participate in at least one relationship instance (minimum cardinality ≥ 1); Partial participation (single line) allows some entities not to participate (minimum cardinality = 0). Modern ER diagrams express both cardinality and participation together using (min, max) notation (for example, (1, 1) for mandatory single association, (0, N) for optional many) or Crow's Foot symbols.
| Notation Style | Entity Representation | Relationship Representation | Cardinality & Participation |
|---|---|---|---|
| Chen ER Notation | Rectangle (Double for Weak) | Diamond (Double for Identifying) | Arrows / 1, N, M labels; double line for total participation. |
| Crow's Foot (IE) | Box with PK/FK compartments | Line connecting entity boxes | Crow's foot (many), bar (one), circle (zero/optional). |
| UML Class Diagram | Class box with attributes | Association line / diamond | Multiplicity ranges 0..1, 1..1, 0..*, 1..*. |
8.2 Primary Keys, Redundant Attributes, and ER Design Issues
Every strong entity set has a primary key (underlined). For a binary relationship set, the primary key is formed from the primary keys of participating entity sets depending on cardinality: for M:N, the union of both primary keys; for 1:N or N:1, the primary key of the "many" side; for 1:1, the primary key of either side.
Removing Redundant Attributes: Beginners often mistakenly copy foreign-key-like attributes into entity sets—such as placing DeptName inside STUDENT while also drawing a BELONGS_TO relationship between STUDENT and DEPARTMENT. In a conceptual ER diagram, the relationship already represents the association; retaining DeptName as an attribute inside STUDENT is redundant and must be removed. Foreign keys appear only later during relational schema reduction.
Architects must also resolve four classic ER Design Issues:
- Entity Set vs. Attribute: Model a concept (such as
PhoneorDepartment) as an entity set rather than a plain attribute whenever it has multiple properties of its own, needs independent existence, or participates in relationships with other entities. - Entity Set vs. Relationship Set: Model an action (such as
LOANorBOOKING) as an entity set if it carries its own identifier and participates in further relationships (for example,PAYMENTpays for aLOAN). - Binary vs. n-ary Relationship Sets: Although any ternary relationship can be decomposed into three binary relationships by introducing a connecting entity set, a true ternary relationship preserves exact semantic constraints when the association exists only among all three entities simultaneously.
- Placement of Relationship Attributes: In a 1:N relationship, a descriptive attribute can be placed on the relationship or on the "many"-side entity; in M:N, descriptive attributes (like
Grade) must remain on the relationship diamond.
8.3 Extended ER (EER) Features
To model complex domains cleanly, the Extended ER (EER) model adds object-oriented abstractions:
- Specialization (Top-Down): Subdividing an entity set into specialized lower-level subclasses based on distinguishing characteristics (for example,
PERSONspecialized intoSTUDENTandFACULTY). Subclasses inherit all attributes and relationships of the superclass (attribute inheritance). - Generalization (Bottom-Up): Merging multiple entity sets sharing common attributes into a single generalized superclass (for example,
CARandTRUCKgeneralized intoVEHICLE). - Constraints on Specialization/Generalization: Disjointness specifies whether an entity can belong to at most one subclass (disjoint,
d) or multiple subclasses simultaneously (overlapping,o). Completeness specifies whether every superclass entity must belong to at least one subclass (total, double line) or not (partial, single line). - Aggregation: Treats an entire relationship set and its participating entity sets as a single higher-level abstract entity so it can participate in another relationship (for example, treating
(EMPLOYEE works_on PROJECT)as an aggregate entity managed by aMANAGER).
Chapter 9: Reducing ER Diagrams to Relational Schemas
9.1 Systematic Seven-Step Reduction Algorithm
Converting an ER diagram into a normalized relational database schema follows a deterministic seven-step mapping procedure:
- Strong Entity Sets: Create a relation with all simple attributes of the entity set; underline its primary key.
- Composite Attributes: Flatten composite attributes by including only their simple component attributes as separate columns (for example,
FirstName, LastNameinstead ofName). - Multivalued Attributes: For each multivalued attribute of entity set , create a separate relation containing the primary key of plus ; the primary key of the new relation is the combination of both.
- Weak Entity Sets: Create a relation containing all attributes of the weak entity set plus the primary key of its identifying owner entity set as a foreign key. The primary key is the owner's primary key combined with the weak entity's discriminator.
- Binary M:N Relationship Sets: Create a new relation containing the primary keys of both participating entity sets (as foreign keys) plus any descriptive attributes of the relationship. The combined primary keys form the new relation's primary key.
- Binary 1:N / N:1 Relationship Sets: Do not create a separate table (unless the relationship is very sparse). Instead, add the primary key of the "1"-side entity set as a foreign key (along with any descriptive attributes) into the relation representing the "N"-side entity set.
- Binary 1:1 Relationship Sets: Choose either entity relation (preferring the side with total participation) and include the primary key of the other entity as a
UNIQUEforeign key. If both sides have total participation, the two entity sets may optionally be merged into one relation.
For EER Specialization/Generalization, designers choose among four mapping strategies: (a) Superclass + Subclass tables (PK of superclass inherited as PK/FK in each subclass—works for all constraints), (b) Subclass tables only (duplicate superclass attributes into each subclass—valid only for total disjoint specialization), (c) Single table with type discriminator (nulls for inapplicable attributes), or (d) Single table with multiple boolean flags (for overlapping subclasses).
9.2 Worked Case Study 1: Hospital Management System
Consider a Hospital Management System ER model with strong entities PATIENT(PatientID, Name(First, Last), DOB, /Age, {Phone}), DOCTOR(DoctorID, DocName, Specialization), WARD(WardNo, WardType, Capacity), weak entity BILL_ITEM(ItemNo, Description, Amount) identified by PATIENT, and relationships: TREATS(M:N, DiagnosisDate, Notes) between Doctor and Patient, and ADMITTED_TO(N:1, AdmitDate) from Patient to Ward. Applying the reduction rules yields:
PATIENT(PatientID, FirstName, LastName, DOB, WardNo [FK], AdmitDate)— compositeNameflattened; derivedAgeomitted from physical storage; 1:NADMITTED_TOmerged into Patient.PATIENT_PHONE(PatientID [FK], Phone)— multivalued attribute extracted into its own relation.DOCTOR(DoctorID, DocName, Specialization)andWARD(WardNo, WardType, Capacity).TREATS(DoctorID [FK], PatientID [FK], DiagnosisDate, Notes)— M:N relationship mapped to junction table.BILL_ITEM(PatientID [FK], ItemNo, Description, Amount)— weak entity composite PK combining owner PK and discriminator.
9.3 Worked Case Study 2: Railway Reservation System
A Railway Reservation System models TRAIN(TrainNo, TrainName, Type), STATION(StationCode, StationName, City), PASSENGER(PassengerID, PName, Age, Gender), and TICKET(PNR, JourneyDate, Class, TotalFare, BookingStatus). Relationships include STOPS_AT(M:N, SeqNo, ArrivalTime, DepartureTime) between Train and Station, FOR_TRAIN(N:1) from Ticket to Train, and BOOKED_FOR(M:N, SeatNo, BerthPref) between Ticket and Passenger. Reducing this ER diagram produces:
TRAIN(TrainNo, TrainName, Type)andSTATION(StationCode, StationName, City).ROUTE_STOP(TrainNo [FK], SeqNo, StationCode [FK], ArrivalTime, DepartureTime).PASSENGER(PassengerID, PName, Age, Gender).TICKET(PNR, TrainNo [FK], JourneyDate, Class, TotalFare, BookingStatus).TICKET_PASSENGER(PNR [FK], PassengerID [FK], SeatNo, BerthPref).
9.4 Complete DDL Implementation of the Reduced ER Schemas
Translating the reduced relational schemas into executable SQL DDL demonstrates how conceptual ER cardinality and participation constraints map directly to PRIMARY KEY, FOREIGN KEY, NOT NULL, and UNIQUE clauses.
-- HOSPITAL MANAGEMENT SYSTEM (Reduced from ER Diagram)
CREATE TABLE WARD (
WardNo INT PRIMARY KEY,
WardType VARCHAR(30) NOT NULL,
Capacity INT CHECK (Capacity > 0)
);
CREATE TABLE DOCTOR (
DoctorID INT PRIMARY KEY,
DocName VARCHAR(80) NOT NULL,
Specialization VARCHAR(60) NOT NULL
);
CREATE TABLE PATIENT (
PatientID INT PRIMARY KEY,
FirstName VARCHAR(40) NOT NULL,
LastName VARCHAR(40) NOT NULL,
DOB DATE NOT NULL,
WardNo INT,
AdmitDate DATE,
FOREIGN KEY (WardNo) REFERENCES WARD(WardNo) ON DELETE SET NULL
);
CREATE TABLE PATIENT_PHONE (
PatientID INT,
Phone VARCHAR(15),
PRIMARY KEY (PatientID, Phone),
FOREIGN KEY (PatientID) REFERENCES PATIENT(PatientID) ON DELETE CASCADE
);
CREATE TABLE TREATS (
DoctorID INT,
PatientID INT,
DiagnosisDate DATE NOT NULL,
Notes VARCHAR(255),
PRIMARY KEY (DoctorID, PatientID),
FOREIGN KEY (DoctorID) REFERENCES DOCTOR(DoctorID),
FOREIGN KEY (PatientID) REFERENCES PATIENT(PatientID)
);
CREATE TABLE BILL_ITEM (
PatientID INT,
ItemNo INT,
Description VARCHAR(100) NOT NULL,
Amount DECIMAL(10,2) CHECK (Amount >= 0),
PRIMARY KEY (PatientID, ItemNo),
FOREIGN KEY (PatientID) REFERENCES PATIENT(PatientID) ON DELETE CASCADE
);
-- RAILWAY RESERVATION SYSTEM (Reduced from ER Diagram)
CREATE TABLE TRAIN (
TrainNo INT PRIMARY KEY,
TrainName VARCHAR(80) NOT NULL,
Type VARCHAR(30) NOT NULL
);
CREATE TABLE STATION (
StationCode VARCHAR(10) PRIMARY KEY,
StationName VARCHAR(80) NOT NULL,
City VARCHAR(50) NOT NULL
);
CREATE TABLE ROUTE_STOP (
TrainNo INT,
SeqNo INT,
StationCode VARCHAR(10) NOT NULL,
ArrivalTime TIME,
DepartureTime TIME,
PRIMARY KEY (TrainNo, SeqNo),
FOREIGN KEY (TrainNo) REFERENCES TRAIN(TrainNo) ON DELETE CASCADE,
FOREIGN KEY (StationCode) REFERENCES STATION(StationCode)
);
CREATE TABLE TICKET (
PNR VARCHAR(12) PRIMARY KEY,
TrainNo INT NOT NULL,
JourneyDate DATE NOT NULL,
Class VARCHAR(10) NOT NULL,
TotalFare DECIMAL(8,2) CHECK (TotalFare > 0),
BookingStatus VARCHAR(20) DEFAULT 'CONFIRMED',
FOREIGN KEY (TrainNo) REFERENCES TRAIN(TrainNo)
);9.5 Summary Checklist for Conceptual ER Validation
Before finalizing any ER diagram for relational reduction, database architects perform a six-point quality audit:
- Key Completeness: Every strong entity set has a clearly underlined primary key; every weak entity set has a dashed partial key and an identifying relationship with total participation.
- Zero Redundant Foreign Keys: No entity set contains an attribute that merely duplicates the primary key of a connected entity set via a relationship.
- Correct Relationship Cardinalities: Every relationship edge clearly specifies 1:1, 1:N, N:1, or M:N (or
(min, max)bounds) matching real business rules. - Proper Attribute Classification: Multivalued attributes (
{Phone}), composite attributes (Name(First, Last)), and derived attributes (/Age) are explicitly distinguished so reduction handles them accurately. - Role Labels on Recursive Relationships: Any self-referencing relationship clearly names both roles (for example, Prerequisite vs. Course).
- EER Constraint Clarity: Every specialization/generalization hierarchy explicitly marks disjoint (
d) vs. overlapping (o) and total vs. partial completeness.
9.6 Worked EER Specialization and Aggregation Mapping
To see how Extended ER constructs translate into concrete relational tables, consider a University Personnel hierarchy where PERSON(PersonID, Name, Email, Phone) is specialized (disjoint, partial) into STUDENT(RollNo, Program, CGPA) and FACULTY(EmpCode, Designation, Salary), alongside an aggregated relationship SPONSORS linking a GRANT_AGENCY(AgencyID, AgencyName) to the ternary/binary association WORKS_ON(FACULTY, PROJECT).
Applying the Superclass + Subclass Tables mapping strategy (Option A) produces clean, anomaly-free tables without NULL-padded columns:
PERSON(PersonID, Name, Email, Phone)— holds shared attributes once.STUDENT(PersonID [PK, FK → PERSON], RollNo [UNIQUE], Program, CGPA)— inheritsPersonIDas both primary and foreign key.FACULTY(PersonID [PK, FK → PERSON], EmpCode [UNIQUE], Designation, Salary)— ensures every faculty member exists inPERSON.WORKS_ON(PersonID [FK → FACULTY], ProjectID [FK → PROJECT], Role, HoursPerWeek)— represents the base M:N relationship.SPONSORS(AgencyID [FK], PersonID [FK], ProjectID [FK], GrantAmount, SanctionDate)— maps the aggregation by referencing the primary key ofWORKS_ONtogether withAgencyID.
CREATE TABLE PERSON (
PersonID INT PRIMARY KEY,
FullName VARCHAR(80) NOT NULL,
Email VARCHAR(100) UNIQUE NOT NULL
);
CREATE TABLE STUDENT_SUB (
PersonID INT PRIMARY KEY,
RollNo VARCHAR(20) UNIQUE NOT NULL,
Program VARCHAR(40) NOT NULL,
CGPA DECIMAL(3,2) CHECK (CGPA BETWEEN 0.00 AND 10.00),
FOREIGN KEY (PersonID) REFERENCES PERSON(PersonID) ON DELETE CASCADE
);
CREATE TABLE FACULTY_SUB (
PersonID INT PRIMARY KEY,
EmpCode VARCHAR(20) UNIQUE NOT NULL,
Designation VARCHAR(50) NOT NULL,
Salary DECIMAL(10,2) CHECK (Salary > 0),
FOREIGN KEY (PersonID) REFERENCES PERSON(PersonID) ON DELETE CASCADE
);
-- Weak Entity Example: COURSE (Owner) -> SECTION (Weak Entity)
CREATE TABLE COURSE_MASTER (
CourseID VARCHAR(12) PRIMARY KEY,
Title VARCHAR(100) NOT NULL,
Credits INT NOT NULL
);
CREATE TABLE COURSE_SECTION (
CourseID VARCHAR(12),
SecNo INT,
Semester VARCHAR(15),
Year INT,
RoomNo VARCHAR(20),
PRIMARY KEY (CourseID, SecNo, Semester, Year),
FOREIGN KEY (CourseID) REFERENCES COURSE_MASTER(CourseID) ON DELETE CASCADE
);9.7 Ternary Relationships vs. Three Binary Relationships
A common conceptual modeling pitfall is replacing a genuine ternary relationship (such as SUPPLIER supplies PART to PROJECT with attribute Quantity) with three separate binary relationships (SUPPLIES(Supplier, Part), USES(Project, Part), and CONTRACTS(Supplier, Project)). The three binary tables lose the exact three-way fact: knowing that Supplier S1 supplies Part P1, Project J1 uses Part P1, and S1 has a contract with J1 does not prove that S1 actually delivered P1 to J1! Whenever an association requires all three entities simultaneously—or carries an attribute like Quantity that depends on all three—it must be modeled as a ternary relationship (or reified into a weak/connecting entity SHIPMENT(ShipID, SupplierID, PartID, ProjectID, Quantity)).
9.8 Worked Case Study 3: Library Management System (ER to Relational)
To reinforce ER-to-relational reduction, consider a University Library System with strong entities BOOK(ISBN, Title, Publisher, Year, {Author}), MEMBER(MemberID, Name(First, Last), Email, MemberType), weak entity BOOK_COPY(CopyNo, ShelfLocation, Condition) identified by BOOK, and EER specialization of MEMBER into STUDENT_MEM(RollNo, Dept) and FACULTY_MEM(EmpID, CabinNo). Members borrow specific book copies via BORROWS(M:N, IssueDate, DueDate, ReturnDate, FineAmount).
BOOK(ISBN, Title, Publisher, PubYear)— strong entity with simple attributes.BOOK_AUTHOR(ISBN [FK], AuthorName)— multivalued attribute{Author}extracted.BOOK_COPY(ISBN [FK], CopyNo, ShelfLocation, Condition)— weak entity combining owner PK and discriminator.MEMBER(MemberID, FirstName, LastName, Email)— superclass table with flattened composite name.STUDENT_MEM(MemberID [PK, FK], RollNo, Dept)andFACULTY_MEM(MemberID [PK, FK], EmpID, CabinNo).BORROWS(MemberID [FK], ISBN [FK], CopyNo [FK], IssueDate, DueDate, ReturnDate, FineAmount)— M:N relationship referencingMEMBERandBOOK_COPY, withIssueDatein the PK so the same member can borrow the same copy again on a future date.
9.9 ER Design Patterns for Historical and Temporal Data
Standard ER relationships capture only the current snapshot unless time is modeled explicitly. When an enterprise must retain historical records—such as an employee's past department transfers, historical product prices, or multiple hospital admissions by the same patient—including a timestamp attribute (such as EffectiveDate or AdmitDate) inside the relationship's primary key prevents overwriting earlier records and preserves a complete audit history.
9.10 Worked Case Study 4: E-Commerce Order & Inventory ER Schema
To demonstrate how ER modeling scales to commercial applications, consider an E-Commerce platform with strong entities CUSTOMER(CustID, Name(First, Last), Email, {ShippingAddr}), PRODUCT(ProdID, ProdName, UnitPrice, StockQty), CATEGORY(CatID, CatName), and ORDER(OrderID, OrderDate, TotalAmount, Status), plus weak entity PAYMENT(PaySeq, Method, PaidAmount, PayDate) identified by ORDER. Relationships include BELONGS_TO(N:1) from Product to Category, PLACES(1:N) from Customer to Order, and ORDER_ITEM(M:N, Quantity, PriceAtPurchase) between Order and Product.
CATEGORY(CatID, CatName)andPRODUCT(ProdID, ProdName, UnitPrice, StockQty, CatID [FK]).CUSTOMER(CustID, FirstName, LastName, Email)andCUST_ADDRESS(CustID [FK], ShippingAddr).ORDERS(OrderID, CustID [FK], OrderDate, TotalAmount, Status).ORDER_ITEM(OrderID [FK], ProdID [FK], Quantity, PriceAtPurchase)— storingPriceAtPurchasepreserves historical invoice accuracy even whenPRODUCT.UnitPricechanges later.PAYMENT(OrderID [FK], PaySeq, Method, PaidAmount, PayDate)— weak entity supporting split payments per order.
9.11 Summary Matrix of ER-to-Relational Mapping Rules
| ER Construct | Relational Mapping Rule | Primary Key Choice |
|---|---|---|
| Strong Entity Set | Create one relation with all simple attributes. | Entity's own key attribute(s). |
| Weak Entity Set | Create relation with weak attributes + owner PK as FK. | Owner PK + weak discriminator. |
| 1:1 Relationship | Add PK of one side as UNIQUE FK into the other (prefer total side). | PK of the chosen host relation. |
| 1:N / N:1 Relationship | Add PK of "1" side as FK into "N"-side relation. | PK of the "N"-side relation. |
| M:N Relationship | Create separate junction relation with both PKs + descriptive attrs. | Union of both participating PKs. |
| Multivalued Attribute | Create separate relation with owner PK + attribute. | Owner PK + multivalued attribute. |
| n-ary Relationship | Create relation with PKs of all n entities + descriptive attrs. | Union of all participating PKs (unless 1-side exists). |
Module IV: Normalization and Database Design Process
Chapter 10: Functional Dependencies and Armstrong's Axioms
10.1 Features of Good Relational Design
A poorly structured relational schema—such as combining all attributes of INSTRUCTOR and DEPARTMENT into a single wide table INST_DEPT(ID, Name, Salary, DeptName, Building, Budget)—causes severe operational anomalies:
| ID | Name | Salary | DeptName | Building | Budget |
|---|---|---|---|---|---|
| 101 | Asha | 65000 | CS | IT Block | 900000 |
| 102 | Rahul | 72000 | CS | IT Block | 900000 |
| 103 | Meera | 60000 | EC | Main Block | 750000 |
- Data Redundancy: The building (
IT Block) and budget (900000) of the CS department are repeated for every CS instructor. - Insertion Anomaly: We cannot insert a newly created department (such as Artificial Intelligence) until at least one instructor is hired into it, unless we insert
NULLforID(which violates entity integrity). - Deletion Anomaly: Deleting instructor
103(Meera) unintentionally destroys all records of theECdepartment's building and budget. - Update Anomaly: Changing CS's budget requires updating multiple instructor rows; missing even one row leaves the database inconsistent.
To eliminate anomalies safely, we decompose large relations into smaller ones. A good decomposition must satisfy two properties: (1) Lossless-Join Decomposition—joining the decomposed relations back together must reconstruct the exact original tuples without generating spurious (fake) rows; and (2) Dependency Preservation—all functional dependencies can be enforced by checking single tables without expensive multi-table joins.
10.2 Functional Dependencies (FDs)
A Functional Dependency (FD), denoted , is a constraint between two sets of attributes and in a relation schema . It states that for any two tuples and in any valid instance of , whenever , it must also hold that . We say " functionally determines " (where is the determinant and is the dependent).
Functional dependencies are classified into five key types:
- Trivial FD: is trivial if (for example,
{ID, Name} → {Name}). Trivial FDs hold automatically in every relation. - Non-Trivial FD: where ; completely non-trivial if .
- Full Functional Dependency: is full if removing any single attribute breaks the dependency ().
- Partial Functional Dependency: depends on only a proper subset of a candidate key .
- Transitive Functional Dependency: holds indirectly because and , where is neither a subset of nor a superkey.
10.3 Armstrong's Axioms and Attribute Closure
Given a set of functional dependencies , the closure is the set of all FDs logically implied by . W.W. Armstrong proved that three axioms are both sound and complete for inferring :
- Reflexivity Rule: If , then .
- Augmentation Rule: If , then for any attribute set .
- Transitivity Rule: If and , then .
From these three axioms, three convenient derived rules follow: Union (), Decomposition (), and Pseudotransitivity ().
To test whether is a superkey or whether is implied by , we compute the Attribute Closure : initialize result := X; repeatedly scan every FD in , and if , set result := result ∪ B until no new attributes can be added. is a superkey if and only if .
10.4 Canonical (Minimal) Cover Computation
A Canonical Cover is a simplified equivalent set of FDs with singleton right-hand sides, no extraneous attributes, and no redundant FDs. We compute in three steps: (1) decompose all right-hand sides into singletons using the Decomposition rule; (2) for each FD , test if any attribute is extraneous (check if under current already contains ); and (3) delete any FD if computed using .
Worked Canonical Cover Example: Let . Split right-hand sides: . In , is extraneous because already contains , reducing to (duplicate). Next, is redundant because and imply . Thus, .
Chapter 11: Normal Forms and Decomposition Algorithms
11.1 First, Second, Third, and Boyce-Codd Normal Forms
Normalization is the stepwise process of organizing relations to eliminate redundancy and anomalies. A prime attribute belongs to at least one candidate key of ; a non-prime attribute belongs to no candidate key.
| Normal Form | Formal Condition | Anomaly Eliminated | Remediation Action |
|---|---|---|---|
| 1NF | Every attribute domain is atomic (indivisible); no repeating groups or nested tables. | Non-atomic / multi-valued cells inside a single tuple. | Flatten nested structures or move multivalued attributes to separate relations. |
| 2NF | In 1NF, and no non-prime attribute is partially dependent on any candidate key. | Partial dependencies on composite candidate keys. | Decompose out attributes depending on only part of the composite key. |
| 3NF | In 2NF, and for every non-trivial FD , either is a superkey OR is a prime attribute. | Transitive dependencies of non-prime attributes on candidate keys. | Extract transitive determinant into a separate relation. |
| BCNF | For every non-trivial FD , must be a superkey of . | All redundancy caused by any FD (including prime-attribute dependencies). | Decompose violating into and . |
11.2 Lossless-Join Test, BCNF vs. 3NF, and Synthesis
When decomposing into and , the decomposition is guaranteed to be lossless-join if and only if at least one of the following two FDs holds in :
While BCNF eliminates all FD-based redundancy and always admits a lossless-join decomposition, it is not always dependency-preserving. Consider with FDs . Here (City, Street) and (Street, Zip) are candidate keys. The FD violates BCNF (because Zip is not a superkey), yet it satisfies 3NF (because City is a prime attribute). Decomposing into (Zip, City) and (Zip, Street) achieves BCNF and lossless join, but loses the ability to enforce (City, Street) → Zip within a single table! By contrast, the 3NF Synthesis Algorithm constructs one relation for each FD in and adds a candidate-key relation if none contains a key, guaranteeing both lossless-join and dependency preservation simultaneously.
11.3 Worked Normalization Walkthrough
Consider an unnormalized university grade sheet GRADE_REPORT(StudentID, SName, Dept, DeptHead, CourseID, CTitle, Grade) with candidate key (StudentID, CourseID) and FDs: StudentID → SName, Dept; Dept → DeptHead; CourseID → CTitle; and (StudentID, CourseID) → Grade.
- 1NF: Assuming all attributes are atomic (one course per row, no nested lists), the table is in 1NF.
- 2NF Decomposition:
SName,Dept, andDeptHeadpartially depend onStudentID;CTitlepartially depends onCourseID. We decompose into:STUDENT(StudentID, SName, Dept, DeptHead),COURSE(CourseID, CTitle), andENROLLMENT(StudentID, CourseID, Grade). - 3NF / BCNF Decomposition: In
STUDENT,Dept → DeptHeadis a transitive dependency (Deptis not a superkey andDeptHeadis non-prime). DecomposingSTUDENTyields:STUDENT(StudentID, SName, Dept)andDEPARTMENT(Dept, DeptHead). Every determinant in all four final tables is now a superkey, achieving both 3NF and BCNF with lossless joins and full dependency preservation.
11.4 Higher Normal Forms (4NF & 5NF) and the Database Design Process
Beyond BCNF, Fourth Normal Form (4NF) eliminates redundancy caused by independent Multivalued Dependencies (MVDs) (for example, storing an employee's independent skills and languages in one table), requiring every non-trivial MVD to have as a superkey. Fifth Normal Form (5NF / PJNF) eliminates redundancy from cyclic Join Dependencies that cannot be expressed by FDs or MVDs.
In the end-to-end Database Design Process, ER modeling and normalization complement each other: ER modeling captures high-level entities and relationships, schema reduction generates initial tables, and 3NF/BCNF normalization formally eliminates subtle anomalies. During physical tuning, architects may selectively denormalize (for example, caching a computed invoice total) only when read-heavy analytical latency demands it and triggers or application logic protect consistency.
11.5 Worked Dependency Preservation and Lossless-Join Verification
Let us verify both properties mathematically on a classic relation with functional dependencies . Notice that , so A, B, C, and D are all candidate keys, and every FD's determinant is already a superkey—meaning is already in BCNF!
Now consider a more nuanced schema with . Here , so P is the sole candidate key. Both and are transitive dependencies violating 3NF and BCNF.
- Step 1 (Decompose on ): Split into and . Check lossless join: , and means . Thus Step 1 is lossless.
- Step 2 (Decompose on ): Split into and . Check lossless join: , and means . Thus Step 2 is also lossless.
- Final Verification: Every relation , , and has only its key on the left-hand side of its FDs, achieving BCNF, lossless join, and full dependency preservation (, , and are each local to one table).
11.6 Worked Normalization of a Hospital Billing Table
Suppose a clinic initially records patient visits in a single unnormalized spreadsheet VISIT_SHEET(VisitID, VisitDate, PatientID, PName, Phones, DocID, DocName, Spec, Fee) where Phones can contain multiple comma-separated phone numbers. Normalizing step by step:
- Convert to 1NF: Separate the repeating
Phonesattribute intoPATIENT_PHONE(PatientID, Phone)and keep atomic columns inVISIT(VisitID, VisitDate, PatientID, PName, DocID, DocName, Spec, Fee). - Check 2NF: Since
VisitIDis a single-attribute primary key, there are no partial dependencies;VISITis already in 2NF. - Convert to 3NF / BCNF: Identify transitive dependencies:
PatientID → PNameandDocID → DocName, Spec. Decomposing out both determinants yields four clean BCNF relations:PATIENT(PatientID, PName),PATIENT_PHONE(PatientID [FK], Phone),DOCTOR(DocID, DocName, Spec), andVISIT(VisitID, VisitDate, PatientID [FK], DocID [FK], Fee).
11.7 Normalization vs. Denormalization Trade-off
| Design Criterion | Normalized Schema (3NF / BCNF) | Selectively Denormalized Schema |
|---|---|---|
| Write Performance (OLTP) | Fast, localized updates; zero redundant copies to synchronize. | Slower writes; redundant columns require multi-row updates or triggers. |
| Read Performance (OLAP) | Requires multi-table joins for summary reports. | Very fast single-table scans without runtime joins. |
| Data Integrity | Guaranteed structurally by keys and FDs; immune to anomalies. | Risks silent inconsistency if application code bypasses sync logic. |
| Storage Footprint | Minimal; eliminates repeated descriptive strings. | Larger due to duplicated attributes across fact rows. |
11.8 Comprehensive Step-by-Step Worked Examples for University Exams
Mastery of normalization requires fluency in finding candidate keys, computing minimal covers, testing normal forms, and executing lossless BCNF/3NF decompositions. Below are three complete, step-by-step worked problems covering every exam pattern.
Worked Problem 1: Finding All Candidate Keys Using Attribute Closure
Given relation and FD set :
- Classify Attributes: Attributes appearing on the right-hand side (RHS) are
{A, B, C, D, E, F}—every attribute appears on some RHS, so there is no single attribute guaranteed to be in every key; however, we test minimal combinations starting with determinants. - Test Singletons:
- → C is a candidate key!
- → D is a candidate key!
- (cannot reach B, C, D) → not a key.
- → not a key.
- Test Pairs Containing Non-Keys:
- → since neither
AnorBalone is a key, AB is a candidate key! - → EB is a candidate key!
- → FB is a candidate key!
- → since neither
- Conclusion: The candidate keys are C, D, AB, EB, FB, and every attribute in is a prime attribute.
Worked Problem 2: Testing Highest Normal Form of a Relation
Given with :
- Find Candidate Keys: Compute . Since
Qnever appears on any RHS,Qmust belong to every key. Testing pairs withQ: and . Thus, candidate keys are PQ, RQ, SQ. Prime attributes ={P, Q, R, S}(all attributes are prime!). - Check 2NF & 3NF: Since there are no non-prime attributes at all, there can be no partial or transitive dependencies of non-prime attributes. Therefore, is in 3NF!
- Check BCNF: Inspect and . Neither
RnorSis a superkey (since neither containsQ). Therefore, violates BCNF. Highest normal form = 3NF.
Worked Problem 3: 3NF Synthesis Algorithm (Dependency-Preserving & Lossless)
Given and :
- Compute Canonical Cover : Notice is redundant because and imply . No LHS has multiple attributes. Thus .
- Create Relations for Each FD in : , , and .
- Verify Candidate Key Containment: The sole candidate key of is
A(). SinceR_1(A, B)already containsA, no extra key relation is needed. - Verify Properties: Every FD in resides inside a single relation (dependency-preserving), and (key of ) and (key of ), guaranteeing a lossless join!
11.9 Summary Comparison of Normal Forms (1NF to 5NF)
| Normal Form | Dependency Type Addressed | Key Requirement | Practical Industry Target |
|---|---|---|---|
| 1NF | Repeating groups / non-atomic cells | Atomic domain values | Mandatory baseline for all SQL tables. |
| 2NF | Partial FDs on composite keys | Full FD on whole candidate key | Intermediate step toward 3NF. |
| 3NF | Transitive FDs of non-prime attributes | Determinant is superkey or RHS is prime | Standard OLTP target (lossless + dep-preserving). |
| BCNF | All non-trivial FDs | Every determinant is a superkey | Preferred when dependency preservation holds. |
| 4NF | Multivalued Dependencies (MVDs) | Every non-trivial MVD determinant is superkey | Used when independent 1:N sets coexist. |
| 5NF | Cyclic Join Dependencies (JDs) | Every JD implied by candidate keys | Rare; specialized multi-way fact schemas. |
11.10 Worked Problem 4: Lossless-Join Chase Test (Tabular Method)
When a relation is decomposed into three or more relations , the binary intersection rule cannot be applied in one step. Instead, we use the Chase Test:
- Construct a tableau with rows (one per decomposed relation ) and columns (one per attribute ).
- In row , place symbol if attribute ; otherwise place .
- Repeatedly apply each FD in : whenever two rows agree on all attributes of , equate their values on (always preferring over ).
- The decomposition is lossless-join if and only if at least one row becomes all- symbols ().
Example: Let with be decomposed into , , , , and .
| Relation | A | B | C | D | E |
|---|---|---|---|---|---|
Applying equates in rows 1, 2, 5 to ; applying equates row 3's to ; applying equates in rows 2, 3, 5 to ; applying on rows 3, 4, 5 (which now all share ) turns into in rows 3 and 5; finally, applying on rows 3, 4, 5 turns into . No row has all five s? Wait: row 2 had which became when merged with , and row 2 already has , lacking only ; row 3 has ! Because row 3 becomes completely , the 5-way decomposition is lossless.
11.11 Worked Problem 5: Equivalence of Two Functional Dependency Sets
Two FD sets and over relation are equivalent () if and only if covers (every FD satisfies ) AND covers (every FD satisfies ).
For example, test and :
- Does cover ? Under , (covers ) and (covers ). Yes!
- Does cover ? Under , (covers and ) and (covers and ). Yes!
- Conclusion: Since both sets cover each other, .
11.12 Complete Database Design Lifecycle Summary
Bringing Modules I–IV together, a disciplined database engineer moves smoothly from real-world requirements to an ER diagram, maps the ER diagram to initial relational schemas, verifies candidate keys and canonical covers via Armstrong's axioms, decomposes relations to 3NF/BCNF with lossless-join guarantees, and finally deploys SQL DDL constraints and indexes to enforce those invariants automatically at runtime.
11.13 Worked Problem 6: BCNF Decomposition of a University Scheduling Schema
Consider a scheduling relation with functional dependencies:
- (each course is taught by one teacher)
- (only one course meets in a given room at a given hour)
- (a teacher can be in only one room at a given hour)
- (a student receives one grade per course)
- (a student can be in only one room at a given hour)
Step 1 — Candidate Keys: Compute = {Hour, Student, Room, Course, Teacher, Grade} = R. Similarly, is a superkey, and is a superkey, but since already determines Room and Teacher, the sole candidate key is (Hour, Student)!
Step 2 — Identify BCNF Violations: Four FDs have determinants that do not contain Student (and therefore are not superkeys): , , , and .
Step 3 — Lossless BCNF Decomposition:
- Decompose on : (BCNF) and .
- In , decompose on : (BCNF) and .
- In , decompose on : (BCNF) and (BCNF).
Every final relation is strictly in BCNF, and every step satisfied the binary lossless-join condition.
11.14 Worked Problem 7: Eliminating Multivalued Dependencies (4NF)
Suppose a faculty directory stores FACULTY_INFO(FacID, CourseTaught, Committee) where a professor teaches multiple courses independently of the committees they serve on. The table is already in BCNF because there are no non-trivial FDs (the entire triple (FacID, CourseTaught, Committee) is the sole candidate key). However, it suffers from severe Cartesian redundancy: if Professor 101 teaches 3 courses and serves on 4 committees, 3 × 4 = 12 rows are required! Here, and are independent multivalued dependencies. Decomposing into TEACHES(FacID, CourseTaught) (3 rows) and SERVES_ON(FacID, Committee) (4 rows) achieves Fourth Normal Form (4NF) and cuts storage to 7 rows with zero update anomalies.
11.15 Worked Problem 8: Normalizing an Order-Invoice Schema from 1NF to BCNF
Consider a retail billing report INVOICE_LINE(InvNo, InvDate, CustID, CustName, CustCity, ProdID, ProdName, UnitPrice, Qty, LineTotal) where LineTotal = UnitPrice * Qty and a single invoice can contain multiple products.
- 1NF & Derived Column Removal: Ensure each row represents one product on one invoice, and drop the derived column
LineTotal(computed on the fly or via view). The composite candidate key is(InvNo, ProdID). - Identify All Functional Dependencies:
InvNo → InvDate, CustID(partial dependency onInvNo)CustID → CustName, CustCity(transitive dependency throughCustID)ProdID → ProdName, UnitPrice(partial dependency onProdID)(InvNo, ProdID) → Qty(full dependency on candidate key)
- 2NF Decomposition: Separate attributes partially dependent on
InvNoandProdID:INVOICE(InvNo, InvDate, CustID, CustName, CustCity)PRODUCT(ProdID, ProdName, UnitPrice)— already in 3NF and BCNF!INVOICE_ITEM(InvNo [FK], ProdID [FK], Qty)— already in 3NF and BCNF!
- 3NF / BCNF Decomposition of INVOICE: Because
CustID → CustName, CustCityis a transitive dependency (CustIDis not a superkey ofINVOICE), splitINVOICEinto:CUSTOMER(CustID, CustName, CustCity)— BCNF!INVOICE(InvNo, InvDate, CustID [FK])— BCNF!
Notice how the final four-table BCNF schema (CUSTOMER, INVOICE, PRODUCT, INVOICE_ITEM) matches the exact schema obtained from a clean ER diagram—confirming the mathematical harmony between top-down ER modeling and bottom-up functional-dependency normalization.
11.16 Common Pitfalls in Functional Dependency Analysis
- Confusing Instance Data with Schema Constraints: A functional dependency is a semantic rule true for all possible valid instances, not an accidental coincidence in five sample rows. For example, two students in a tiny sample might have distinct names, but
SName → SIDis false in reality. - Forgetting Trivial Attributes in 2NF/3NF Checks: Always verify whether an attribute is prime before declaring a 3NF violation; is permitted in 3NF (though not BCNF) whenever is part of some candidate key.
- Losing Dependencies During BCNF Decomposition: Always check whether every FD in can still be verified within a single decomposed table; if not, decide consciously between BCNF and 3NF synthesis.
11.17 Worked Problem 9: Railway Ticket Schema Normalization
Consider a flat booking table RAIL_BOOKING(PNR, TrainNo, TrainName, JourneyDate, Class, Coach, SeatNo, PassengerID, PName, Age, Fare) where one PNR covers multiple passengers. Converting to 1NF and separating passenger-specific attributes yields PASSENGER(PassengerID, PName, Age), TRAIN(TrainNo, TrainName), TICKET(PNR, TrainNo [FK], JourneyDate, Class, Fare), and TICKET_SEAT(PNR [FK], PassengerID [FK], Coach, SeatNo). Checking FDs: TrainNo → TrainName is isolated in TRAIN, PassengerID → PName, Age is isolated in PASSENGER, PNR → TrainNo, JourneyDate, Class, Fare is isolated in TICKET, and (PNR, PassengerID) → Coach, SeatNo is isolated in TICKET_SEAT. Every determinant in all four relations is a primary key, guaranteeing BCNF and zero redundancy.
11.18 Controlled Denormalization Patterns in Practice
Although 3NF and BCNF are the gold standard for OLTP schemas, high-traffic analytical dashboards sometimes apply three disciplined denormalization patterns while guarding consistency via triggers or batch jobs:
- Pre-Computed Aggregates: Storing
TotalOrderAmounton anORDERSheader table avoids scanning millions ofORDER_ITEMrows on every invoice summary query. - Materialized Summary Tables: Maintaining nightly rollup tables (such as daily branch revenue) accelerates BI dashboards from minutes to milliseconds.
- Historical Snapshot Columns: Copying
UnitPriceintoINVOICE_ITEMat checkout time is technically redundant withPRODUCT.UnitPriceat purchase instant, yet legally required so future catalog price changes never alter past customer receipts.
11.19 Worked Problem 10: Canonical Cover & Key Discovery on a 6-Attribute Schema
Given with FD set :
- Find Attributes Missing from All RHS: Notice
Xnever appears on the right-hand side of any FD, soXmust be present in every candidate key. - Compute Closures with
X:- → UX is a candidate key!
- → WX is a candidate key!
- → YX is a candidate key!
- → ZX is a candidate key!
- Test Normal Form: Because
U, W, Y, Z, Xare all prime attributes, onlyVis non-prime. In ,Uis a proper subset of candidate keyUXwhileVis non-prime, creating a partial dependency that violates 2NF, 3NF, and BCNF. Therefore, is in 1NF, and decomposing out immediately eliminates the partial dependency.
Module V: Security, Transactions, NoSQL & SQL Lab
Chapter 12: Database Security Issues and Solutions
12.1 Basic Security Concepts and Threat Taxonomy
Database security protects stored data and DBMS infrastructure against unauthorized disclosure, improper modification, and denial of service. It rests on the CIA Triad: Confidentiality (preventing unauthorized reading of sensitive records), Integrity (preventing unauthorized or accidental alteration), and Availability (ensuring authorized users have reliable, timely access).
| Security Issue / Threat | Mechanism of Attack | Recommended Solution |
|---|---|---|
| SQL Injection (SQLi) | Attacker injects malicious SQL fragments into unsanitized user input fields (e.g., ' OR '1'='1). |
Use parameterized queries / prepared statements, strict input validation, and stored procedures. |
| Excessive / Abused Privileges | Users or service accounts hold broader rights than required, enabling data exfiltration or tampering. | Enforce Principle of Least Privilege via RBAC, GRANT/REVOKE, and restricted views. |
| Inference & Statistical Attacks | Deriving confidential individual values from aggregate queries (e.g., COUNT/SUM on small groups). |
Suppress small-group query results, add controlled statistical noise, or restrict aggregate access. |
| Unencrypted Data (Transit & Rest) | Network sniffing captures plaintext queries/passwords; stolen disks or backups expose raw tables. | Mandate TLS/SSL for connections and Transparent Data Encryption (TDE) for disks and backups. |
| Weak Authentication | Default vendor passwords, shared logins, or missing multi-factor checks. | Enforce strong password hashing (bcrypt/Argon2), MFA, centralized IAM/SSO, and unique accounts. |
| Lack of Audit Trails | Inability to detect or investigate breaches after unauthorized DDL/DML execution. | Enable tamper-evident database audit logging and real-time anomaly alerting. |
12.2 Access Control Models: DAC, MAC, RBAC, and SQLi Prevention
DBMS platforms implement authorization using three complementary models:
- Discretionary Access Control (DAC): Object owners grant and revoke specific privileges (
SELECT,INSERT,UPDATE,DELETE,REFERENCES) to other users via SQLGRANT ... ON table TO user [WITH GRANT OPTION]andREVOKE. - Role-Based Access Control (RBAC): Privileges are assigned to named roles (such as
Receptionist,Doctor,BillingClerk) rather than individuals, and users are assigned to roles—dramatically simplifying administration in large organizations. - Mandatory Access Control (MAC): Used in high-security defense systems; classifies data objects and users into hierarchical security levels (Top Secret, Secret, Confidential) following Bell-LaPadula rules ("no read up, no write down").
-- 1. Role-Based Access Control (RBAC) in SQL CREATE ROLE doctor_role; CREATE VIEW PATIENT_PUBLIC AS SELECT PatientID, FirstName, LastName, WardNo FROM PATIENT; GRANT SELECT ON PATIENT_PUBLIC TO doctor_role; GRANT INSERT, UPDATE ON TREATS TO doctor_role; GRANT doctor_role TO 'dr_meera'@'localhost'; -- 2. Parameterized Query (Prepared Statement) blocking SQL Injection PREPARE stmt_login FROM 'SELECT EmpID, EmpName FROM EMPLOYEE WHERE Email = ? AND EmpID = ?'; SET @email = '[email protected]'; SET @id = 101; EXECUTE stmt_login USING @email, @id; DEALLOCATE PREPARE stmt_login;
Chapter 13: Database Design Issues, Transactions, and Concurrency
13.1 Physical Database Design Issues
Even a perfectly normalized 3NF/BCNF schema can perform poorly if physical storage is neglected. Key database design issues include:
- Indexing Strategy: Creating B+ Tree indexes on primary keys, foreign keys, and frequent range-query columns accelerates reads from to , while Hash indexes speed up exact equality lookups. However, every index slows down
INSERT/UPDATE/DELETEoperations and consumes disk space. - Partitioning & Sharding: Horizontal partitioning splits huge tables across date or region ranges into smaller physical segments; vertical partitioning separates frequently accessed columns from bulky BLOBs.
- Controlled Denormalization & Materialized Views: Pre-joining summary tables or caching materialized views trades extra write maintenance for sub-second analytical dashboards.
13.2 Transaction Management, ACID Properties, and States
A transaction is a single logical unit of work consisting of one or more database read/write operations (for example, transferring Rs. 5,000 from Account A to Account B). Every reliable DBMS guarantees four ACID properties:
- Atomicity: "All or nothing"—either every operation in the transaction commits permanently, or all effects are rolled back using the Write-Ahead Log (WAL).
- Consistency: Executing a transaction in isolation transforms the database from one valid state satisfying all integrity constraints to another valid state.
- Isolation: Concurrent transactions execute without interfering with each other's intermediate states, preventing anomalies such as Dirty Reads (reading uncommitted writes), Non-Repeatable Reads, and Phantom Reads.
- Durability: Once a transaction commits, its changes survive power loss or system crashes via non-volatile log flushing and checkpoints.
During execution, a transaction transitions through five states: Active (executing reads/writes) → Partially Committed (final statement executed) → Committed (log flushed to disk), or if an error occurs: Failed → Aborted (rolled back to prior state).
13.3 Serializability, Locking Protocols, and Crash Recovery
When transactions interleave concurrently, a schedule is Conflict Serializable if it is conflict-equivalent to a serial schedule—tested by constructing a Precedence (Serialization) Graph with nodes for transactions and directed edges whenever accesses a data item before a conflicting access (at least one write) by . The schedule is conflict serializable if and only if the graph is acyclic.
To enforce serializability automatically, DBMS engines use Strict Two-Phase Locking (Strict 2PL): transactions acquire Shared (S) locks for reads and Exclusive (X) locks for writes during a growing phase, and hold all exclusive locks until commit or abort (preventing cascading aborts). Deadlocks caused by circular lock waits are resolved via Wait-For Graph cycle detection (aborting a victim) or timestamp prevention schemes (Wait-Die and Wound-Wait). Crash recovery relies on Write-Ahead Logging (WAL) and periodic Checkpoints to redo committed writes and undo uncommitted writes after a failure.
Chapter 14: NoSQL Databases and Complete SQL Lab Solutions
14.1 Motivation for NoSQL, CAP Theorem, and BASE
Traditional relational databases excel at structured, transactional workloads but face friction when handling petabyte-scale unstructured web logs, rapidly evolving JSON schemas, and global horizontal scaling across commodity clusters. NoSQL ("Not Only SQL") databases sacrifice strict relational joins and rigid schemas to achieve horizontal scalability and high availability.
Eric Brewer's CAP Theorem states that a distributed data store can simultaneously guarantee at most two of three properties: Consistency (C) (every read sees the most recent write), Availability (A) (every non-failing node returns a response), and Partition Tolerance (P) (the cluster continues operating despite network splits). Because network partitions are unavoidable in distributed systems, architects choose between CP systems (favoring consistency) and AP systems (favoring availability). AP systems typically follow the BASE philosophy: Basically Available, Soft state, and Eventual consistency.
14.2 Four Major NoSQL Data Models
- Key-Value Stores (e.g., Redis, Amazon DynamoDB): Store opaque values indexed by unique keys. Extremely fast lookups for session caches, shopping carts, and leaderboards.
- Document Stores (e.g., MongoDB, CouchDB): Store self-describing JSON/BSON documents in collections without a fixed schema, supporting nested arrays and rich secondary indexes.
- Column-Family / Wide-Column Stores (e.g., Apache Cassandra, HBase): Organize data into row keys with dynamic, sparse column families optimized for high-throughput time-series and write-heavy workloads.
- Graph Databases (e.g., Neo4j): Store entities as nodes and relationships as first-class edges with properties, executing multi-hop social-network, fraud-ring, and recommendation traversals in milliseconds.
| Feature | Relational DBMS (SQL) | NoSQL Databases |
|---|---|---|
| Schema | Fixed, predefined schema (schema-on-write). | Dynamic, flexible schema (schema-on-read). |
| Scaling | Primarily vertical scaling (scale-up). | Primarily horizontal scaling / sharding (scale-out). |
| Transactions | Strict ACID guarantees across multi-row joins. | Typically BASE / eventual consistency (ACID per document). |
| Query Language | Standardized declarative SQL with joins. | Vendor APIs, JSON query DSLs, Cypher (graph), CQL. |
// Insert, Query, Update, and Delete in MongoDB
db.students.insertOne({ rollNo: 1, name: "Arjun Menon", dept: "BCA", marks: 88.5 });
db.students.find({ dept: "BCA", marks: { $gte: 80 } }).sort({ marks: -1 });
db.students.updateOne({ rollNo: 1 }, { $inc: { marks: 2.0 } });
db.students.deleteOne({ rollNo: 99 });14.3 Complete SQL Lab Exercises (Part A & Part B Case Studies)
The following verified SQL script implements all twelve Part A laboratory exercises using a unified COLLEGE_DB schema covering DDL, DML, keys, constraints, pattern matching, BETWEEN, aggregates, ordering, GROUP BY, views, and stored procedures.
-- Lab 1, 3, 4: Create, Alter, Drop tables with Keys and All Constraints
CREATE TABLE DEPT (
DeptCode VARCHAR(10) PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE STUDENT (
RollNo INT PRIMARY KEY,
SName VARCHAR(60) NOT NULL,
Email VARCHAR(80) UNIQUE,
Age INT CHECK (Age >= 17),
Marks DECIMAL(5,2) DEFAULT 0.00 CHECK (Marks BETWEEN 0 AND 100),
DeptCode VARCHAR(10),
FOREIGN KEY (DeptCode) REFERENCES DEPT(DeptCode) ON DELETE CASCADE
);
ALTER TABLE STUDENT ADD City VARCHAR(40);
-- Lab 2: Insert, Update, and Delete records
INSERT INTO DEPT VALUES ('BCA', 'Computer Applications'), ('CS', 'Computer Science');
INSERT INTO STUDENT (RollNo, SName, Email, Age, Marks, DeptCode, City) VALUES
(1, 'Arjun Menon', '[email protected]', 19, 88.5, 'BCA', 'Kollam'),
(2, 'Sneha Pillai', '[email protected]', 20, 92.0, 'BCA', 'Trivandrum'),
(3, 'Karthik Raj', '[email protected]', 19, 74.0, 'CS', 'Kochi');
UPDATE STUDENT SET Marks = Marks + 2.5 WHERE RollNo = 3;
DELETE FROM STUDENT WHERE RollNo = 99;
-- Lab 5, 6, 8, 9: Substring comparison, BETWEEN, Range, and Ordering
SELECT RollNo, SName, Marks FROM STUDENT
WHERE SName LIKE 'A%' AND Marks BETWEEN 70 AND 95
ORDER BY Marks DESC, SName ASC;
-- Lab 7 & 10: Aggregate functions and GROUP BY
SELECT DeptCode, COUNT(*) AS TotalStudents, AVG(Marks) AS AvgMarks,
MIN(Marks) AS MinMarks, MAX(Marks) AS MaxMarks, SUM(Marks) AS SumMarks
FROM STUDENT
GROUP BY DeptCode
HAVING COUNT(*) >= 1;
-- Lab 11: Create and Delete View
CREATE VIEW TOP_SCORERS AS
SELECT RollNo, SName, Marks FROM STUDENT WHERE Marks >= 85;
SELECT * FROM TOP_SCORERS;
DROP VIEW TOP_SCORERS;
-- Lab 12: Stored Procedure Usage
DELIMITER //
CREATE PROCEDURE GetDeptStudents(IN p_dept VARCHAR(10))
BEGIN
SELECT RollNo, SName, Marks FROM STUDENT WHERE DeptCode = p_dept;
END //
DELIMITER ;
CALL GetDeptStudents('BCA');14.4 Part B Case Study: Hospital Management & Railway Reservation SQL Queries
In addition to designing the ER diagram and normalizing schemas to 3NF/BCNF, Part B laboratory work requires executing analytical queries across the resulting multi-table schemas. The following listing illustrates realistic operational queries on both case studies:
-- 1. Hospital: Total billing amount per admitted patient along with ward type
SELECT p.PatientID, CONCAT(p.FirstName, ' ', p.LastName) AS PatientName,
w.WardType, COALESCE(SUM(b.Amount), 0) AS TotalBill
FROM PATIENT p
LEFT JOIN WARD w ON p.WardNo = w.WardNo
LEFT JOIN BILL_ITEM b ON p.PatientID = b.PatientID
GROUP BY p.PatientID, p.FirstName, p.LastName, w.WardType
ORDER BY TotalBill DESC;
-- 2. Hospital: Doctors who have treated more than 5 distinct patients
SELECT d.DoctorID, d.DocName, d.Specialization, COUNT(DISTINCT t.PatientID) AS PatientsTreated
FROM DOCTOR d
JOIN TREATS t ON d.DoctorID = t.DoctorID
GROUP BY d.DoctorID, d.DocName, d.Specialization
HAVING COUNT(DISTINCT t.PatientID) > 5;
-- 3. Railway: Full route timetable for Train 16302 ordered by stop sequence
SELECT r.SeqNo, s.StationCode, s.StationName, s.City, r.ArrivalTime, r.DepartureTime
FROM ROUTE_STOP r
JOIN STATION s ON r.StationCode = s.StationCode
WHERE r.TrainNo = 16302
ORDER BY r.SeqNo ASC;
-- 4. Railway: Total confirmed revenue per train for a given journey date
SELECT tr.TrainNo, tr.TrainName, COUNT(tk.PNR) AS ConfirmedTickets,
SUM(tk.TotalFare) AS Revenue
FROM TRAIN tr
JOIN TICKET tk ON tr.TrainNo = tk.TrainNo
WHERE tk.JourneyDate = '2026-12-15' AND tk.BookingStatus = 'CONFIRMED'
GROUP BY tr.TrainNo, tr.TrainName
ORDER BY Revenue DESC;14.5 Summary Comparison of Concurrency Control & Recovery Techniques
| Mechanism | Core Technique | Guarantee Provided |
|---|---|---|
| Strict 2PL | Acquire S/X locks; hold X locks until commit/abort. | Conflict serializability and cascadeless (strict) schedules. |
| Timestamp Ordering | Assign unique start timestamps; abort conflicting out-of-order ops. | Deadlock-free conflict serializability (may suffer starvation). |
| MVCC | Maintain multiple committed versions per tuple; snapshot reads. | Readers never block writers and writers never block readers. |
| WAL + Checkpoints | Flush undo/redo log records to disk before dirty data pages. | Atomicity (Undo) and Durability (Redo) across system crashes. |
13.4 Worked Serializability & Precedence Graph Example
Consider two concurrent transactions and operating on bank accounts A and B under an interleaved schedule :
- :
read(A);A := A - 500;write(A) - :
read(A);write(A) - :
read(B);B := B + 500;write(B) - :
read(B);write(B)
To test Conflict Serializability, we draw a precedence graph with nodes and :
- On item
A, executeswrite(A)before executesread(A)andwrite(A)→ add directed edge . - On item
B, executeswrite(B)before executesread(B)andwrite(B)→ confirms edge .
Because the precedence graph has only and contains no cycle, schedule is conflict serializable and equivalent to the serial execution .
By contrast, if had executed read(B) and write(B) before executed read(B), we would add edge , creating the cycle —proving the schedule is not conflict serializable.
13.5 SQL Transaction Isolation Levels
The ANSI SQL standard defines four isolation levels allowing developers to balance concurrency throughput against anomaly protection:
| Isolation Level | Dirty Read | Non-Repeatable Read | Phantom Read |
|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible |
| READ COMMITTED | Prevented | Possible | Possible |
| REPEATABLE READ | Prevented | Prevented | Possible (in standard SQL) |
| SERIALIZABLE | Prevented | Prevented | Prevented |
14.6 Additional NoSQL Examples: Redis Key-Value & Neo4j Cypher
To illustrate how non-relational engines model data differently from SQL tables, consider caching a user session in Redis (Key-Value) and querying friend recommendations in Neo4j (Graph):
-- 1. Redis Key-Value Store (Session Caching with TTL expiration)
SET session:user:101 "{ 'name': 'Ananya', 'role': 'Admin' }" EX 3600
GET session:user:101
INCR page_views:home
-- 2. Neo4j Graph Database (Cypher: Find friends-of-friends not yet connected)
MATCH (u:Student {name: 'Arjun'})-[:KNOWS]->(friend)-[:KNOWS]->(fof:Student)
WHERE NOT (u)-[:KNOWS]->(fof) AND u <> fof
RETURN DISTINCT fof.name AS SuggestedConnection;14.7 Database Backup, Recovery, and Performance Tuning Checklist
In production environments, database administrators combine security, transaction recovery, and physical tuning into a unified operational discipline:
- 3-2-1 Backup Rule: Maintain at least three copies of critical database backups across two different media types, with at least one encrypted copy stored off-site or in immutable cloud object storage.
- Point-in-Time Recovery (PITR): Pair nightly full/incremental snapshots with continuous Write-Ahead Log (WAL) archiving so a database can be restored to any exact second prior to an accidental
DROP TABLEor ransomware event. - Execution Plan Analysis (
EXPLAIN ANALYZE): Inspect query plans regularly to replace costly full-table sequential scans with B+ tree index scans, eliminate unnecessary sorting, and keep table cardinality statistics fresh.
14.8 Physical Storage Internals: B+ Tree Indexes and Hashing
To understand why physical database design decisions dramatically affect query latency, it helps to examine the two dominant index structures used inside storage engines:
- B+ Tree Index: A balanced multi-way search tree where all actual data pointers (or records, in a clustered index) reside exclusively in the leaf nodes, and leaf nodes are linked together in a doubly-linked list. Internal nodes store only routing keys and child pointers, achieving high fan-out (typically 100–500 children per page). Consequently, even a table with 100 million rows requires only 3–4 disk I/O operations to locate any key, and linked leaves make range queries (
BETWEEN,>,ORDER BY) extraordinarily fast. - Static and Extendible Hashing: Applies a hash function to map a search key directly to a disk bucket address in average time. Hashing excels at exact-match equality lookups (
WHERE RollNo = 101) but cannot support range queries efficiently because adjacent key values scatter across unrelated buckets.
14.9 Deadlock Handling: Detection vs. Prevention
When two transactions wait indefinitely for locks held by each other (for example, holds X(A) and requests X(B) while holds X(B) and requests X(A)), a deadlock occurs. DBMS engines handle deadlocks in two ways:
- Deadlock Detection & Recovery: The lock manager periodically constructs a directed Wait-For Graph where an edge means is waiting for a lock held by . Any cycle indicates a deadlock; the engine selects a victim transaction (usually the youngest or one with fewest writes) and aborts it to break the cycle.
- Deadlock Prevention: Assigns each transaction a unique start timestamp . Under Wait-Die (non-preemptive), an older transaction may wait for a younger one, but a younger transaction requesting a lock held by an older one aborts ("dies"). Under Wound-Wait (preemptive), an older transaction forces ("wounds") a younger holder to abort, while a younger transaction waits for an older one. Both guarantee zero cycles and zero starvation.
14.10 Distributed Databases, Replication, and Sharding
Enterprise applications serving millions of global users outgrow a single database server. Architects scale horizontally using two complementary techniques:
- Replication (Leader-Follower / Multi-Leader): Copies identical data across multiple nodes so read queries can be load-balanced across read replicas and hardware failures trigger automatic failover.
- Sharding (Horizontal Partitioning): Splits a massive table by a shard key (such as
CustomerID % 4or geographic region) across independent server nodes, distributing both storage and write throughput linearly across the cluster.
14.11 Complete Practical Reference: SQL Constraints, Clauses & NoSQL Mapping
To consolidate practical laboratory skills alongside theoretical architecture, the following quick-reference matrix maps common relational SQL operations to their MongoDB Document Store equivalents:
| Operation | Relational SQL | MongoDB Document API |
|---|---|---|
| Create / Insert | INSERT INTO STUDENT VALUES (...) |
db.students.insertOne({ ... }) |
| Filter & Project | SELECT SName, Marks FROM STUDENT WHERE Dept='BCA' |
db.students.find({ dept: 'BCA' }, { name: 1, marks: 1 }) |
| Sort & Limit | ORDER BY Marks DESC LIMIT 5 |
.sort({ marks: -1 }).limit(5) |
| Update | UPDATE STUDENT SET Marks = Marks + 5 WHERE RollNo = 1 |
db.students.updateOne({ rollNo: 1 }, { $inc: { marks: 5 } }) |
| Aggregate / Group | SELECT Dept, AVG(Marks) FROM STUDENT GROUP BY Dept |
db.students.aggregate([{ $group: { _id: '$dept', avg: { $avg: '$marks' } } }]) |
| Delete | DELETE FROM STUDENT WHERE RollNo = 99 |
db.students.deleteOne({ rollNo: 99 }) |
14.12 Choosing Between SQL and NoSQL in Modern Architectures
Modern enterprise systems rarely rely exclusively on one paradigm; instead, they adopt Polyglot Persistence, selecting the storage engine best matched to each subsystem:
- Choose Relational SQL (PostgreSQL, MySQL, Oracle): For financial ledgers, inventory orders, student registrations, and healthcare billing where multi-row ACID transactions, strict referential integrity, and complex ad-hoc joins are non-negotiable.
- Choose Key-Value (Redis): For sub-millisecond session tokens, API rate limiting, and real-time leaderboards.
- Choose Document Store (MongoDB): For product catalogs with varying attributes, content management systems, and event logs.
- Choose Column-Family (Cassandra): For high-velocity IoT sensor telemetry and write-heavy time-series ingestion across data centers.
- Choose Graph Database (Neo4j): For fraud-detection rings, social recommendations, and network topology routing.
14.13 Worked Transaction Recovery Trace (WAL Undo / Redo)
To see how Write-Ahead Logging (WAL) guarantees both Atomicity and Durability after a sudden power failure, consider a log sequence recorded before a crash:
<T1, START>→<T1, A, 1000, 900>(old=1000, new=900) →<T1, B, 500, 600>→<T1, COMMIT><CHECKPOINT (T2)>(T1 already committed; T2 active)<T2, C, 300, 250>→ SYSTEM CRASH BEFORE T2 COMMITS
Upon restart, the recovery manager executes two passes over the WAL:
- Redo Pass (Forward from Checkpoint): Replays
<T1, COMMIT>effects if any dirty pages were not yet flushed, ensuring Durability (though T1 committed before the checkpoint, any transaction committing after the checkpoint would be redone). - Undo Pass (Backward for Uncommitted Active Transactions): Since
T2has noCOMMITrecord in the log, its write onCis rolled back to its old value300, and<T2, ABORT>is appended, ensuring Atomicity.
14.14 Comprehensive Security Hardening Checklist for Production DBMS
Deploying a relational or NoSQL database in production requires defense-in-depth across network, identity, query, and storage layers:
- Network Isolation: Bind the database engine exclusively to private VPC subnets; never expose database ports (3306, 5432, 27017) directly to the public internet.
- Encrypted Transport & Storage: Enforce TLS 1.3 for all client-server connections and enable Transparent Data Encryption (TDE) for data files, WAL logs, and automated backups.
- Least-Privilege Service Accounts: Application servers should connect using restricted database roles possessing only
SELECT,INSERT,UPDATE, andDELETEon application tables—never superuser/DBA credentials. - Parameterized Queries Everywhere: Ban string concatenation in SQL construction across all backend codebases to eliminate SQL Injection permanently.
- Automated Patching & Audit Alerts: Apply vendor security patches promptly and forward DDL/privilege-change audit logs to an immutable SIEM system.
14.15 Practical SQL Lab Verification Checklist
Before submitting Part A and Part B laboratory records, students should verify five essential execution invariants in their SQL environment:
- Constraint Enforcement Tests: Intentionally run a negative test (such as inserting a negative age or duplicate email) to confirm
CHECKandUNIQUEconstraints reject invalid tuples. - Referential Integrity Verification: Test deleting a parent department row to observe
ON DELETE CASCADEorON DELETE SET NULLbehavior in child rows. - Null-Safe Aggregations: Compare
COUNT(*)againstCOUNT(column)on a table containing at least oneNULLvalue to confirm aggregate behavior. - View & Procedure Execution: Verify that dropping a view leaves base table tuples untouched, and invoke stored procedures with multiple parameter values using
CALL. - Normalized Case Study Queries: Run multi-table
JOINandGROUP BYqueries across the Hospital and Railway schemas to confirm lossless data reconstruction.
University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 3 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Database Management (University of Kerala BCA Sem 3)
Database Management (UK3DSCCAP201 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in database management. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Database Management Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to Database Systems & Relational Model
A database is an organized, persistent, and self-describing collection of logically related data designed to model some real-world enterprise—such as university enrollments, banking ledgers, hospital patient records, or railway reservations. A Database Management System (DBMS) is a general-purpose software suite that enables users and application programs to define, construct, manipulate, share, and protect databases across concurrent workloads.
Structured Query Language (SQL)
Structured Query Language (SQL) is the universal declarative language for relational database management systems, standardized jointly by ANSI and ISO. Unlike imperative programming languages where the developer specifies step-by-step loops and pointer traversals, SQL lets the user declare what result set is desired, while the DBMS query optimizer determines the optimal physical execution plan. Every relational table created via DDL specifies column names, standard SQL data types, and declarative integrity constraints enforced automatically on every write:
Database Design Using the ER Model
Designing a large enterprise database requires systematic conceptual modeling before writing a single CREATE TABLE statement. The database design lifecycle progresses through six structured phases: Introduced by Peter Chen, the Entity-Relationship (ER) model views the real world as a collection of basic objects called entities and associations among them:
Normalization and Database Design Process
A poorly structured relational schema—such as combining all attributes of INSTRUCTOR and DEPARTMENT into a single wide table INST_DEPT(ID, Name, Salary, DeptName, Building, Budget) —causes severe operational anomalies: To eliminate anomalies safely, we decompose large relations into smaller ones.
Security, Transactions, NoSQL & SQL Lab
Database security protects stored data and DBMS infrastructure against unauthorized disclosure, improper modification, and denial of service. It rests on the CIA Triad: Confidentiality (preventing unauthorized reading of sensitive records), Integrity (preventing unauthorized or accidental alteration), and Availability (ensuring authorized users have reliable, timely access). -- 1.
Core Curriculum & Key Topics
- Database Systems, Architecture, and View of Data
- 1 Database Systems and the Purpose of a DBMS
- 2 View of Data: Abstraction, Instances, Schemas, and Data Independence
- 3 Database Languages
- 4 Database Design, Database Engine, and System Architecture
- 5 Database Users and Database Administrator (DBA)
- Data Models and the Relational Model
- 1 Classification of Data Models
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of database management.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Database Management
The evaluation framework for Database Management (UK3DSCCAP201) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK3DSCCAP201 (Database Management) examination: 1. Draw Clear Diagrams & Step-by-Step Traces: Illustrate trees, graphs, ER schemas, normalization tables, or ML pipeline diagrams neatly alongside dry-run traces. 2. State Complexity & Mathematical Formulas Explicitly: Include time/space complexity (Big-O notation), SQL query syntax, or model evaluation metrics (precision, recall, accuracy) accurately. 3. Compare Algorithms & Models in Tables: Use structured comparison tables (e.g., supervised vs. unsupervised, BFS vs. DFS, B-Tree vs. B+ Tree) for Part B analytical questions. 4. Allocate Time Strategically: Dedicate 25 minutes to Part A definitions, 50 minutes to Part B derivations and query/algorithm traces, and 75 minutes to Part C comprehensive problems.
Exam Preparation & Study Guides — Database Management
What is Database System & Purpose of DBMS and why is it important in Database Management?
A database is an organized, persistent collection of logically related data, and a Database Management System (DBMS) is general-purpose software for defining, constructing, manipulating, sharing, and protecting it, overcoming seven major flaws of traditional file-processing systems.
What is Data Models and why is it important in Database Management?
Conceptual frameworks for describing data structures, relationships, and constraints across five major paradigms.
What is Set Operations, Null Values & Three-Valued Logic and why is it important in Database Management?
SQL combines query results using set operators and evaluates missing values using three-valued logic (TRUE, FALSE, UNKNOWN).
What is Attribute Taxonomy & Latest Representations and why is it important in Database Management?
Attributes describe entity properties across six structural categories in Chen, UML, and Crow's Foot notations.
What are the core elements of Features of Good Relational Design & Anomalies in Database Management?
Combining unrelated entity attributes into one wide table causes redundancy and three operational anomalies fixed by lossless, dependency-preserving decomposition.
What is the official course code and credit structure for Database Management at University of Kerala?
Database Management carries the official course code UK3DSCCAP201 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Database Management?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Database Management (UK3DSCCAP201) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 3 Subjects
Browse study notes for other courses in BCA Sem 3:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.