Course code: BCA202 (earlier catalog reference: CACS255)
Semester: 3 (the earlier catalog placed the related course in Semester 4)
Credits: 3
Class load: 6 Hrs./Week (Theory: 3 Hrs., Tutorial: 1 Hr., Practical: 2 Hrs.)


Course Overview

A Database Management System (DBMS) is software that stores, retrieves, and manages structured data for many users simultaneously. Almost every modern application — a bank, an e-commerce site, a hospital, a university — relies on a DBMS. This course teaches you how data is modelled, stored, queried, and protected.

You will learn the relational model (the dominant model used by MySQL, PostgreSQL, SQL Server, and Oracle), write SQL queries from simple SELECT statements to multi-table JOINs and subqueries, design databases using entity-relationship diagrams and normalization, and understand how transactions maintain data integrity in a multi-user environment.

Curriculum alignment note: This guide adapts units and teaching hours from the earlier CACS255 outline in semester 4. The TU 2025 PDF lists BCA202 in semester 3 but has no detailed numbered unit outline there. Unit alignment with 2025 is unverified; enrichment topics are BCA Nepal study material, not TU requirements.


Learning Outcomes

  1. Explain the objectives, importance, merits, and demerits of a DBMS.
  2. Draw and interpret ER diagrams including weak entities, generalization, and aggregation.
  3. Convert ER diagrams to relational tables.
  4. Apply relational algebra operations (select, project, join, union, set difference).
  5. Normalize relations to 1NF, 2NF, 3NF, BCNF, and 4NF.
  6. Write DDL statements to create, alter, and drop databases and tables with constraints.
  7. Write DML statements including SELECT with WHERE, ORDER BY, GROUP BY, JOINS, and subqueries.
  8. Create and use views, stored procedures, and triggers.
  9. Explain transaction ACID properties, isolation levels, deadlocks, and lock-based concurrency control.
  10. Describe query processing, optimization, database security, and access control mechanisms.

Unit 1: Introduction to DBMS

Teaching hours: 3

1.1 Introduction

Before databases, applications stored data in flat files. Each application maintained its own files, leading to data redundancy (same data stored multiple times) and inconsistency (different copies containing different values). A DBMS solves these problems by providing a single, controlled repository.

A database is an organized collection of related data. A DBMS is the software that manages that database — it handles storage, retrieval, security, concurrency, and backup.

Examples of DBMS products:

Type Products
Relational (RDBMS) MySQL, PostgreSQL, Oracle, SQL Server, SQLite
NoSQL document MongoDB, CouchDB
NoSQL key-value Redis, DynamoDB
NoSQL column-family Cassandra, HBase

1.2 Objectives of DBMS

  1. Data independence — application logic separated from physical storage
  2. Minimal redundancy — store each fact once; derive copies when needed
  3. Data consistency — changes propagate automatically; no conflicting copies
  4. Data sharing — multiple users and applications access the same data concurrently
  5. Data security — control who can read, write, or delete data
  6. Data integrity — enforce rules to prevent invalid data
  7. Backup and recovery — restore data after failure

1.3 Importance of DBMS

Large organizations need to manage millions of records reliably. A DBMS provides:

  • Fast queries across large datasets via indexes
  • Concurrent access by thousands of users without data corruption
  • Recovery from hardware failure without data loss
  • Audit trails for compliance and security

1.4 Merits and Demerits

Merits Demerits
Reduces redundancy High initial cost (software licensing)
Enforces data consistency Complex setup and administration
Multi-user concurrent access Requires skilled DBA
Security and access control Performance overhead for simple applications
Backup, recovery, audit Single point of failure without replication

1.5 Applications of DBMS

  • Banking: account transactions, loan management
  • Airlines: reservations, flight scheduling
  • Universities: student records, course enrollment
  • E-commerce: product catalog, order management
  • Healthcare: patient records, prescriptions

Key Terms — Unit 1

  • Database — organized collection of related data
  • DBMS — software managing database storage, retrieval, and control
  • Data redundancy — same data stored in multiple places
  • Data independence — separating logical structure from physical storage

Unit 2: Database Design, Architecture and Model

Teaching hours: 6

2.1 Database Design Overview and View of Data

Database design moves through three levels of abstraction:

  1. Physical level — how data is actually stored on disk (files, blocks, indexes)
  2. Logical level — what data is stored and the relationships among it (tables, keys)
  3. View level — a subset of the database tailored for a particular user or application

This three-level separation enables data independence: you can reorganize physical storage without changing the logical schema, and you can change the logical schema without changing user views (within limits).

2.2 Three-Level Database Architecture (ANSI/SPARC)

graph TD
    A[External Level<br/>User Views] --> B[Conceptual Level<br/>Logical Schema]
    B --> C[Internal Level<br/>Physical Storage]

The ANSI/SPARC three-level architecture separates how users see data (external), how data is logically organised (conceptual), and how it is physically stored (internal). Changes at one level do not require changes at other levels, providing data independence.

Level Description Example
External Individual user's view A student sees only their grades
Conceptual Complete logical structure Full Students table with all columns
Internal Physical storage details B-tree index on student_id on disk

2.3 Database Languages

Language Stands for Purpose Example
DDL Data Definition Language Define/modify schema structure CREATE TABLE, ALTER TABLE
DML Data Manipulation Language Add, modify, delete, retrieve data INSERT, UPDATE, DELETE, SELECT
DCL Data Control Language Control access and permissions GRANT, REVOKE
TCL Transaction Control Language Manage transactions COMMIT, ROLLBACK, SAVEPOINT
QBE Query By Example Visual query tool, fill-in-the-blank grids Used in Microsoft Access

Swipe to see all columns

2.4 Data Models

A data model is a conceptual framework describing how data is structured and related.

Model Structure Used in
Hierarchical Tree-like parent-child IBM IMS (legacy)
Network Graph (many-to-many directly) CODASYL databases
Relational Tables (relations) MySQL, Oracle, PostgreSQL
ER model Entities and relationships Design phase (conceptual)
Object-based Objects with methods Object databases (Versant)

Relational model dominates because it is mathematically clean (based on set theory), supports ad-hoc queries via SQL, and provides excellent tool support.

2.5 Entity-Relationship (ER) Diagram

An ER diagram is a conceptual diagram showing entities (things), their attributes, and the relationships between them.

Key symbols:

Symbol Meaning
Rectangle Entity (e.g., Student)
Ellipse Attribute (e.g., StudentID)
Double ellipse Multivalued attribute (e.g., PhoneNumbers)
Dashed ellipse Derived attribute (e.g., Age derived from DOB)
Diamond Relationship (e.g., Enrolls)
Double rectangle Weak entity (e.g., Dependant)
Double diamond Identifying relationship

Cardinality notations:

  • 1:1 — one-to-one (one person has one passport)
  • 1:N — one-to-many (one teacher teaches many students)
  • M:N — many-to-many (students enroll in many courses; courses have many students)

ER Diagram Example:

erDiagram
    STUDENT {
        int StudentID PK
        string Name
        string Email
    }
    COURSE {
        int CourseID PK
        string Title
        int Credits
    }
    ENROLLMENT {
        int StudentID FK
        int CourseID FK
        date EnrollDate
        string Grade
    }
    STUDENT ||--o{ ENROLLMENT : "enrolls in"
    COURSE ||--o{ ENROLLMENT : "has"

Each STUDENT can enroll in many COURSEs, and each COURSE can have many STUDENTs enrolled. The ENROLLMENT entity captures the relationship with additional attributes (EnrollDate, Grade).

2.6 Weak Entity Sets

A weak entity cannot be identified by its own attributes alone — it depends on a related strong entity (its identifying entity).

Example: A DEPENDANT (child of an employee) has no unique ID of its own. It is identified by its name plus the employee it belongs to. The relationship between EMPLOYEE and DEPENDANT is an identifying relationship.

Discriminator: The partial key of a weak entity that distinguishes it among all dependants of the same employee (e.g., DependantName).

2.7 Generalization and Specialization

Generalization: Combine similar entities into a higher-level entity.

  • SAVINGS_ACCOUNT and CURRENT_ACCOUNT generalize to ACCOUNT.

Specialization (top-down): Divide an entity into sub-entities with specific attributes.

  • PERSON specializes into EMPLOYEE and STUDENT.

Aggregation: Treat a relationship as a higher-level entity so it can participate in another relationship.

  • Example: A WORKS_ON relationship between EMPLOYEE and PROJECT can itself participate in a MANAGES relationship with MANAGER.

2.8 Converting ER Diagrams to Tables

Rules:

  1. Each strong entity becomes a table; its attributes become columns; primary key is the entity's key.
  2. Each weak entity becomes a table with the discriminator + primary key of the identifying entity as combined primary key.
  3. A 1:N relationship: add the primary key of the "1" side as a foreign key in the "N" side table.
  4. A M:N relationship: create a new junction table with foreign keys to both entities; additional relationship attributes become columns in the junction table.
  5. A 1:1 relationship: add the primary key of one entity as a foreign key in the other's table (or merge them if participation is total on both sides).

Example — converting the ER diagram above:

CREATE TABLE Student (
    StudentID INT PRIMARY KEY,
    Name      VARCHAR(100),
    Email     VARCHAR(100)
);

CREATE TABLE Course (
    CourseID  INT PRIMARY KEY,
    Title     VARCHAR(200),
    Credits   INT
);

CREATE TABLE Enrollment (          -- junction table for M:N
    StudentID  INT REFERENCES Student(StudentID),
    CourseID   INT REFERENCES Course(CourseID),
    EnrollDate DATE,
    Grade      CHAR(2),
    PRIMARY KEY (StudentID, CourseID)
);

Key Terms — Unit 2

  • Three-level architecture — external, conceptual, internal
  • DDL / DML / DCL / TCL — categories of SQL statements
  • ER diagram — conceptual model of entities, attributes, and relationships
  • Weak entity — entity whose identity depends on a related strong entity
  • Generalization / Specialization — merging or splitting entities

Unit 3: Relational Database Model

Teaching hours: 4

3.1 Structure and Terminology

The relational model represents data as a collection of relations (tables).

Term Meaning
Relation A table with rows and columns
Tuple A row in a table (one record)
Attribute A column in a table (one field)
Domain The set of allowed values for an attribute (e.g., Age must be an integer 0–150)
Degree Number of attributes in a relation
Cardinality Number of tuples in a relation
Schema The structure definition (table name + attribute names + domains)
Instance The current set of tuples in a relation

Example — Students relation:

StudentID Name Age Major
101 Sita 20 BCA
102 Ram 21 BCA
103 Hari 19 BSc

Swipe to see all columns

Schema: Students(StudentID, Name, Age, Major)
Degree: 4, Cardinality: 3

3.2 Keys

Key Type Definition
Super key Any set of attributes that uniquely identifies a tuple
Candidate key A minimal super key (no proper subset is also a super key)
Primary key The chosen candidate key for a table; no NULLs allowed
Foreign key An attribute (or set) in one table that references the primary key of another table
Composite key A primary key made of two or more attributes
Alternate key A candidate key that was not chosen as the primary key

Example: In the Students table, StudentID is the primary key. Email could be an alternate candidate key if emails are unique.

In the Enrollment table (StudentID, CourseID) is a composite primary key, and each attribute is a foreign key to its respective table.

3.3 Relational Integrity Constraints

  • Entity integrity: No primary key attribute can be NULL.
  • Referential integrity: A foreign key value must either be NULL (if allowed) or must match a primary key value in the referenced table.
  • Domain constraint: Attribute values must come from their defined domain.

3.4 Relational Algebra

Relational algebra is the theoretical foundation of SQL queries. It operates on relations and produces relations.

Core operations:

Operation Symbol SQL equivalent Description
Select (σ) σ_condition(R) WHERE Returns rows satisfying a condition
Project (π) π_attrs(R) SELECT cols Returns only specified columns
Cartesian Product (×) R × S FROM R, S All combinations of rows
Union (∪) R ∪ S UNION Rows in R or S (removes duplicates)
Set Difference (−) R − S EXCEPT Rows in R but not in S
Natural Join (⋈) R ⋈ S JOIN … USING Join on matching attribute names
Outer Join R ⟕ S LEFT JOIN etc. Includes rows with no match, using NULLs

Swipe to see all columns

Examples using Students and Enrollment tables:

-- Select students in BCA
σ_(Major='BCA')(Students)
→ StudentID=101 Sita, StudentID=102 Ram

-- Project only Name and Major
π_(Name, Major)(Students)
→ (Sita, BCA), (Ram, BCA), (Hari, BSc)

-- Natural join Students with Enrollment
Students ⋈ Enrollment
→ Rows combining matching StudentID values

Key Terms — Unit 3

  • Tuple — a row; Attribute — a column
  • Primary key — unique, non-null identifier
  • Foreign key — references another table's primary key
  • Referential integrity — foreign key must reference an existing primary key
  • Relational algebra — set-based operations on relations

Unit 4: Database Normalization

Teaching hours: 4

4.1 Definition and Purpose

Normalization is the process of organizing attributes and tables to minimize redundancy and avoid update anomalies.

Anomalies in an unnormalized table:

Consider a table where student, course, and instructor info is all in one row:

StudentID CourseID Instructor InstructorPhone
101 CS201 Dr. Sharma 9800001
102 CS201 Dr. Sharma 9800001
101 CS202 Dr. Thapa 9800002

Swipe to see all columns

  • Insertion anomaly: Cannot record a new instructor without also recording a student.
  • Deletion anomaly: Deleting the only student in a course removes the instructor's record too.
  • Update anomaly: Changing Dr. Sharma's phone requires updating every row where she appears.

Normalization resolves these by decomposing tables until each table stores facts about exactly one subject.

4.2 Functional Dependencies

A functional dependency (FD) X → Y means: knowing the value of X uniquely determines the value of Y.

Example: StudentID → Name, Age, Major — knowing StudentID determines Name, Age, and Major.

Types:

  • Full FD: Y depends on the whole of X, not any subset (important for 2NF).
  • Partial FD: Y depends on only part of a composite key (violates 2NF).
  • Transitive FD: X → Y and Y → Z, so X → Z but Y is not a key (violates 3NF).

4.3 Normal Forms

First Normal Form (1NF)

Rule: Every attribute contains only atomic (indivisible) values. No repeating groups or multi-valued attributes.

Violation example: A PhoneNumbers column containing "9801, 9802" is not atomic.

Fix: Create a separate row for each phone number, or a separate PhoneNumbers table.

Second Normal Form (2NF)

Rule: Must be in 1NF, and every non-key attribute must be fully functionally dependent on the entire primary key (no partial dependencies).

Applies only when the primary key is composite.

Example violating 2NF:

StudentID CourseID Grade CourseName
101 CS201 A Data Structures

Swipe to see all columns

Primary key = (StudentID, CourseID). But CourseName depends only on CourseID (partial dependency).

Fix: Remove CourseName to a separate Course table.

Third Normal Form (3NF)

Rule: Must be in 2NF, and no non-key attribute should be transitively dependent on the primary key through another non-key attribute.

Example violating 3NF:

StudentID ZipCode City
101 44600 Kathmandu

StudentID → ZipCode → City. City is transitively dependent on StudentID through ZipCode.

Fix: Separate into Student(StudentID, ZipCode) and Location(ZipCode, City).

Boyce-Codd Normal Form (BCNF)

Rule: For every functional dependency X → Y, X must be a super key.

BCNF is stricter than 3NF. It eliminates certain anomalies 3NF allows when a table has overlapping candidate keys.

Example violating BCNF but in 3NF:

CourseID Instructor Room
CS201 Dr. Sharma R101
CS202 Dr. Thapa R102
CS201 Dr. Sharma R101

FDs: {CourseID, Instructor} → Room, but also Room → Instructor (each room is used by only one instructor). Room is not a super key, but it determines Instructor. Because Instructor is part of the candidate key {CourseID, Instructor}, it is a prime attribute, so the table is in 3NF — it violates BCNF only.

Fix: Split into CourseRoom(CourseID, Room) and RoomInstructor(Room, Instructor).

Fourth Normal Form (4NF)

Rule: Must be in BCNF, and no multi-valued dependencies (MVDs) exist.

A multi-valued dependency X →→ Y means: for each value of X, there is a set of Y values independent of all other attributes.

Example: An employee can have many skills and many hobbies. EmpID →→ Skill and EmpID →→ Hobby. Storing them together creates redundancy (every skill–hobby combination is repeated).

Fix: Separate into Employee_Skills(EmpID, Skill) and Employee_Hobbies(EmpID, Hobby).

4.4 Summary Table

Normal Form Rule Violations eliminated
1NF Atomic values, no repeating groups Multi-valued attributes
2NF No partial dependencies (on composite key) Partial FD anomalies
3NF No transitive dependencies Transitive FD anomalies
BCNF Every determinant is a super key Overlapping candidate key anomalies
4NF No multi-valued dependencies MVD anomalies

Key Terms — Unit 4

  • Functional dependency — X → Y: X uniquely determines Y
  • Partial dependency — non-key attribute depends on part of composite key (2NF violation)
  • Transitive dependency — non-key depends on non-key which depends on primary key (3NF violation)
  • BCNF — every determinant is a super key

Unit 4 Practice Questions

Q1. Given a table Order(OrderID, ProductID, ProductName, CustomerID, CustomerName, Qty), identify all anomalies and normalize it to 3NF.

Answer:

  • Partial dependency: ProductName depends only on ProductID; CustomerName depends only on CustomerID.
  • Decompose into:
    • Product(ProductID, ProductName)
    • Customer(CustomerID, CustomerName)
    • Order(OrderID, ProductID, CustomerID, Qty) with foreign keys to Product and Customer.
  • Check for transitive FDs in Order — none remain. Result is in 3NF.

Unit 5: Creating and Altering Database and Tables (SQL)

Teaching hours: 6

5.1 Introduction to SQL

SQL (Structured Query Language) is the standard language for relational databases. It is declarative — you describe what you want, not how to retrieve it. SQL is based on relational algebra and set theory.

SQL is divided into subcategories (DDL, DML, DCL, TCL) introduced in Unit 2.

Case sensitivity: SQL keywords are conventionally written in uppercase (SELECT, FROM) but are case-insensitive in most databases. Table and column names may be case-sensitive depending on the database and OS.

5.2 Creating a Database

-- Create a new database
CREATE DATABASE CollegeDB;

-- Use (switch to) the database
USE CollegeDB;

-- Drop (delete) the database permanently
DROP DATABASE CollegeDB;

Explanation:

  • CREATE DATABASE — DDL statement that initialises a new named database.
  • USE — switches the active database context (MySQL/SQL Server syntax).
  • DROP DATABASE — permanently removes the database and all its tables. Irreversible without backup.

5.3 Creating Tables with Constraints

CREATE TABLE Student (
    StudentID   INT           NOT NULL,
    Name        VARCHAR(100)  NOT NULL,
    Email       VARCHAR(150)  UNIQUE,
    DOB         DATE,
    Major       VARCHAR(50)   DEFAULT 'BCA',
    PRIMARY KEY (StudentID)
);

CREATE TABLE Course (
    CourseID    INT           NOT NULL,
    Title       VARCHAR(200)  NOT NULL,
    Credits     INT           CHECK (Credits > 0 AND Credits <= 6),
    PRIMARY KEY (CourseID)
);

CREATE TABLE Enrollment (
    StudentID   INT           NOT NULL,
    CourseID    INT           NOT NULL,
    Grade       CHAR(2),
    PRIMARY KEY (StudentID, CourseID),
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
    FOREIGN KEY (CourseID)  REFERENCES Course(CourseID)
);

Constraint explanations:

Constraint Purpose
NOT NULL Column must have a value; NULL is rejected
UNIQUE No two rows can have the same value in this column
PRIMARY KEY Uniquely identifies each row; implies NOT NULL and UNIQUE
FOREIGN KEY … REFERENCES Value must exist in the referenced table's primary key
CHECK (condition) Value must satisfy the given condition
DEFAULT value Provides a default value when none is specified on INSERT

5.4 Altering Tables

-- Add a new column
ALTER TABLE Student ADD COLUMN Phone VARCHAR(15);

-- Modify a column's type
ALTER TABLE Student MODIFY COLUMN Phone VARCHAR(20);

-- Drop a column
ALTER TABLE Student DROP COLUMN Phone;

-- Add a constraint after table creation
ALTER TABLE Student ADD CONSTRAINT chk_dob CHECK (DOB > '1990-01-01');

-- Drop a constraint
ALTER TABLE Student DROP CONSTRAINT chk_dob;

Keyword explanations:

  • ALTER TABLE — modifies an existing table's structure.
  • ADD COLUMN — appends a new column.
  • MODIFY COLUMN — changes a column's data type or constraints.
  • DROP COLUMN — removes a column and all its data.
  • ADD CONSTRAINT — adds a named constraint.

5.5 DROP Statement

DROP TABLE Enrollment;   -- deletes table structure and all data
DROP DATABASE CollegeDB; -- deletes the entire database

Common mistake: Using DROP TABLE instead of DELETE FROM when you only want to remove data, not the table itself. DROP removes the structure; DELETE removes rows.


Key Terms — Unit 5

  • DDL — CREATE, ALTER, DROP — changes structure
  • Constraint — rule enforced by the database on column values
  • NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT
  • Referential integrity — enforced by FOREIGN KEY constraint

Unit 6: Manipulating and Querying Data

Teaching hours: 8

This is the most exam-heavy unit. Every clause, keyword, and operator below appears frequently in exams.

6.1 Sample Schema and Data

Throughout this unit, the following schema and rows are used:

-- Students: StudentID, Name, Age, Major
INSERT INTO Student VALUES (101, 'Sita',  20, 'BCA');
INSERT INTO Student VALUES (102, 'Ram',   21, 'BCA');
INSERT INTO Student VALUES (103, 'Hari',  19, 'BSc');
INSERT INTO Student VALUES (104, 'Gita',  22, 'BCA');

-- Courses: CourseID, Title, Credits
INSERT INTO Course VALUES (1, 'Data Structures', 3);
INSERT INTO Course VALUES (2, 'Web Technology',  3);
INSERT INTO Course VALUES (3, 'DBMS',            3);

-- Enrollment: StudentID, CourseID, Grade
INSERT INTO Enrollment VALUES (101, 1, 'A');
INSERT INTO Enrollment VALUES (101, 2, 'B');
INSERT INTO Enrollment VALUES (102, 1, 'A');
INSERT INTO Enrollment VALUES (103, 3, 'C');

6.2 SELECT with FROM and WHERE

-- Full table: all rows, all columns
SELECT * FROM Student;
-- * means "all columns"

-- Specific columns
SELECT StudentID, Name FROM Student;

-- Filter with WHERE
SELECT Name, Age FROM Student WHERE Major = 'BCA';
-- WHERE filters rows; only BCA students returned

-- Multiple conditions
SELECT Name FROM Student WHERE Major = 'BCA' AND Age < 21;
-- AND: both conditions must be true
-- OR: either condition is true
-- NOT: negates a condition

-- LIKE operator (pattern matching)
SELECT Name FROM Student WHERE Name LIKE 'S%';
-- %: matches any sequence of characters
-- _: matches exactly one character
-- S%: matches Sita, Surendra, etc.

-- BETWEEN operator
SELECT Name FROM Student WHERE Age BETWEEN 19 AND 21;
-- Equivalent to: Age >= 19 AND Age <= 21; inclusive

-- IN operator
SELECT Name FROM Student WHERE Major IN ('BCA', 'BSc');
-- Equivalent to: Major = 'BCA' OR Major = 'BSc'

Expected results:

  • WHERE Major = 'BCA' → Sita (101), Ram (102), Gita (104)
  • WHERE Name LIKE 'S%' → Sita

6.3 ORDER BY and GROUP BY

-- ORDER BY: sort results
SELECT Name, Age FROM Student ORDER BY Age ASC;
-- ASC: ascending (default); DESC: descending

-- GROUP BY: aggregate rows with same value in a column
SELECT Major, COUNT(*) AS StudentCount
FROM Student
GROUP BY Major;
-- COUNT(*): counts rows in each group
-- AS StudentCount: gives the result column a name (alias)

-- Expected result:
-- Major | StudentCount
-- BCA   | 3
-- BSc   | 1

-- HAVING: filter groups (like WHERE but for aggregated groups)
SELECT Major, COUNT(*) AS StudentCount
FROM Student
GROUP BY Major
HAVING COUNT(*) > 1;
-- Keeps only groups where count exceeds 1
-- Result: BCA | 3

-- Aggregate functions: COUNT, SUM, AVG, MAX, MIN
SELECT AVG(Age) AS AvgAge, MAX(Age) AS MaxAge FROM Student;
-- AVG: arithmetic mean; MAX: highest value

Rule: Columns in SELECT must either be in GROUP BY or be wrapped in an aggregate function.

6.4 Retrieving Data from Multiple Tables (JOINs)

A JOIN combines rows from two tables based on a matching condition.

-- INNER JOIN: only rows with matches in both tables
SELECT s.Name, c.Title, e.Grade
FROM Student s
INNER JOIN Enrollment e ON s.StudentID = e.StudentID
INNER JOIN Course c     ON e.CourseID  = c.CourseID;

-- s, e, c are table aliases (shorthand)
-- ON specifies the join condition
-- Only enrolled students appear

Expected result:

Name  | Title            | Grade
Sita  | Data Structures  | A
Sita  | Web Technology   | B
Ram   | Data Structures  | A
Hari  | DBMS             | C
-- LEFT OUTER JOIN: all rows from left table; NULLs where no match in right
SELECT s.Name, e.CourseID
FROM Student s
LEFT JOIN Enrollment e ON s.StudentID = e.StudentID;
-- Gita (104) has no enrollment → CourseID will be NULL

-- RIGHT OUTER JOIN: all rows from right table
-- FULL OUTER JOIN: all rows from both tables (not supported in MySQL, use UNION)

-- CROSS JOIN: Cartesian product — every row of left × every row of right
SELECT s.Name, c.Title
FROM Student s
CROSS JOIN Course c;
-- 4 students × 3 courses = 12 rows
graph LR
    A[INNER JOIN<br/>only matching rows] 
    B[LEFT JOIN<br/>all left + matching right]
    C[RIGHT JOIN<br/>matching left + all right]
    D[FULL JOIN<br/>all rows from both]

6.5 Subqueries (Nested Queries)

A subquery is a SELECT statement inside another statement.

-- Subquery in WHERE: find students enrolled in course 1
SELECT Name FROM Student
WHERE StudentID IN (
    SELECT StudentID FROM Enrollment WHERE CourseID = 1
);
-- IN: StudentID must be in the set returned by the inner query
-- Inner query returns: {101, 102}
-- Result: Sita, Ram

-- Subquery with comparison operator
SELECT Name FROM Student
WHERE Age > (SELECT AVG(Age) FROM Student);
-- Returns students older than the average age
-- AVG(Age) = (20+21+19+22)/4 = 20.5
-- Result: Ram (21), Gita (22)

-- Correlated subquery: inner query references outer query's row
SELECT s.Name
FROM Student s
WHERE EXISTS (
    SELECT 1 FROM Enrollment e WHERE e.StudentID = s.StudentID
);
-- EXISTS: true if subquery returns any rows
-- Returns students who have at least one enrollment

6.6 INSERT, UPDATE, DELETE

-- INSERT: add one row
INSERT INTO Student (StudentID, Name, Age, Major)
VALUES (105, 'Maya', 20, 'BCA');

-- INSERT multiple rows
INSERT INTO Student VALUES
    (106, 'Suresh', 22, 'BSc'),
    (107, 'Meena',  21, 'BCA');

-- UPDATE: modify existing rows
UPDATE Student SET Age = 21 WHERE StudentID = 103;
-- SET specifies new value; WHERE limits which rows are changed
-- Without WHERE: ALL rows are updated — a common destructive mistake

-- DELETE: remove rows
DELETE FROM Student WHERE StudentID = 107;
-- Without WHERE: ALL rows are deleted (table structure remains)

Common mistakes:

  • UPDATE or DELETE without a WHERE clause changes/removes every row.
  • Always test with a SELECT using the same WHERE before running UPDATE/DELETE.

6.7 Views

A view is a saved SELECT query that behaves like a virtual table.

-- Create a view showing BCA students only
CREATE VIEW BCA_Students AS
SELECT StudentID, Name, Age
FROM Student
WHERE Major = 'BCA';

-- Query the view like a table
SELECT * FROM BCA_Students;

-- Update the view
CREATE OR REPLACE VIEW BCA_Students AS
SELECT StudentID, Name, Age, Email
FROM Student
WHERE Major = 'BCA';

-- Drop the view
DROP VIEW BCA_Students;

Benefits of views:

  • Security: expose only specific columns/rows to certain users
  • Simplify complex queries: hide join logic behind a view name
  • Logical independence: views remain useful after underlying table is restructured

Limitation: Most databases do not allow INSERT/UPDATE through complex views.


Key Terms — Unit 6

  • SELECT — retrieve data; FROM — specify table; WHERE — filter rows
  • GROUP BY — aggregate rows; HAVING — filter groups; ORDER BY — sort
  • JOIN — combine tables; INNER JOIN — matching rows only; LEFT JOIN — all left rows
  • Subquery — nested SELECT; EXISTS — true if subquery returns rows
  • View — stored query acting as a virtual table

Unit 7: Stored Procedures, Triggers, and Indexing

Teaching hours: 5

7.1 Stored Procedures

A stored procedure is a named, pre-compiled block of SQL (and procedural logic) stored in the database. It is called by name rather than re-parsed each time.

Benefits:

  • Performance: compiled once, executed many times
  • Reusability: shared across applications
  • Security: grant EXECUTE permission without granting direct table access
  • Reduced network traffic: one call instead of many SQL statements

Creating a Stored Procedure

-- Simple procedure with no parameters
CREATE PROCEDURE GetAllStudents()
BEGIN
    SELECT * FROM Student;
END;

-- Execute
CALL GetAllStudents();

Procedures with Parameters

CREATE PROCEDURE GetStudentByMajor(IN major_param VARCHAR(50))
BEGIN
    SELECT StudentID, Name
    FROM Student
    WHERE Major = major_param;    -- uses the input parameter
END;

-- Call with argument
CALL GetStudentByMajor('BCA');

Parameter types:

Type Direction Description
IN Caller → procedure Input value
OUT Procedure → caller Output value
INOUT Both directions Input that can be modified

Output Parameter Example

CREATE PROCEDURE CountStudents(IN major_param VARCHAR(50),
                               OUT total INT)
BEGIN
    SELECT COUNT(*) INTO total
    FROM Student
    WHERE Major = major_param;
END;

-- Call
CALL CountStudents('BCA', @count);
SELECT @count;    -- @count is a session variable

Altering and Dropping Procedures

DROP PROCEDURE IF EXISTS GetAllStudents;   -- drop first
CREATE PROCEDURE GetAllStudents()         -- then recreate (MySQL pattern)
BEGIN
    SELECT StudentID, Name FROM Student ORDER BY Name;
END;

Encryption

Some databases allow encrypting the procedure body so users can call it without viewing its source (WITH ENCRYPTION in SQL Server). The database stores an obfuscated version.

7.2 Triggers

A trigger is a stored procedure that runs automatically in response to INSERT, UPDATE, or DELETE on a table.

-- Trigger: log every new enrollment into an audit table
CREATE TRIGGER AfterEnrollInsert
AFTER INSERT ON Enrollment
FOR EACH ROW
BEGIN
    INSERT INTO EnrollmentLog (StudentID, CourseID, LogTime)
    VALUES (NEW.StudentID, NEW.CourseID, NOW());
END;

Keyword explanations:

  • AFTER INSERT — fires after a row is inserted (can also be BEFORE)
  • FOR EACH ROW — fires once per affected row
  • NEW — refers to the new row being inserted
  • OLD — refers to the row before UPDATE or DELETE

Trigger types:

Timing Event Use case
BEFORE INSERT Validate/modify data before saving
AFTER INSERT Log the action
BEFORE UPDATE Enforce business rules
AFTER UPDATE Notify other tables
BEFORE / AFTER DELETE Soft-delete, cascade

Trigger limitations:

  • Cannot be called directly
  • Cannot use COMMIT or ROLLBACK inside a trigger (in most databases)
  • Cascading triggers (trigger A fires trigger B) can cause infinite loops
  • Excessive triggers slow database performance

Disabling triggers (SQL Server):

DISABLE TRIGGER AfterEnrollInsert ON Enrollment;
ENABLE  TRIGGER AfterEnrollInsert ON Enrollment;

7.3 Indexing

An index is a separate data structure that maps key values to the row locations in a table, dramatically speeding up SELECT queries at the cost of slightly slower INSERT/UPDATE/DELETE and extra disk space.

Analogy: A book's index tells you which page number contains a topic. Without it, you read every page.

Creating and Dropping Indexes

-- Create an index on a single column
CREATE INDEX idx_student_major ON Student(Major);

-- Create a unique index (also enforces uniqueness)
CREATE UNIQUE INDEX idx_student_email ON Student(Email);

-- Multi-column (composite) index
CREATE INDEX idx_enroll_course ON Enrollment(CourseID, StudentID);

-- Drop an index
DROP INDEX idx_student_major ON Student;   -- MySQL syntax

Types of Indexes

Type Description
Ordered (clustered) Table rows physically sorted by the index key; at most one per table
Non-clustered Separate structure pointing to table rows; multiple allowed
Unique Enforces uniqueness; used for PRIMARY KEY and UNIQUE constraints
Composite Covers multiple columns; queries using those columns in order benefit

Multiple key access: A composite index on (CourseID, StudentID) speeds up queries that filter on CourseID alone or on (CourseID, StudentID) together, but not on StudentID alone (the leading column rule).


Key Terms — Unit 7

  • Stored procedure — named SQL block; IN / OUT / INOUT parameters
  • Trigger — fires automatically on DML events; NEW / OLD references
  • Index — data structure for fast lookup; clustered vs. non-clustered
  • Encryption — hiding procedure source code from unauthorized users

Unit 8: Query Processing and Security

Teaching hours: 5

8.1 Overview of Query Processing

When you submit a SQL query, the database engine goes through several stages:

flowchart LR
    A[SQL Query] --> B[Parser<br/>Syntax check]
    B --> C[Query Rewriter<br/>View expansion]
    C --> D[Query Optimizer<br/>Choose execution plan]
    D --> E[Execution Engine<br/>Run plan]
    E --> F[Result]

Query processing pipeline: a submitted SQL query is parsed for syntax, rewritten to expand views and simplify expressions, optimized to find the cheapest execution plan, then executed to produce results.

  1. Parser: Checks SQL syntax; produces a parse tree.
  2. Query Rewriter: Expands views, simplifies expressions.
  3. Query Optimizer: Generates candidate execution plans (e.g., use index vs. sequential scan); estimates cost of each; selects cheapest.
  4. Execution Engine: Executes the chosen plan.

8.2 Measuring Query Cost

Cost is typically measured in terms of disk I/O (number of block transfers), since disk access is the bottleneck.

Factors affecting cost:

  • Table size (number of blocks)
  • Availability and selectivity of indexes
  • Join order (which table to scan first)
  • Buffer pool size (how many blocks fit in RAM)

8.3 Selection, Sorting, and Joining

Selection strategies:

  • Linear scan: Read every block; O(b) where b = number of blocks. Used when no index exists.
  • Index scan: Use an index to jump directly to qualifying rows; O(log b + result size).

Sorting: External sort-merge for large tables:

  1. Split into sorted runs that fit in memory.
  2. Merge runs pairwise until one sorted file remains.

Join evaluation strategies:

  • Nested-loop join: For each row in R, scan all of S. Cost: O(|R| × |S|).
  • Sort-merge join: Sort both on the join key; merge. Cost: O(|R| log |R| + |S| log |S|).
  • Hash join: Build a hash table on the smaller relation; probe with the larger. Very fast when one relation fits in memory.

8.4 Query Optimization

The optimizer uses statistics (column cardinality, value distribution, table size) to estimate result sizes and pick the cheapest plan. Key techniques:

  • Predicate pushdown: Apply WHERE filters as early as possible to reduce data volume.
  • Join reordering: Join smallest tables first; left-deep vs. bushy join trees.
  • Index selection: Use an index when selectivity is high (fewer rows match).

8.5 Database Administrator (DBA) Roles and Responsibilities

The DBA is responsible for the DBMS installation, configuration, performance, security, backup, and recovery.

Responsibility Description
Schema design Create and maintain tables, indexes, views
User management Create accounts, assign roles and privileges
Performance tuning Monitor slow queries, add indexes, adjust configuration
Backup and recovery Regular backups; restore after failure
Security Enforce access control, encryption, auditing
Capacity planning Monitor growth; plan storage and hardware upgrades

8.6 Database Security

Security threats:

  • Unauthorized data reading (snooping)
  • Unauthorized data modification
  • Denial of service
  • SQL injection attacks

Types of security:

Level Description
OS-level File system permissions on data files
Network-level Firewall, SSL/TLS for data in transit
Database-level User accounts, role-based access control
Application-level Parameterized queries, input validation

8.7 Access Control

Discretionary Access Control (DAC):

The owner of a database object grants or revokes privileges to other users.

-- Grant SELECT and INSERT on Student to user 'teacher'
GRANT SELECT, INSERT ON Student TO teacher;

-- Allow teacher to pass the privilege to others
GRANT SELECT ON Student TO teacher WITH GRANT OPTION;

-- Revoke INSERT from teacher
REVOKE INSERT ON Student FROM teacher;

SQL privilege types: SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALL PRIVILEGES

Mandatory Access Control (MAC): Each database object has a classification level (Unclassified, Confidential, Secret, Top Secret) and each user has a clearance level. Users can only access objects at or below their clearance. The operating system enforces this — it cannot be overridden by individual grants.

Data Encryption:

  • At rest: Data files encrypted on disk (Transparent Data Encryption).
  • In transit: SSL/TLS between application and database server.
  • Column-level: Sensitive columns (passwords, credit card numbers) encrypted individually.

User Accounts and Database Audits: Auditing logs who accessed what data and when, enabling post-incident forensic analysis and regulatory compliance.


Key Terms — Unit 8

  • Query optimizer — chooses cheapest execution plan
  • DBA — database administrator; manages schema, users, performance, security
  • DAC — Discretionary Access Control; owner grants privileges
  • MAC — Mandatory Access Control; classification-based; OS-enforced
  • SQL injection — attacker inserts SQL into user input fields to manipulate queries

Unit 9: Transaction and Concurrency Control

Teaching hours: 4

9.1 Transaction Concept

A transaction is a logical unit of work: a sequence of SQL operations that must all succeed or all fail together.

Classic example — bank transfer of Rs. 500 from Account A to Account B:

BEGIN TRANSACTION;
    UPDATE Account SET Balance = Balance - 500 WHERE AccountID = 'A';
    UPDATE Account SET Balance = Balance + 500 WHERE AccountID = 'B';
COMMIT;

If the system crashes between the two updates, the half-completed transfer would leave Rs. 500 disappeared. The transaction ensures either both updates commit or neither does (via rollback on recovery).

9.2 ACID Properties

Property Meaning Implementation
Atomicity All or nothing — the transaction is indivisible Undo log (rollback)
Consistency Transaction takes the database from one valid state to another Constraints, triggers
Isolation Concurrent transactions appear to run serially Locking, MVCC
Durability Committed changes survive failures Redo log, write-ahead logging

9.3 Simple Transaction Model

BEGIN;                   -- start transaction
  INSERT INTO Orders ...;
  UPDATE Inventory ...;
COMMIT;                  -- make changes permanent

-- Or, if something goes wrong:
ROLLBACK;                -- undo all changes since BEGIN

SAVEPOINT: Allows partial rollback within a transaction.

BEGIN;
  INSERT ...;
  SAVEPOINT sp1;
  UPDATE ...;
  ROLLBACK TO sp1;   -- undo only the UPDATE; INSERT stays
COMMIT;              -- commit the INSERT

9.4 Transaction Isolation Levels

Isolation controls how visible uncommitted changes are to other concurrent transactions.

Level Dirty Read Non-repeatable Read Phantom Read
READ UNCOMMITTED Yes Yes Yes
READ COMMITTED No Yes Yes
REPEATABLE READ No No Yes
SERIALIZABLE No No No

Swipe to see all columns

Anomaly definitions:

  • Dirty read: T1 reads data that T2 has modified but not yet committed. T2 may roll back.
  • Non-repeatable read: T1 reads a row; T2 updates and commits it; T1 reads again and gets a different value.
  • Phantom read: T1 reads rows matching a condition; T2 inserts/deletes rows matching that condition and commits; T1 re-reads and finds different rows.

Higher isolation = fewer anomalies = more locking = lower concurrency. SERIALIZABLE is safest but slowest.

9.5 Lock-Based Protocol

Locks prevent conflicting concurrent access to the same data.

Lock Type Symbol Multiple holders? Meaning
Shared (S) S Yes Read-only; multiple transactions can hold S on the same item
Exclusive (X) X No Read-write; only one transaction can hold X

Swipe to see all columns

Compatibility:

S X
S ✓ ✗
X ✗ ✗

Two-Phase Locking (2PL):

  • Growing phase: Acquire locks; do not release any.
  • Shrinking phase: Release locks; do not acquire any.

2PL guarantees serializability — the schedule is equivalent to some serial execution.

9.6 Deadlock

A deadlock occurs when two or more transactions each hold a lock that the other needs, so neither can proceed.

T1 holds lock on A, waiting for B
T2 holds lock on B, waiting for A
→ Neither can progress

Detection: Build a wait-for graph. A cycle indicates a deadlock. The DBMS selects one transaction as the victim, rolls it back, and releases its locks.

Prevention strategies:

  • Wait-die: An older transaction waits; a younger one is killed.
  • Wound-wait: An older transaction kills the younger; a younger one waits.
  • Lock ordering: Always acquire locks in a fixed order (e.g., always lock A before B).
  • Timeout: Roll back a transaction that has waited too long.

9.7 Multiple Granularity

Locks can be held at different levels of granularity:

  • Database (coarsest)
  • Table
  • Page
  • Row (finest)

Finer granularity allows more concurrency (two transactions locking different rows) but increases lock management overhead. Coarser granularity is simpler but reduces concurrency.

Intention locks: When locking a row, place an intention lock on its table so other transactions know the table is partially locked, without scanning every row.

9.8 Timestamp-Based Protocol

Assign each transaction a unique timestamp when it starts. If T1 has an earlier timestamp than T2:

  • If T2 wants to read/write data T1 is using: check whether T2's access is compatible with T1's timestamp order.
  • If not: roll back T2 and restart it with a new timestamp.

Timestamp protocols avoid deadlocks (no waiting) but may cause cascading rollbacks.


Key Terms — Unit 9

  • Transaction — atomic unit of work
  • ACID — Atomicity, Consistency, Isolation, Durability
  • COMMIT / ROLLBACK — make permanent / undo
  • Isolation level — how visible uncommitted changes are
  • Deadlock — circular wait for locks
  • 2PL — Two-Phase Locking guarantees serializability

Unit 9 Practice Questions

Q1. A bank transfer between two accounts must be atomic. Write the SQL transaction with error handling.

Answer:

BEGIN;
  UPDATE Account SET Balance = Balance - 500 WHERE AccID = 'A';
  UPDATE Account SET Balance = Balance + 500 WHERE AccID = 'B';
  -- If both succeed:
COMMIT;
-- If an error occurs at any point, the application issues:
-- ROLLBACK;
-- ensuring no money is lost or duplicated

Q2. T1 reads Balance=1000 from Account A. T2 updates Balance to 1500 and commits. T1 reads Balance again and gets 1500. What anomaly is this?

Answer: Non-repeatable read. T1 got different values for the same read in the same transaction because T2 committed a change in between. Prevented by REPEATABLE READ isolation level.


Detailed Practice Questions and Answer Key

Q1. Draw an ER diagram for a Hospital system with entities Patient, Doctor, and Appointment.

Answer:
Entities: PATIENT (PatientID, Name, DOB), DOCTOR (DoctorID, Name, Specialization), APPOINTMENT (AppointmentID, Date, Time, Diagnosis). Relationships: PATIENT books many APPOINTMENTs (1:N); DOCTOR attends many APPOINTMENTs (1:N). APPOINTMENT participates in both.


Q2. Normalize the following relation to 3NF:
Project(EmpID, EmpName, ProjectID, ProjectName, Hours, DeptID, DeptName)

Answer:
FDs: EmpID → EmpName, DeptID; DeptID → DeptName; ProjectID → ProjectName; {EmpID, ProjectID} → Hours.
Decompose:

  • Employee(EmpID, EmpName, DeptID) — eliminates EmpName/DeptID partial dep on composite key
  • Department(DeptID, DeptName) — eliminates transitive dep DeptID→DeptName
  • Project(ProjectID, ProjectName) — eliminates ProjectName partial dep
  • WorksOn(EmpID, ProjectID, Hours) — full dependency on composite key

Q3. What is the difference between a view and a stored procedure?

Answer: A view is a saved SELECT query that behaves like a virtual table — you query it with SELECT. It does not contain procedural logic and executes when queried. A stored procedure is a named program that can contain multiple SQL statements, flow control (IF, LOOP), parameters, and transactions. It is called explicitly with CALL and can perform DML as well as SELECT.


Q4. Two transactions execute concurrently:
T1: UPDATE Account SET Bal = Bal - 100 WHERE ID = 1
T2: UPDATE Account SET Bal = Bal + 50 WHERE ID = 1
Explain what problem can occur without proper isolation and how 2PL prevents it.

Answer: Without isolation, both transactions read the same initial balance (say 1000), compute new values (900 and 1050), and write them back — the last write wins, losing one update. This is the lost update anomaly. With 2PL, T1 acquires an exclusive lock on row ID=1. T2 tries to acquire an exclusive lock and blocks until T1 commits and releases. T2 then reads the updated value (900) and applies its change correctly, producing 950.


References

  • Earlier TU BCA compilation — CACS255, PDF p. 68–71 (confirm the edition) Source: the course outline
    sourceHash: sha256:d126d513c1051b176b03e56e067608546786d279b596b7b431ecff4d944496cb
  • TU BCA 2025 mapping — BCA202 → CACS255
    Source: reports/syllabus-scrape/mapping-verification-2025.json
  • TU BCA 2025 — BCA202 listed at semester 3 with no detailed unit outline
    Source: the course outline