SESSION 1 – THEORY
Topics Covered
1. Introduction to DBMS
2. Basic Database Terminology
3. Types of DBMS
o Relational DBMS
o Object Relational DBMS
o NoSQL Databases
4. Introduction to MySQL
5. MySQL Clients
1. Introduction to DBMS
What is a Database?
A database is an organized collection of related data stored electronically, designed to be
accessed, managed, and updated efficiently.
Example:
A student database stores student details such as roll number, name, course, and marks.
What is DBMS?
A Database Management System (DBMS) is software that provides an interface to create,
store, retrieve, update, and manage data in a database.
Standard definition (exam-ready):
A DBMS is a collection of programs that enables users to define, construct, manipulate, and
control access to databases.
Why DBMS is Needed (File System Limitations)
Traditional file systems store data in files without centralized control. This leads to multiple
issues:
Problem Explanation
Data Redundancy Same data stored in multiple files
Data Inconsistency Different copies of same data have different values
Difficult Access Writing new programs for every query
Problem Explanation
No Security No fine-grained access control
No Concurrency Control Multiple users overwrite data
No Backup/Recovery Data loss on failure
DBMS addresses all these problems.
Advantages of DBMS
Reduced data redundancy
Improved data consistency
Data security and authorization
Backup and recovery
Concurrency control
Data abstraction and independence
2. Basic Database Terminology
These terms are very important for CCEE objective and descriptive questions.
Term Meaning
Data Raw facts (numbers, text)
Information Processed data with meaning
Database Organized collection of data
Table (Relation) Data stored in rows and columns
Row (Tuple) Single record
Column (Attribute) Property of an entity
Schema Logical structure of database
Instance Actual data at a specific time
Primary Key Uniquely identifies a record
Foreign Key Refers to primary key of another table
Example Table:
STUDENT
--------------------------------
roll_no | name | age
--------------------------------
101 | Rahul | 22
102 | Mayank | 23
Relation → STUDENT
Tuple → (101, Rahul, 22)
Attribute → name
Primary Key → roll_no
3. Types of DBMS
A. Relational DBMS (RDBMS)
RDBMS stores data in tables (relations) and enforces relationships using keys.
Characteristics:
Data stored in rows and columns
Fixed schema
Uses SQL
Supports ACID properties
Data integrity using constraints
Examples:
MySQL
Oracle
PostgreSQL
SQL Server
Important Note for Exam:
RDBMS is based on E.F. Codd’s relational model.
B. Object Relational DBMS (ORDBMS)
ORDBMS extends RDBMS by supporting object-oriented features.
Features:
User-defined data types
Inheritance
Encapsulation
Methods stored with data
Examples:
PostgreSQL
Oracle (object features)
Key Difference:
ORDBMS = Relational model + Object-oriented concepts
C. NoSQL Databases
NoSQL databases are non-relational databases designed for scalability and flexible schema.
Characteristics:
Schema-less or dynamic schema
Horizontal scalability
High availability
Designed for big data and distributed systems
Types of NoSQL Databases:
Key-Value Store (Redis)
Document Store (MongoDB)
Column-Oriented (Cassandra)
Graph Databases (Neo4j)
RDBMS vs NoSQL (Frequently Asked)
Feature RDBMS NoSQL
Schema Fixed Flexible
Data Structured Semi/Unstructured
Scaling Vertical Horizontal
Transactions ACID BASE
Query Language SQL No standard
4. Introduction to MySQL
What is MySQL?
MySQL is an open-source Relational Database Management System that uses SQL to
manage data.
Key Points:
Developed and maintained by Oracle
Fast and reliable
Supports ACID transactions using InnoDB
Widely used in web and enterprise applications
Common Usage:
Java (JDBC, Spring Boot)
PHP
Python
[Link]
MySQL Architecture (Conceptual)
Client sends SQL query
MySQL Server processes query
Storage Engine (InnoDB/MyISAM) handles data
Result returned to client
5. MySQL Clients
MySQL provides multiple clients to interact with the database.
A. MySQL Monitor
Command-line based client
Executes SQL commands directly
Lightweight and fast
Used mainly for:
Learning SQL
Exam practice
Server access
B. MySQL Shell
Advanced client
Supports SQL, JavaScript, and Python modes
Used for automation and administration
C. MySQL Workbench
Graphical user interface
Used for database design, querying, and administration
Supports ER diagrams and query editor
Exam-friendly definition:
MySQL Workbench is a visual tool for database design, development, and administration of
MySQL databases.
SESSION 1 – QUICK REVISION POINTS
DBMS manages data efficiently and securely
RDBMS uses tables and SQL
ORDBMS adds object-oriented features
NoSQL is schema-less and scalable
MySQL is an open-source RDBMS
Multiple MySQL clients exist for database interaction
STOPPING HERE
When you are ready, say:
“Next session”
Next we will cover Session 2 in the same depth:
Data Models
ER Diagrams
Codd’s 12 Rules
SQL categories and DDL commands
Slow, structured, and strictly aligned with CCEE CDAC final exam.
Move forward
Alright. Moving forward to Session 2.
As promised: theory-focused, exam-oriented, no lab, no unnecessary content, and I will
stop after this session.
DATABASE TECHNOLOGIES – SESSION 2
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 2 – THEORY
Topics Covered
1. Data Models
o Conceptual
o Logical
o Physical
2. Database Design
3. Entity–Relationship Diagram (ERD)
4. Codd’s 12 Rules for RDBMS
5. Introduction to SQL
6. Categories of SQL Commands
o DDL
o DML
o DCL
o TCL (DTL)
7. DDL Commands
o CREATE
o ALTER
o DROP
o TRUNCATE
1. Data Models
A data model defines how data is structured, stored, and related in a database.
Exam Definition:
A data model is a collection of concepts used to describe the structure of a database, data
relationships, constraints, and operations.
Types of Data Models
A. Conceptual Data Model
High-level view of data
Focuses on what data is stored, not how
Independent of DBMS
Used during requirement analysis
Key Components:
Entities
Attributes
Relationships
Example:
Entities: Student, Course
Relationship: Student enrolls in Course
No data types, no tables—only business view.
B. Logical Data Model
Represents structure of data
Still DBMS-independent
Includes attributes, primary keys, foreign keys
Example:
STUDENT (student_id, name, email)
COURSE (course_id, course_name)
ENROLLMENT (student_id, course_id)
This model is close to tables but not yet implemented.
C. Physical Data Model
Lowest level
DBMS-specific
Includes data types, indexes, storage details
Example (MySQL):
CREATE TABLE student (
student_id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);
Comparison (Very Important)
Model Level DBMS Dependent Focus
Conceptual High No Business view
Model Level DBMS Dependent Focus
Logical Medium No Structure
Physical Low Yes Implementation
2. Database Design
Database design is the process of organizing data efficiently to reduce redundancy and
ensure integrity.
Steps in Database Design
1. Requirement analysis
2. Identify entities and attributes
3. Identify relationships
4. Create ER diagram
5. Normalize data
6. Convert to tables
Goal:
Efficient, consistent, scalable database.
3. Entity–Relationship Diagram (ERD)
An ERD is a graphical representation of entities and their relationships.
Core Components of ERD
A. Entity
A real-world object with independent existence.
Examples:
Student
Employee
Course
B. Attribute
Properties of an entity.
Types:
Simple: name
Composite: address (street, city)
Derived: age (from DOB)
Multivalued: phone numbers
C. Relationship
Association between entities.
Example:
Student enrolls in Course
Cardinality (Very Important)
One-to-One (1:1)
One-to-Many (1:N)
Many-to-Many (M:N)
Example:
One department has many employees → 1:N
Primary Key in ERD
Uniquely identifies an entity
Shown as underlined attribute
4. Codd’s 12 Rules for RDBMS
Proposed by E. F. Codd, these rules define what a true RDBMS should follow.
Important Rules (Focus for Exam)
1. Information Rule
All data must be stored in tables.
2. Guaranteed Access Rule
Each value is accessible using table name, primary key, and column name.
3. Systematic Treatment of NULLs
NULL represents missing or unknown values.
4. Dynamic Online Catalog
Metadata stored as tables.
5. Comprehensive Data Sublanguage Rule
One language (SQL) for all operations.
6. View Updating Rule
Views should be updatable when possible.
7. High-Level Insert, Update, Delete
Operations must work on sets of rows.
8. Physical Data Independence
Storage changes should not affect applications.
9. Logical Data Independence
Logical changes should not affect applications.
10. Integrity Independence
Constraints stored in database, not application.
11. Distribution Independence
12. Non-Subversion Rule
Exam Tip:
At least 5–6 rules are frequently asked in short answers.
5. Introduction to SQL
SQL (Structured Query Language) is used to communicate with relational databases.
SQL is used to:
Create database objects
Insert, update, delete data
Retrieve data
Control access
Manage transactions
SQL is:
Declarative (what to do, not how)
Standardized (ANSI/ISO)
6. Categories of SQL Commands
A. DDL – Data Definition Language
Used to define database structure.
Commands:
CREATE
ALTER
DROP
TRUNCATE
B. DML – Data Manipulation Language
Used to manipulate data.
Commands:
INSERT
UPDATE
DELETE
SELECT
C. DCL – Data Control Language
Used for access control.
Commands:
GRANT
REVOKE
D. TCL (DTL) – Transaction Control Language
Used to manage transactions.
Commands:
COMMIT
ROLLBACK
SAVEPOINT
7. DDL Commands (Detailed)
CREATE
Used to create database objects.
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary INT
);
ALTER
Used to modify table structure.
ALTER TABLE employee ADD department VARCHAR(30);
DROP
Removes table completely (structure + data).
DROP TABLE employee;
TRUNCATE
Deletes all rows but keeps table structure.
TRUNCATE TABLE employee;
Difference (Very Important):
DROP TRUNCATE
Deletes structure Keeps structure
Cannot rollback Cannot rollback
Slow Fast
SESSION 2 – QUICK REVISION
Data models: Conceptual, Logical, Physical
ERD shows entities and relationships
Codd’s rules define true RDBMS
SQL is standard database language
DDL defines structure, not data
STOPPING HERE
When ready, say:
“Next session”
Next up:
Session 3 & 4 – Normalization, Functional Dependency, Normal Forms, DML
This pace and depth is exactly what is required for CCEE CDAC final exam.
Next session
Proceeding to Session 3 & Session 4.
As agreed: theory-focused, exam-oriented, clear examples, queries only where
meaningful, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 3 & SESSION 4
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 3 & 4 – THEORY
Topics Covered
1. Data Redundancy
2. Data Anomalies
3. Functional Dependency
4. Normalization
5. Need for Normalization
6. Normal Forms
o First Normal Form (1NF)
o Second Normal Form (2NF)
o Third Normal Form (3NF)
o Boyce–Codd Normal Form (BCNF)
o Introduction to 4NF and 5NF
7. DML Commands
o INSERT
o UPDATE
o DELETE
1. Data Redundancy
What is Data Redundancy?
Data redundancy refers to unnecessary duplication of data in a database.
Example:
STUDENT_COURSE
----------------------------------------
student_id | student_name | course | fee
----------------------------------------
1 | Rahul | DAC | 90000
1 | Rahul | DBT | 80000
Here, student_name is repeated for the same student.
Problems Caused by Redundancy
Wastes storage
Causes inconsistency
Increases maintenance cost
Redundancy is the root cause of anomalies.
2. Data Anomalies
An anomaly is an inconsistency or unexpected behavior caused due to poor database design.
Types of Data Anomalies
A. Insertion Anomaly
Cannot insert data without inserting unnecessary data.
Example:
You cannot add a new course unless at least one student enrolls.
B. Update Anomaly
Updating data in one place but forgetting another.
Example:
Changing Rahul’s name requires updating multiple rows.
C. Deletion Anomaly
Deleting data unintentionally removes important information.
Example:
Deleting last student of a course removes course information.
3. Functional Dependency (FD)
Definition
A functional dependency occurs when one attribute uniquely determines another attribute.
Notation:
A→B
(Attribute A determines attribute B)
Example
student_id → student_name
If student_id is known, student_name is uniquely determined.
Types of Functional Dependencies
1. Trivial FD
If B is a subset of A
{student_id, name} → name
2. Non-Trivial FD
If B is not a subset of A
student_id → name
Full Functional Dependency
An attribute depends on the entire primary key, not part of it.
Partial Dependency
An attribute depends on part of a composite key.
This concept is critical for 2NF.
4. Normalization
What is Normalization?
Normalization is the process of organizing data to:
Reduce redundancy
Eliminate anomalies
Improve data integrity
Need for Normalization
Avoid duplication
Avoid anomalies
Improve consistency
Efficient storage
5. Normal Forms
First Normal Form (1NF)
Rule
Table should have atomic values
No repeating groups or multivalued attributes
Before 1NF:
STUDENT
--------------------------
id | name | phone_numbers
--------------------------
1 | Rahul| 9999,8888
After 1NF:
STUDENT
--------------------
id | name | phone
--------------------
1 | Rahul| 9999
1 | Rahul| 8888
Second Normal Form (2NF)
Rule
Table must be in 1NF
No partial dependency
Applies only when composite primary key exists.
Example (Violation of 2NF)
ENROLLMENT
-------------------------------------
student_id | course_id | student_name
-------------------------------------
1 | C1 | Rahul
Primary key: (student_id, course_id)
Here:
student_id → student_name
Partial dependency exists.
Convert to 2NF
STUDENT(student_id, student_name)
ENROLLMENT(student_id, course_id)
Third Normal Form (3NF)
Rule
Table must be in 2NF
No transitive dependency
Transitive Dependency
A → B and B → C
Then A → C (undesirable)
Example
EMPLOYEE
---------------------------------------
emp_id | emp_name | dept_id | dept_name
---------------------------------------
Dependencies:
emp_id → dept_id
dept_id → dept_name
Transitive dependency exists.
Convert to 3NF
EMPLOYEE(emp_id, emp_name, dept_id)
DEPARTMENT(dept_id, dept_name)
Boyce–Codd Normal Form (BCNF)
Rule
For every functional dependency A → B,
A must be a super key.
BCNF is stronger than 3NF.
Example
COURSE
------------------------
course | instructor | room
Dependencies:
course → instructor
instructor → room
Instructor is not a super key → violates BCNF.
Fix
Split into:
COURSE(course, instructor)
INSTRUCTOR(instructor, room)
Introduction to 4NF and 5NF (Exam Awareness)
Fourth Normal Form (4NF)
No multivalued dependencies
Fifth Normal Form (5NF)
No join dependency
Rare in practical systems
Usually asked as theoretical definitions only.
6. DML Commands
DML commands manipulate data inside tables.
INSERT
INSERT INTO student VALUES (1, 'Rahul', 22);
UPDATE
UPDATE student
SET age = 23
WHERE id = 1;
DELETE
DELETE FROM student
WHERE id = 1;
DELETE vs TRUNCATE (Recalled)
DELETE TRUNCATE
Deletes selected rows Deletes all rows
WHERE allowed WHERE not allowed
Can rollback Cannot rollback
SESSION 3 & 4 – QUICK REVISION
Redundancy causes anomalies
Functional dependency is core of normalization
1NF: Atomic values
2NF: No partial dependency
3NF: No transitive dependency
BCNF: Determinant must be super key
DML changes data, not structure
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 5:
MySQL Data Types
Constraints
Aggregate Functions
Group By, Having
LIKE, DISTINCT, ORDER BY, BETWEEN, IN, NULL comparisons
This sequence is exactly aligned with CCEE CDAC final exam expectations.
Move forward
Proceeding to Session 5.
Same rules maintained: theory-focused, exam-oriented, clear explanations, meaningful
SQL examples only, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 5
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 5 – THEORY
Topics Covered
1. MySQL Data Types
2. Database Constraints
o Primary Key
o Unique
o Not Null
o Foreign Key
o Default
o Check
3. Aggregate Functions
4. GROUP BY and HAVING
5. LIKE Operator
6. DISTINCT
7. Sorting using ORDER BY
8. BETWEEN … AND
9. NULL Comparisons (IS NULL / IS NOT NULL)
10. IN and NOT IN
1. MySQL Data Types
Data types define what kind of data can be stored in a column.
A. Numeric Data Types
Data Type Description
INT Integer values
BIGINT Large integer values
DECIMAL(p,s) Fixed-point numbers
FLOAT / DOUBLE Approximate values
Example:
salary DECIMAL(10,2)
B. Character / String Data Types
Data Type Description
CHAR(n) Fixed-length string
VARCHAR(n) Variable-length string
TEXT Large text
Important Difference (Exam):
CHAR VARCHAR
Fixed size Variable size
Faster Saves space
C. Date and Time Data Types
Data Type Description
DATE YYYY-MM-DD
TIME HH:MM:SS
DATETIME Date and time
TIMESTAMP Auto-updated date-time
D. Boolean Data Type
BOOLEAN or BOOL
Stored internally as TINYINT (0 or 1)
2. Database Constraints
Constraints enforce data integrity rules on tables.
A. Primary Key
Uniquely identifies each record
Cannot be NULL
Only one primary key per table
emp_id INT PRIMARY KEY
B. Unique Constraint
Ensures all values are unique
NULL values allowed (multiple)
email VARCHAR(100) UNIQUE
C. NOT NULL
Column cannot contain NULL values
name VARCHAR(50) NOT NULL
D. Foreign Key
Creates relationship between tables
Refers to primary key of another table
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES department(dept_id)
E. DEFAULT
Assigns default value if none is provided
status VARCHAR(10) DEFAULT 'ACTIVE'
F. CHECK Constraint
Ensures condition on column values
age INT CHECK (age >= 18)
Exam Note:
MySQL supports CHECK syntactically; enforcement depends on version.
3. Aggregate Functions
Aggregate functions operate on multiple rows and return a single value.
Common Aggregate Functions
Function Purpose
COUNT() Number of rows
SUM() Total
AVG() Average
MIN() Minimum
MAX() Maximum
Examples:
SELECT COUNT(*) FROM employee;
SELECT AVG(salary) FROM employee;
4. GROUP BY Clause
GROUP BY groups rows that have the same values.
SELECT dept_id, AVG(salary)
FROM employee
GROUP BY dept_id;
HAVING Clause
HAVING is used with GROUP BY to filter grouped results.
SELECT dept_id, AVG(salary)
FROM employee
GROUP BY dept_id
HAVING AVG(salary) > 50000;
Important Difference (Exam Favorite):
WHERE HAVING
Filters rows Filters groups
Used before grouping Used after grouping
Cannot use aggregates Can use aggregates
5. LIKE Operator
Used for pattern matching.
Wildcards
Symbol Meaning
% Zero or more characters
_ Single character
Examples:
SELECT * FROM student WHERE name LIKE 'A%';
SELECT * FROM student WHERE name LIKE '_a%';
6. DISTINCT Keyword
Removes duplicate values from result set.
SELECT DISTINCT dept_id FROM employee;
7. ORDER BY Clause
Used to sort result set.
SELECT * FROM employee ORDER BY salary DESC;
Default sorting is ascending (ASC).
8. BETWEEN … AND Operator
Used to specify a range.
SELECT * FROM employee
WHERE salary BETWEEN 30000 AND 60000;
Inclusive of boundary values.
9. NULL Comparisons
NULL cannot be compared using =.
Correct Way
SELECT * FROM employee WHERE manager_id IS NULL;
SELECT * FROM employee WHERE manager_id IS NOT NULL;
10. IN and NOT IN Operators
Used to check multiple values.
SELECT * FROM employee
WHERE dept_id IN (10, 20, 30);
SELECT * FROM employee
WHERE dept_id NOT IN (10, 20);
SESSION 5 – QUICK REVISION
Data types define storage format
Constraints ensure data integrity
Aggregate functions summarize data
GROUP BY forms groups, HAVING filters groups
LIKE is for pattern matching
DISTINCT removes duplicates
ORDER BY sorts data
BETWEEN checks range
IS NULL is mandatory for NULL checks
IN handles multiple values
STOPPING HERE
When ready, say:
“Next session”
Next up: Session 6
Relational Algebra
Joins (all types)
UNION / UNION ALL
Copying table structure/data
AUTO_INCREMENT
This will be a very high-weight session for CCEE.
Next
Proceeding to Session 6.
Same discipline: theory-focused, exam-oriented, clear explanations, meaningful SQL
examples, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 6
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 6 – THEORY
Topics Covered
1. Relational Algebra Operations
o Selection
o Projection
o Union
o Intersection
o Set Difference (Minus)
o Cartesian Product
2. Joins
o Equi Join
o Inner Join
o Outer Join (Left, Right, Full)
o Natural Join
o Cross Join
3. SQL Standard Join Syntax vs Old Join Syntax
4. UNION vs UNION ALL
5. Copying Table Structure and Data
6. Sequences / AUTO_INCREMENT
1. Relational Algebra
Relational algebra is a procedural query language used to describe how data is retrieved
from relations.
Exam Definition:
Relational algebra is a set of operations that take relations as input and produce relations as
output.
A. Selection (σ)
Selects rows based on a condition.
Notation:
σ(condition)(Relation)
Example:
Select employees with salary > 50000.
σ(salary > 50000)(EMPLOYEE)
SQL Equivalent:
SELECT * FROM employee WHERE salary > 50000;
B. Projection (π)
Selects specific columns.
Notation:
π(column_list)(Relation)
Example:
π(name, salary)(EMPLOYEE)
SQL Equivalent:
SELECT name, salary FROM employee;
C. Union (∪)
Combines results of two relations.
Conditions:
Same number of columns
Same data types
Same order
Example:
EMP1 ∪ EMP2
SQL:
SELECT emp_id FROM emp1
UNION
SELECT emp_id FROM emp2;
D. Intersection (∩)
Returns common rows from both relations.
EMP1 ∩ EMP2
SQL Equivalent (using INTERSECT):
SELECT emp_id FROM emp1
INTERSECT
SELECT emp_id FROM emp2;
(MySQL does not support INTERSECT directly; concept is theoretical.)
E. Set Difference (Minus)
Rows present in first relation but not in second.
EMP1 − EMP2
SQL Conceptual:
SELECT emp_id FROM emp1
EXCEPT
SELECT emp_id FROM emp2;
(Also theoretical in MySQL.)
F. Cartesian Product (×)
Combines all rows of two tables.
If table A has m rows and B has n rows → result has m × n rows.
EMPLOYEE × DEPARTMENT
2. Joins
Joins combine rows from multiple tables based on related columns.
A. Equi Join
Join using equality condition.
SELECT *
FROM employee e, department d
WHERE e.dept_id = d.dept_id;
This uses old join syntax.
B. Inner Join
Returns only matching rows.
SELECT [Link], d.dept_name
FROM employee e
INNER JOIN department d
ON e.dept_id = d.dept_id;
C. Outer Joins
Include unmatched rows.
Left Outer Join
Returns all rows from left table.
SELECT [Link], d.dept_name
FROM employee e
LEFT JOIN department d
ON e.dept_id = d.dept_id;
Right Outer Join
Returns all rows from right table.
SELECT [Link], d.dept_name
FROM employee e
RIGHT JOIN department d
ON e.dept_id = d.dept_id;
Full Outer Join
Returns all rows from both tables.
(Not supported directly in MySQL; asked conceptually.)
D. Natural Join
Automatically joins columns with same name and data type.
SELECT * FROM employee NATURAL JOIN department;
Exam Note:
Avoid natural joins in real systems due to ambiguity.
E. Cross Join
Produces Cartesian product.
SELECT * FROM employee CROSS JOIN department;
3. Old Join Syntax vs SQL Standard Syntax
Old Style
SELECT *
FROM employee e, department d
WHERE e.dept_id = d.dept_id;
SQL Standard (Preferred)
SELECT *
FROM employee e
JOIN department d
ON e.dept_id = d.dept_id;
Exam Tip:
Always prefer SQL standard syntax for clarity and maintenance.
4. UNION vs UNION ALL
UNION
Removes duplicates
Slower
SELECT dept_id FROM emp1
UNION
SELECT dept_id FROM emp2;
UNION ALL
Keeps duplicates
Faster
SELECT dept_id FROM emp1
UNION ALL
SELECT dept_id FROM emp2;
Key Difference (Very Important)
UNION UNION ALL
Removes duplicates Keeps duplicates
Slower Faster
Uses sorting No sorting
5. Copying Table Structure and Data
Copy Structure + Data
CREATE TABLE emp_backup
AS SELECT * FROM employee;
Copy Only Structure
CREATE TABLE emp_structure
AS SELECT * FROM employee WHERE 1=0;
Copy Data into Existing Table
INSERT INTO emp_backup
SELECT * FROM employee;
6. AUTO_INCREMENT
AUTO_INCREMENT automatically generates unique numeric values.
emp_id INT AUTO_INCREMENT PRIMARY KEY
Key Points:
Used with PRIMARY KEY
Starts from 1 by default
Incremented automatically
SESSION 6 – QUICK REVISION
Relational algebra defines data retrieval operations
Selection filters rows, Projection filters columns
Joins combine tables
INNER JOIN returns matching rows
OUTER JOIN returns unmatched rows
UNION removes duplicates
UNION ALL keeps duplicates
AUTO_INCREMENT generates unique values
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 7:
Subqueries and Correlated Subqueries
EXISTS / NOT EXISTS
TCL & DCL Commands
Views and Indexes
Temporary Tables
This is another high-scoring session for CCEE.
Next session
Proceeding to Session 7.
Maintaining the same approach: theory-focused, exam-oriented, clear explanations,
meaningful SQL examples, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 7
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 7 – THEORY
Topics Covered
1. Subqueries
2. Correlated Subqueries
3. EXISTS / NOT EXISTS
4. TCL Commands
o COMMIT
o ROLLBACK
o SAVEPOINT
5. DCL Commands
o GRANT
o REVOKE
o GRANT OPTION
6. Views
o Types of Views
o Simple and Complex Views
7. Indexes
8. Temporary Tables
1. Subquery
What is a Subquery?
A subquery is a query written inside another SQL query.
Exam Definition:
A subquery is a SELECT statement nested inside another SQL statement.
Where Subqueries Are Used
SELECT clause
WHERE clause
FROM clause
Example: Subquery in WHERE clause
Find employees whose salary is greater than the average salary.
SELECT name
FROM employee
WHERE salary > (
SELECT AVG(salary)
FROM employee
);
Types of Subqueries
A. Single-row Subquery
Returns one row.
SELECT name
FROM employee
WHERE dept_id = (
SELECT dept_id
FROM department
WHERE dept_name = 'HR'
);
Uses operators: =, <, >
B. Multiple-row Subquery
Returns multiple rows.
SELECT name
FROM employee
WHERE dept_id IN (
SELECT dept_id
FROM department
WHERE location = 'Pune'
);
Uses operators: IN, ANY, ALL
2. Correlated Subquery
Definition
A correlated subquery depends on values from the outer query and executes once for each
row of the outer query.
Example
Find employees who earn more than the average salary of their department.
SELECT [Link]
FROM employee e
WHERE salary > (
SELECT AVG(salary)
FROM employee
WHERE dept_id = e.dept_id
);
Here, the subquery uses e.dept_id from the outer query.
Key Difference (Exam Favorite)
Subquery Correlated Subquery
Executes once Executes per row
Independent Depends on outer query
Faster Slower
3. EXISTS and NOT EXISTS
EXISTS
Checks whether a subquery returns at least one row.
Returns TRUE or FALSE.
Example: EXISTS
Find departments that have at least one employee.
SELECT dept_name
FROM department d
WHERE EXISTS (
SELECT 1
FROM employee e
WHERE e.dept_id = d.dept_id
);
NOT EXISTS
Checks whether a subquery returns no rows.
Example: NOT EXISTS
Find departments with no employees.
SELECT dept_name
FROM department d
WHERE NOT EXISTS (
SELECT 1
FROM employee e
WHERE e.dept_id = d.dept_id
);
EXISTS vs IN (Exam Insight)
EXISTS is faster for large datasets
EXISTS stops searching after first match
IN compares full result set
4. TCL Commands (Transaction Control Language)
Transactions group SQL operations into a single unit of work.
COMMIT
Saves changes permanently.
COMMIT;
ROLLBACK
Undo changes since last COMMIT.
ROLLBACK;
SAVEPOINT
Creates a checkpoint inside a transaction.
SAVEPOINT sp1;
ROLLBACK TO sp1;
Transaction Example
INSERT INTO account VALUES (1, 5000);
SAVEPOINT s1;
UPDATE account SET balance = balance - 1000 WHERE id = 1;
ROLLBACK TO s1;
COMMIT;
5. DCL Commands (Data Control Language)
Used to control access and permissions.
GRANT
Gives privileges to users.
GRANT SELECT, INSERT ON employee TO user1;
REVOKE
Removes privileges.
REVOKE INSERT ON employee FROM user1;
GRANT OPTION
Allows user to grant permissions to others.
GRANT SELECT ON employee TO user1 WITH GRANT OPTION;
6. Views
What is a View?
A view is a virtual table created from a query.
Exam Definition:
A view is a logical table based on one or more tables.
Creating a View
CREATE VIEW emp_view AS
SELECT name, salary
FROM employee;
Types of Views
A. Simple View
Based on single table
No GROUP BY, JOIN, DISTINCT
CREATE VIEW emp_simple AS
SELECT emp_id, name
FROM employee;
B. Complex View
Based on multiple tables
Uses JOIN, GROUP BY, functions
CREATE VIEW dept_salary AS
SELECT dept_id, AVG(salary)
FROM employee
GROUP BY dept_id;
Updatable Views (Exam Point)
Simple views are usually updatable
Complex views are not updatable
7. Indexes
What is an Index?
An index is a database object that improves data retrieval speed.
Creating an Index
CREATE INDEX idx_salary
ON employee(salary);
Advantages
Faster SELECT queries
Efficient searching
Disadvantages
Slower INSERT/UPDATE/DELETE
Extra storage required
8. Temporary Tables
Temporary tables exist only for the session.
Creating Temporary Table
CREATE TEMPORARY TABLE temp_emp (
id INT,
name VARCHAR(50)
);
Characteristics
Automatically dropped when session ends
Useful for intermediate results
Session-specific
SESSION 7 – QUICK REVISION
Subqueries can be nested inside queries
Correlated subqueries run per row
EXISTS checks existence, not data
TCL controls transactions
DCL manages privileges
Views are virtual tables
Indexes improve query performance
Temporary tables are session-based
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 8:
Indexes (in depth)
ACID Properties
Database Instance vs Schema
MySQL Storage Engines
This session is concept-heavy and frequently tested in CCEE.
Next
Proceeding to Session 8.
Same discipline maintained: theory-focused, exam-oriented, clear explanations, no lab, no
unnecessary content, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 8
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 8 – THEORY
Topics Covered
1. Indexes
o Concept
o Benefits
o Types of Indexes
2. Temporary Tables (revision perspective)
3. ACID Properties
4. Database Instance and Schema
5. MySQL Storage Engines
o InnoDB
o MyISAM
o Others (overview)
6. Revision of SQL Commands (conceptual)
1. Indexes (In Depth)
What is an Index?
An index is a database object that improves the speed of data retrieval operations on a
table, similar to an index in a book.
Exam Definition:
An index is a data structure that allows faster access to rows in a table based on column
values.
How Index Works (Conceptually)
Index stores column values in sorted order
Points to the actual row locations
Reduces full table scans
Benefits of Indexes
Faster SELECT queries
Faster WHERE, JOIN, ORDER BY, GROUP BY operations
Improves performance on large tables
Drawbacks of Indexes
Slower INSERT, UPDATE, DELETE operations
Requires extra storage
Too many indexes degrade performance
Types of Indexes (Important for Exam)
A. Primary Index
Created automatically with PRIMARY KEY
Ensures uniqueness
Cannot contain NULL
B. Unique Index
Ensures unique values
Allows NULL values
CREATE UNIQUE INDEX idx_email ON employee(email);
C. Composite Index
Index on multiple columns
CREATE INDEX idx_dept_salary
ON employee(dept_id, salary);
Exam Tip:
Column order matters in composite indexes.
D. Single-Column Index
Index on one column
E. Clustered vs Non-Clustered Index (Conceptual)
Clustered Non-Clustered
Data stored in index order Separate from data
Clustered Non-Clustered
Only one per table Multiple allowed
Faster range queries Extra lookup needed
(In MySQL InnoDB, PRIMARY KEY is clustered.)
2. Temporary Tables (Revision View)
Temporary tables:
Exist only for the current session
Automatically dropped when session ends
Used for intermediate processing
CREATE TEMPORARY TABLE temp_sales (
product_id INT,
total_sales INT
);
3. ACID Properties
ACID properties ensure reliable transaction processing.
A. Atomicity
Transaction is all-or-nothing
Either fully executed or fully rolled back
Example:
Money transfer: debit and credit must both succeed.
B. Consistency
Database moves from one valid state to another
Constraints must not be violated
C. Isolation
Concurrent transactions should not affect each other
Ensures data correctness
D. Durability
Once committed, data is permanent
Survives crashes or power failures
Exam Favorite Question:
Explain ACID properties with example.
4. Database Instance and Schema
Database Schema
Logical structure of database
Defines tables, relationships, constraints
Does not change frequently
Example:
Table definitions, column types, keys
Database Instance
Actual data stored at a particular moment
Changes frequently
Difference (Very Important)
Schema Instance
Structure Data
Static Dynamic
Defined once Changes often
5. MySQL Storage Engines
A storage engine determines how data is stored, indexed, and retrieved.
A. InnoDB (Default Engine)
Features:
Supports ACID transactions
Supports foreign keys
Row-level locking
Crash recovery
Use Case:
Transactional applications (banking, ERP)
B. MyISAM
Features:
No transaction support
No foreign keys
Table-level locking
Faster for read-heavy operations
Use Case:
Read-only or reporting systems
Comparison (Very Important)
Feature InnoDB MyISAM
Transactions Yes No
Foreign Keys Yes No
Locking Row-level Table-level
Crash Recovery Yes No
Default Engine Yes No
C. Other Engines (Overview)
MEMORY: Data stored in RAM
CSV: Stores data in CSV files
ARCHIVE: Compressed storage for logs
Usually asked only as names and basic purpose.
6. SQL Commands – Conceptual Revision
At this stage, you should clearly differentiate:
DDL: Structure
DML: Data
DCL: Privileges
TCL: Transactions
Exam Tip:
Expect mixed MCQs combining multiple SQL concepts.
SESSION 8 – QUICK REVISION
Indexes speed up data access
Too many indexes slow down DML
ACID ensures transaction reliability
Schema defines structure, instance defines data
InnoDB is transactional and default
MyISAM is fast but non-transactional
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 9:
MySQL Programming Basics
Stored Procedures
Benefits of Stored Procedures
IN, OUT, INOUT Parameters
From here onward, focus shifts to procedural SQL, which is highly important for CCEE
practical and theory questions.
Next
Proceeding to Session 9.
Continuing with theory-first, CCEE-focused, clear explanations, and only meaningful
SQL examples. I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 9
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 9 – THEORY
Topics Covered
1. Introduction to MySQL Programming
2. MySQL Programs (Client-side vs Server-side logic)
3. Stored Procedures
4. Benefits of Stored Procedures
5. Procedure Parameters
o IN
o OUT
o INOUT
1. Introduction to MySQL Programming
Until now, we used SQL mainly for data definition and querying.
MySQL programming allows us to write procedural logic inside the database.
This includes:
Stored Procedures
Functions
Cursors
Triggers
Exception handling
Key Idea:
Instead of sending multiple SQL queries from application code, logic can be executed inside
the database.
2. MySQL Programs: Where Logic Runs
Client-side Logic
Written in Java, Python, PHP, etc.
SQL sent to database from application
More network overhead
Server-side Logic (MySQL Programming)
Written and stored inside MySQL
Executed directly on database server
Reduced network traffic
Stored procedures fall under server-side programming.
3. Stored Procedures
What is a Stored Procedure?
A stored procedure is a named block of SQL statements stored in the database and
executed as a single unit.
Exam Definition:
A stored procedure is a precompiled set of SQL statements stored in the database that can be
executed repeatedly.
Characteristics of Stored Procedures
Stored in database
Can accept parameters
Can contain control flow (loops, conditions)
Can return values via OUT parameters
Improves performance
Basic Syntax
DELIMITER //
CREATE PROCEDURE getAllEmployees()
BEGIN
SELECT * FROM employee;
END //
DELIMITER ;
Explanation:
DELIMITER changes statement terminator
BEGIN ... END defines procedure body
Procedure stored permanently in DB
Calling a Procedure
CALL getAllEmployees();
4. Benefits of Stored Procedures
This is a frequently asked theory question.
Advantages
1. Performance
o Compiled once, executed many times
o Reduced SQL parsing
2. Reduced Network Traffic
o One CALL instead of multiple queries
3. Security
o Users can execute procedure without table access
4. Code Reusability
o Logic written once, reused
5. Consistency
o Business rules enforced centrally
Disadvantages (Exam Balance Point)
Harder to debug
DB-specific syntax
Increased load on DB server
5. Procedure Parameters
Stored procedures can take parameters to pass values.
Types of Parameters
1. IN
2. OUT
3. INOUT
A. IN Parameter
Default parameter type
Used to pass value into procedure
Value cannot be changed and returned
Example
DELIMITER //
CREATE PROCEDURE getEmployeeById(IN eid INT)
BEGIN
SELECT * FROM employee WHERE emp_id = eid;
END //
DELIMITER ;
Call
CALL getEmployeeById(101);
B. OUT Parameter
Used to return value from procedure
Value assigned inside procedure
Example
DELIMITER //
CREATE PROCEDURE getEmployeeCount(OUT total INT)
BEGIN
SELECT COUNT(*) INTO total FROM employee;
END //
DELIMITER ;
Call
CALL getEmployeeCount(@count);
SELECT @count;
C. INOUT Parameter
Acts as both input and output
Value passed in, modified, and returned
Example
DELIMITER //
CREATE PROCEDURE incrementSalary(INOUT sal INT)
BEGIN
SET sal = sal + 5000;
END //
DELIMITER ;
Call
SET @s = 30000;
CALL incrementSalary(@s);
SELECT @s;
Parameter Comparison (Exam Important)
Parameter Input Output
IN Yes No
Parameter Input Output
OUT No Yes
INOUT Yes Yes
SESSION 9 – QUICK REVISION
MySQL programming enables server-side logic
Stored procedures are precompiled SQL blocks
Procedures improve performance and security
IN passes values in
OUT returns values
INOUT does both
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 10:
Flow Control Statements
Conditional Statements
Using logic inside Stored Procedures
This is very important for procedural SQL questions in CCEE.
Next
Proceeding to Session 10.
Continuing with theory-focused, exam-oriented, clear explanations, and only meaningful
examples. I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 10
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 10 – THEORY
Topics Covered
1. Flow Control Statements
o LOOP
o WHILE
o REPEAT
2. Conditional Statements
o IF
o IF–ELSE
o CASE (Switch Case)
3. Using Flow Control and Conditionals in Stored Procedures
1. Flow Control Statements
Flow control statements allow repeated execution of SQL statements inside stored
procedures and functions.
They are used when logic cannot be handled by simple SQL queries.
A. LOOP Statement
Concept
Executes a block of statements indefinitely
Must use LEAVE to exit the loop
Syntax
LOOP
statements;
END LOOP;
Example
DELIMITER //
CREATE PROCEDURE loop_example()
BEGIN
DECLARE counter INT DEFAULT 1;
myloop: LOOP
IF counter > 5 THEN
LEAVE myloop;
END IF;
SET counter = counter + 1;
END LOOP;
END //
DELIMITER ;
Explanation:
Loop runs until counter > 5
LEAVE exits the loop
B. WHILE Statement
Concept
Condition checked before loop execution
Loop runs only if condition is true
Syntax
WHILE condition DO
statements;
END WHILE;
Example
DELIMITER //
CREATE PROCEDURE while_example()
BEGIN
DECLARE i INT DEFAULT 1;
WHILE i <= 5 DO
SET i = i + 1;
END WHILE;
END //
DELIMITER ;
C. REPEAT Statement
Concept
Condition checked after execution
Executes at least once
Syntax
REPEAT
statements;
UNTIL condition
END REPEAT;
Example
DELIMITER //
CREATE PROCEDURE repeat_example()
BEGIN
DECLARE i INT DEFAULT 1;
REPEAT
SET i = i + 1;
UNTIL i > 5
END REPEAT;
END //
DELIMITER ;
Difference Between LOOP, WHILE, REPEAT (Very Important)
LOOP WHILE REPEAT
Infinite loop Entry-controlled Exit-controlled
Needs LEAVE Condition before Condition after
May run zero times May run zero times Runs at least once
2. Conditional Statements
Conditional statements allow decision-making logic.
A. IF Statement
Syntax
IF condition THEN
statements;
END IF;
Example
IF salary > 50000 THEN
SET grade = 'A';
END IF;
B. IF–ELSE Statement
Syntax
IF condition THEN
statements;
ELSE
statements;
END IF;
Example
IF marks >= 40 THEN
SET result = 'PASS';
ELSE
SET result = 'FAIL';
END IF;
C. IF–ELSEIF–ELSE Statement
IF marks >= 75 THEN
SET grade = 'A';
ELSEIF marks >= 60 THEN
SET grade = 'B';
ELSE
SET grade = 'C';
END IF;
D. CASE Statement (Switch Case)
Used when multiple conditions exist.
Syntax
CASE
WHEN condition1 THEN statement
WHEN condition2 THEN statement
ELSE statement
END CASE;
Example
CASE
WHEN marks >= 75 THEN SET grade = 'A';
WHEN marks >= 60 THEN SET grade = 'B';
ELSE SET grade = 'C';
END CASE;
Simple CASE (Value-based)
CASE grade
WHEN 'A' THEN SET bonus = 5000;
WHEN 'B' THEN SET bonus = 3000;
ELSE SET bonus = 1000;
END CASE;
IF vs CASE (Exam Favorite)
IF CASE
Better for few conditions Better for many conditions
More flexible Cleaner syntax
Complex conditions Value-based logic
3. Using Flow Control & Conditionals Together
Example: Salary Increment Logic
DELIMITER //
CREATE PROCEDURE salary_increment(INOUT sal INT)
BEGIN
IF sal < 30000 THEN
SET sal = sal + 5000;
ELSE
SET sal = sal + 3000;
END IF;
END //
DELIMITER ;
SESSION 10 – QUICK REVISION
LOOP runs infinitely unless exited
WHILE checks condition before execution
REPEAT checks condition after execution
IF handles decision making
CASE is alternative to multiple IF-ELSE
Flow control enables procedural logic in SQL
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 11:
Loop control statements (ITERATE, LEAVE)
Functions with and without parameters
MySQL built-in functions
These topics are commonly tested in CCEE theory and coding questions.
Next
Proceeding to Session 11.
Same approach: theory-focused, exam-oriented, clear explanations, only meaningful
examples, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 11
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 11 – THEORY
Topics Covered
1. Loop Control Statements
o LEAVE
o ITERATE
2. Functions in MySQL
o Functions with parameters
o Functions without parameters
3. MySQL Built-in Functions
o String Functions
o Numeric Functions
o Date and Time Functions
1. Loop Control Statements
Loop control statements are used inside loops (LOOP, WHILE, REPEAT) to control execution
flow.
A. LEAVE Statement
Concept
Used to exit a loop immediately
Similar to break in programming languages
Requires a label
Syntax
LEAVE label_name;
Example
DELIMITER //
CREATE PROCEDURE leave_example()
BEGIN
DECLARE i INT DEFAULT 1;
myloop: LOOP
IF i > 5 THEN
LEAVE myloop;
END IF;
SET i = i + 1;
END LOOP;
END //
DELIMITER ;
Explanation:
Loop exits when i > 5
Control jumps outside the loop
B. ITERATE Statement
Concept
Skips remaining statements of current iteration
Continues with next loop iteration
Similar to continue
Syntax
ITERATE label_name;
Example
DELIMITER //
CREATE PROCEDURE iterate_example()
BEGIN
DECLARE i INT DEFAULT 0;
myloop: LOOP
SET i = i + 1;
IF i = 3 THEN
ITERATE myloop;
END IF;
IF i > 5 THEN
LEAVE myloop;
END IF;
END LOOP;
END //
DELIMITER ;
Explanation:
When i = 3, rest of statements are skipped
Loop continues to next iteration
LEAVE vs ITERATE (Exam Favorite)
LEAVE ITERATE
Exits loop Skips current iteration
Terminates loop Continues loop
Similar to break Similar to continue
2. Functions in MySQL
What is a Function?
A MySQL function is a stored program that:
Always returns exactly one value
Can be used in SQL statements
Similar to built-in functions
Exam Definition:
A function is a stored routine that returns a single value and can be used in expressions.
A. Function Without Parameters
Example
DELIMITER //
CREATE FUNCTION getCurrentYear()
RETURNS INT
DETERMINISTIC
BEGIN
RETURN YEAR(CURDATE());
END //
DELIMITER ;
Usage
SELECT getCurrentYear();
B. Function With Parameters
Example
DELIMITER //
CREATE FUNCTION calculateBonus(salary INT)
RETURNS INT
DETERMINISTIC
BEGIN
RETURN salary * 0.10;
END //
DELIMITER ;
Usage
SELECT calculateBonus(50000);
Important Points (Exam)
Functions must return a value
Procedures may or may not return values
Functions cannot return result sets
Function vs Procedure (Very Important)
Function Procedure
Returns one value May return multiple values
Used in SELECT Cannot be used in SELECT
Mandatory RETURN RETURN optional
No OUT params Supports OUT params
3. MySQL Built-in Functions
Built-in functions perform common operations on data.
A. String Functions
Common String Functions
Function Purpose
LENGTH() Length of string
UPPER() Convert to uppercase
LOWER() Convert to lowercase
CONCAT() Join strings
SUBSTRING() Extract part of string
Function Purpose
TRIM() Remove spaces
Examples
SELECT LENGTH('CDAC');
SELECT UPPER('mysql');
SELECT CONCAT('Hello', ' ', 'World');
SELECT SUBSTRING('Database', 1, 4);
B. Numeric Functions
Common Numeric Functions
Function Purpose
ABS() Absolute value
ROUND() Round number
CEIL() Smallest integer ≥ value
FLOOR() Largest integer ≤ value
MOD() Remainder
Examples
SELECT ABS(-10);
SELECT ROUND(12.567, 2);
SELECT CEIL(4.2);
SELECT FLOOR(4.8);
C. Date and Time Functions
Common Date Functions
Function Purpose
CURDATE() Current date
NOW() Current date & time
YEAR() Extract year
MONTH() Extract month
DATEDIFF() Difference between dates
Examples
SELECT CURDATE();
SELECT NOW();
SELECT YEAR('2025-12-24');
SELECT DATEDIFF('2025-12-31', '2025-12-01');
SESSION 11 – QUICK REVISION
LEAVE exits loop, ITERATE skips iteration
Functions return exactly one value
Functions can be used inside SELECT
Built-in functions simplify data manipulation
String, numeric, and date functions are frequently tested
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 12:
Cursors
Types of Cursors
Cursor declaration, fetch, and close
This is a conceptually tricky but high-value topic for CCEE.
Next
Proceeding to Session 12.
Same approach maintained: theory-focused, exam-oriented, clear explanations, minimal
but meaningful examples, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 12
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 12 – THEORY
Topics Covered
1. Cursors in MySQL
2. Types of Cursors
o Asensitive
o Insensitive
o Read-only
o Nonscrollable
3. Cursor Lifecycle
o Declare
o Open
o Fetch
o Close
4. Cursor Example and Real-Time Use
1. Cursors in MySQL
What is a Cursor?
A cursor is a database object used to process query results row by row.
Exam Definition:
A cursor is a pointer that allows traversal of rows returned by a SELECT statement one at a
time.
Why Do We Need Cursors?
SQL normally works on sets of rows, not individual rows.
Cursors are used when:
Row-by-row processing is required
Complex logic must be applied to each record
Aggregate or conditional operations cannot handle the requirement
Important Limitation
Cursors are used only inside stored procedures or functions
Not used in plain SQL queries
2. Types of Cursors
MySQL cursors are limited compared to other RDBMS, but conceptually the following types
are important for exams.
A. Asensitive Cursor
Cursor behavior is decided by the database engine
May or may not reflect changes made to data after cursor is opened
Exam Note:
Default cursor type in MySQL.
B. Insensitive Cursor
Creates a temporary copy of data
Does not reflect changes made after cursor is opened
More stable but uses more memory
C. Read-Only Cursor
Data fetched cannot be modified using cursor
Default behavior in MySQL
D. Nonscrollable Cursor
Cursor can move only forward
Cannot move backward or jump to specific row
Important:
MySQL supports only forward-only cursors.
Cursor Type Summary (Exam Table)
Cursor Type Description
Asensitive Engine decides sensitivity
Insensitive Uses snapshot of data
Read-only Cannot update rows
Nonscrollable Forward-only movement
3. Cursor Lifecycle (Very Important)
Every cursor follows four mandatory steps.
Step 1: Declare Cursor
Defines the SELECT statement for cursor.
DECLARE cur_emp CURSOR FOR
SELECT emp_id, salary FROM employee;
Step 2: Declare Handler
Used to handle end of cursor data.
DECLARE done INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
Explanation:
When no more rows exist, done becomes 1
Prevents infinite loop
Step 3: Open Cursor
OPEN cur_emp;
Step 4: Fetch Cursor
Fetches one row at a time.
FETCH cur_emp INTO v_id, v_salary;
Step 5: Close Cursor
CLOSE cur_emp;
4. Complete Cursor Example
Example: Process Employee Salaries Row by Row
DELIMITER //
CREATE PROCEDURE process_salary()
BEGIN
DECLARE v_id INT;
DECLARE v_salary INT;
DECLARE done INT DEFAULT 0;
DECLARE cur_emp CURSOR FOR
SELECT emp_id, salary FROM employee;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur_emp;
read_loop: LOOP
FETCH cur_emp INTO v_id, v_salary;
IF done = 1 THEN
LEAVE read_loop;
END IF;
-- Processing logic here
IF v_salary < 30000 THEN
SET v_salary = v_salary + 5000;
END IF;
END LOOP;
CLOSE cur_emp;
END //
DELIMITER ;
Key Observations (Exam Perspective)
Cursor declared after variable declarations
Handler must be declared before opening cursor
FETCH retrieves one row at a time
LEAVE used to exit loop
Cursor must always be closed
5. Real-Time Use of Cursors
Cursors are used when:
Salary calculation per employee
Generating reports row-wise
Migrating data with transformation
Applying complex business rules per row
Exam Insight:
Use cursors only when set-based SQL is insufficient.
Common Exam Questions from Cursors
1. What is a cursor and why is it needed?
2. Steps involved in cursor processing
3. Role of handler in cursor
4. Difference between cursor and normal SELECT
5. Limitations of cursors in MySQL
SESSION 12 – QUICK REVISION
Cursor processes rows one at a time
Used inside stored procedures/functions
MySQL cursors are forward-only and read-only
Cursor lifecycle: Declare → Open → Fetch → Close
Handler avoids infinite loop
Use cursors only when required
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 13:
Triggers
BEFORE and AFTER triggers
NEW and OLD variables
Real-time trigger use cases
This topic is frequently tested in CCEE theory and scenario-based questions.
Next
Proceeding to Session 13.
Same discipline: theory-focused, CCEE-oriented, clear explanations, minimal but
meaningful examples, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 13
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 13 – THEORY
Topics Covered
1. Triggers
2. Types of Triggers
o BEFORE Triggers
o AFTER Triggers
3. OLD and NEW Trigger Variables
4. Trigger Examples
5. Real-Time Use of Triggers
1. Triggers
What is a Trigger?
A trigger is a database object that is automatically executed (fired) in response to certain
events on a table.
Exam Definition:
A trigger is a stored program that is automatically invoked when a specified event (INSERT,
UPDATE, DELETE) occurs on a table.
Key Characteristics of Triggers
Automatically executed
Cannot be called explicitly
Associated with a specific table
Executed before or after a DML operation
Used to enforce business rules and auditing
Trigger Events
Triggers respond to DML events only:
INSERT
UPDATE
DELETE
2. Types of Triggers
Triggers are classified based on timing.
A. BEFORE Triggers
Concept
Executed before the DML operation
Used to validate or modify data before it is stored
Example: BEFORE INSERT Trigger
Ensure salary is not negative before inserting employee.
DELIMITER //
CREATE TRIGGER before_emp_insert
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
IF [Link] < 0 THEN
SET [Link] = 0;
END IF;
END //
DELIMITER ;
Use Cases
Data validation
Default value enforcement
Prevent invalid data entry
B. AFTER Triggers
Concept
Executed after the DML operation
Used for logging, auditing, or cascading actions
Example: AFTER INSERT Trigger
Log employee insertion.
DELIMITER //
CREATE TRIGGER after_emp_insert
AFTER INSERT ON employee
FOR EACH ROW
BEGIN
INSERT INTO emp_log(emp_id, action_date)
VALUES (NEW.emp_id, NOW());
END //
DELIMITER ;
Use Cases
Audit trails
Maintaining history tables
Notifications
3. OLD and NEW Trigger Variables
Triggers use special row variables to access data.
NEW
Refers to new row values
Available in:
o INSERT
o UPDATE
OLD
Refers to existing row values
Available in:
o UPDATE
o DELETE
Availability Matrix (Exam Favorite)
Operation OLD NEW
INSERT No Yes
UPDATE Yes Yes
DELETE Yes No
Example: BEFORE UPDATE Using OLD and NEW
CREATE TRIGGER before_salary_update
BEFORE UPDATE ON employee
FOR EACH ROW
BEGIN
IF [Link] < [Link] THEN
SET [Link] = [Link];
END IF;
END;
4. Trigger Rules and Restrictions
Important exam points:
Triggers are table-level, not database-level
Cannot commit or rollback inside triggers
Cannot call triggers explicitly
Multiple triggers for same event allowed (MySQL 5.7+)
One trigger per event per table in older versions
5. Real-Time Use of Triggers
Common real-world scenarios:
1. Audit logging
2. Enforcing business rules
3. Maintaining derived data
4. Preventing invalid updates
5. Synchronizing tables
Example: DELETE Audit Trigger
CREATE TRIGGER after_emp_delete
AFTER DELETE ON employee
FOR EACH ROW
BEGIN
INSERT INTO emp_audit
VALUES (OLD.emp_id, [Link], NOW());
END;
6. Triggers vs Stored Procedures (Exam Comparison)
Triggers Stored Procedures
Automatically invoked Manually called
Event-driven Call-driven
Triggers Stored Procedures
Cannot accept parameters Can accept parameters
Used for enforcement Used for logic processing
Common Exam Questions from Triggers
1. What is a trigger?
2. Difference between BEFORE and AFTER triggers
3. Explain OLD and NEW
4. Can we use COMMIT inside trigger? (Answer: No)
5. Trigger vs Stored Procedure
SESSION 13 – QUICK REVISION
Triggers execute automatically
Used with INSERT, UPDATE, DELETE
BEFORE triggers validate data
AFTER triggers log or audit data
OLD and NEW hold row values
Triggers cannot be called manually
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 14:
Error Handling and Exceptions
Handlers
Defining and Handling Exceptions
This is a frequently asked conceptual and coding topic in CCEE.
Next
Proceeding to Session 14.
Same rules followed: theory-focused, CCEE-oriented, clear explanations, only
meaningful examples, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 14
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 14 – THEORY
Topics Covered
1. Error Handling and Exceptions
2. Types of Handler Actions
3. DECLARE HANDLER
4. Defining and Handling Exceptions in Stored Procedures
5. Examples of Exception Handling
1. Error Handling and Exceptions
What is an Exception?
An exception is an error condition that occurs during the execution of a SQL statement or
stored program.
Examples of Errors:
Division by zero
Duplicate key insertion
Cursor fetch beyond last row
Constraint violation
Why Exception Handling is Needed?
Prevent abnormal termination of procedures
Handle runtime errors gracefully
Maintain data consistency
Control program flow when errors occur
Exam Insight:
Exception handling improves robustness and reliability of stored programs.
2. Error Handling in MySQL
MySQL provides HANDLERS to manage errors inside stored procedures and functions.
Handlers are declared using:
DECLARE handler_type HANDLER FOR condition_value action;
3. Types of Handler Actions
A. CONTINUE Handler
Execution continues after the handler
Used for recoverable errors
B. EXIT Handler
Exits the BEGIN…END block
Used for serious errors
C. UNDO Handler
Rolls back changes (not supported in MySQL)
Mentioned only for theoretical knowledge
Handler Action Comparison (Exam Table)
Handler Type Behavior
CONTINUE Continue execution
EXIT Exit block
UNDO Rollback (not supported)
4. Condition Values in Handlers
Handlers can be defined for:
A. NOT FOUND
Raised when cursor fetch fails
Commonly used with cursors
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
B. SQLEXCEPTION
Handles all SQL errors
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
C. SQLWARNING
Handles warnings
DECLARE CONTINUE HANDLER FOR SQLWARNING
SET warning_flag = 1;
5. Handler Declaration Rules (Very Important)
Handlers must be declared after variable declarations
Must be declared before cursor operations
Scope is limited to the BEGIN…END block
6. Basic Exception Handling Example
Example: Handling Duplicate Entry Error
DELIMITER //
CREATE PROCEDURE insert_employee(
IN eid INT,
IN ename VARCHAR(50)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SELECT 'Error occurred while inserting record';
END;
INSERT INTO employee(emp_id, name)
VALUES (eid, ename);
END //
DELIMITER ;
7. Using EXIT Handler with Transaction
DELIMITER //
CREATE PROCEDURE transfer_funds(
IN from_acc INT,
IN to_acc INT,
IN amount INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
START TRANSACTION;
UPDATE account SET balance = balance - amount WHERE acc_id = from_acc;
UPDATE account SET balance = balance + amount WHERE acc_id = to_acc;
COMMIT;
END //
DELIMITER ;
Explanation:
If any UPDATE fails, ROLLBACK is executed
Ensures atomicity
8. Raising User-Defined Exceptions
SIGNAL Statement
Used to raise custom errors.
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Invalid salary value';
Example: Custom Validation Error
IF salary < 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Salary cannot be negative';
END IF;
9. SIGNAL vs HANDLER (Exam Comparison)
SIGNAL HANDLER
Raises exception Handles exception
Used to throw error Used to catch error
Stops execution Controls flow
10. Common Exam Questions from Session 14
1. What is exception handling?
2. Types of handlers in MySQL
3. Difference between CONTINUE and EXIT handler
4. What is NOT FOUND handler?
5. Purpose of SIGNAL statement
SESSION 14 – QUICK REVISION
Exceptions are runtime errors
HANDLERS manage errors in procedures
CONTINUE resumes execution
EXIT stops execution
NOT FOUND is used with cursors
SIGNAL raises custom errors
Proper exception handling ensures reliability
STOPPING HERE
When ready, say:
“Next session”
Next will be Session 15:
Introduction to NoSQL
RDBMS vs NoSQL
CAP Theorem
BASE Model
Categories of NoSQL Databases
This session is concept-heavy and MCQ-oriented for CCEE.
Next
Proceeding to Session 15.
Continuing with theory-focused, CCEE-oriented, clear explanations, exam-ready
comparisons, no lab, and I will stop after this session.
DATABASE TECHNOLOGIES – SESSION 15
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSION 15 – THEORY
Topics Covered
1. Introduction to NoSQL Databases
2. Features of NoSQL Databases
3. Structured vs Semi-Structured vs Unstructured Data
4. RDBMS vs NoSQL Databases
5. CAP Theorem
6. BASE Model
7. Categories of NoSQL Databases
1. Introduction to NoSQL Databases
What is NoSQL?
NoSQL (Not Only SQL) refers to a class of databases designed to handle:
Large volumes of data
High velocity (fast read/write)
High variety (different data formats)
Exam Definition:
NoSQL databases are non-relational databases that provide flexible schema design and
horizontal scalability.
Why NoSQL Emerged
Traditional RDBMS systems face challenges with:
Massive data (Big Data)
Distributed systems
Real-time web applications
Frequent schema changes
NoSQL databases were created to overcome these limitations.
2. Features of NoSQL Databases
Key characteristics (often asked in MCQs):
Schema-less or flexible schema
Horizontal scalability (scale out)
High availability
Distributed architecture
Optimized for read/write performance
Designed for big data and cloud environments
3. Types of Data
A. Structured Data
Fixed schema
Stored in tables
Easy to query
Examples:
Student records
Bank transactions
B. Semi-Structured Data
No fixed schema, but has structure
Uses tags or key-value pairs
Examples:
JSON
XML
C. Unstructured Data
No predefined format
Difficult to process with RDBMS
Examples:
Images
Videos
Emails
Social media posts
Comparison (Exam Table)
Type Schema Example
Structured Fixed Tables
Semi-Structured Flexible JSON
Unstructured None Media files
4. RDBMS vs NoSQL Databases
This is a very high-frequency exam question.
Feature RDBMS NoSQL
Data Model Tables Key-Value, Document, etc.
Schema Fixed Flexible
Scalability Vertical Horizontal
Transactions ACID BASE
Joins Supported Limited / Not supported
Consistency Strong Eventual
Examples MySQL, Oracle MongoDB, Cassandra
5. CAP Theorem
What is CAP Theorem?
CAP theorem states that a distributed database can guarantee only two out of the following
three properties at the same time:
1. Consistency (C)
2. Availability (A)
3. Partition Tolerance (P)
CAP Properties Explained
Consistency
Every read receives the most recent write.
Availability
Every request receives a response (success or failure).
Partition Tolerance
System continues to operate even if network failures occur.
CAP Rule (Exam Line)
In the presence of a network partition, a system must choose between consistency and
availability.
CAP Combinations
System Type Guarantees
CA Consistency + Availability
CP Consistency + Partition Tolerance
AP Availability + Partition Tolerance
Most NoSQL databases are CP or AP systems.
6. BASE Model
NoSQL databases follow the BASE model instead of ACID.
BASE stands for:
Basically Available
Soft State
Eventual Consistency
BASE Explained
Basically Available: System is always available
Soft State: Data may change over time
Eventual Consistency: Data becomes consistent eventually
ACID vs BASE (Exam Comparison)
ACID BASE
Strong consistency Eventual consistency
Transaction-oriented Availability-oriented
Used in RDBMS Used in NoSQL
7. Categories of NoSQL Databases
A. Key-Value Stores
Data stored as key-value pairs
Very fast access
Examples:
Redis
DynamoDB
Use Case:
Caching, session management
B. Document Stores
Data stored as documents (JSON/BSON)
Flexible structure
Examples:
MongoDB
CouchDB
Use Case:
Web applications, content management
C. Column-Oriented Databases
Data stored column-wise
Optimized for analytics
Examples:
Cassandra
HBase
Use Case:
Big data analytics
D. Graph Databases
Data stored as nodes and edges
Relationship-centric
Examples:
Neo4j
Use Case:
Social networks, recommendation systems
SESSION 15 – QUICK REVISION
NoSQL is designed for big data and scalability
Supports flexible schema
CAP theorem: choose any two of C, A, P
NoSQL follows BASE model
Four main NoSQL categories
RDBMS vs NoSQL comparison is very important for exams
STOPPING HERE
When ready, say:
“Next session”
Next will be Sessions 16, 17 & 18:
Introduction to MongoDB
MongoDB Architecture
Documents & Collections
CRUD Operations
Operators, Sorting, Indexing
This is the final major block and carries significant weight in CCEE MCQs and practical
understanding.
Next
Proceeding to Sessions 16, 17 & 18 (MongoDB).
As before: theory-focused, CCEE-oriented, clear explanations, meaningful examples, no
lab walkthrough, and I will stop after this block.
DATABASE TECHNOLOGIES – SESSIONS 16, 17 & 18
PG-DAC (ACTS, Pune) | CCEE Final Exam Preparation
SESSIONS 16–18 – THEORY (MongoDB)
Topics Covered
1. Introduction to MongoDB
2. Features of MongoDB
3. MongoDB Architecture (High-level)
4. MongoDB Documents & Collections
5. RDBMS vs MongoDB Analogies
6. JSON and BSON
7. CRUD Operations (Create, Read, Update, Delete)
8. UPSERT
9. MongoDB Operators
10. Sorting
11. Indexing
1. Introduction to MongoDB
What is MongoDB?
MongoDB is a NoSQL, document-oriented database designed for scalability, flexibility,
and high performance.
Exam Definition:
MongoDB is a document-based NoSQL database that stores data in flexible, JSON-like
documents.
Why MongoDB?
Handles large volumes of data
Flexible schema
Easy horizontal scaling
Suited for modern web and cloud applications
2. Features of MongoDB
Key features frequently tested in MCQs:
Document-oriented storage
Schema-less design
High availability
Horizontal scalability
Rich query language
Supports indexing
Replication and sharding support
3. MongoDB Architecture (Conceptual)
Core Components
Database: Logical container for collections
Collection: Group of documents
Document: Basic unit of data
MongoDB Server: Handles storage and queries
Replica Set (Awareness)
Group of MongoDB servers
Ensures high availability
One primary, multiple secondaries
(Usually asked at conceptual level.)
4. MongoDB Documents & Collections
Document
Stored in BSON format
Key-value pairs
Similar to JSON object
Example Document:
{
"_id": 1,
"name": "Mayank",
"age": 23,
"skills": ["Java", "SQL", "MongoDB"]
}
Collection
Group of related documents
No fixed schema
Documents inside a collection may have different fields
5. RDBMS vs MongoDB Analogies (Very Important)
RDBMS MongoDB
Database Database
Table Collection
Row (Tuple) Document
Column Field
Primary Key _id
JOIN Embedded documents / References
6. JSON and BSON
JSON
JavaScript Object Notation
Human-readable
Used for data exchange
BSON
Binary JSON
Used internally by MongoDB
Faster parsing and traversal
Supports additional data types (Date, Binary)
Exam Line:
MongoDB stores data internally in BSON format.
7. CRUD Operations
CRUD operations are core MongoDB commands.
A. CREATE (Insert)
Insert One Document
[Link]({
name: "Rahul",
age: 22
});
Insert Multiple Documents
[Link]([
{ name: "Amit", age: 23 },
{ name: "Neha", age: 21 }
]);
B. READ (Find)
Find All Documents
[Link]();
Find with Condition
[Link]({ age: { $gt: 22 } });
Projection (Select Specific Fields)
[Link]({}, { name: 1, age: 1 });
C. UPDATE
Update One Document
[Link](
{ name: "Rahul" },
{ $set: { age: 23 } }
);
Update Many Documents
[Link](
{ age: { $lt: 22 } },
{ $set: { status: "Junior" } }
);
D. DELETE
Delete One Document
[Link]({ name: "Amit" });
Delete Many Documents
[Link]({ age: { $lt: 20 } });
8. UPSERT
What is UPSERT?
Combination of UPDATE + INSERT
If document exists → update
If document does not exist → insert
Example
[Link](
{ name: "Karan" },
{ $set: { age: 24 } },
{ upsert: true }
);
9. MongoDB Operators
A. Comparison Operators
Operator Meaning
$eq Equal
$ne Not equal
$gt Greater than
$lt Less than
$gte Greater than or equal
$lte Less than or equal
Example
[Link]({ age: { $gte: 22 } });
B. Logical Operators
Operator Meaning
$and Logical AND
$or Logical OR
$not Logical NOT
Example
[Link]({
$and: [
{ age: { $gt: 20 } },
{ status: "Junior" }
]
});
10. Sorting
Sort documents using .sort().
Example
[Link]().sort({ age: -1 });
1 → Ascending
-1 → Descending
11. Indexing in MongoDB
What is an Index?
An index improves query performance by reducing document scans.
Create Index
[Link]({ name: 1 });
Types of Indexes (Awareness)
Single field index
Compound index
Unique index
Text index
Advantages
Faster read operations
Disadvantages
Slower write operations
Extra storage
Common Exam Questions from MongoDB
1. Difference between document and collection
2. MongoDB vs RDBMS
3. What is BSON?
4. What is UPSERT?
5. Purpose of indexing
6. CRUD operations in MongoDB
SESSIONS 16–18 – QUICK REVISION
MongoDB is a document-oriented NoSQL database
Data stored as BSON documents
Collections do not enforce schema
CRUD operations are core operations
UPSERT updates or inserts
Operators enable complex queries
Indexes improve performance
STOPPING HERE
You have now completed the entire Database Technologies syllabus as per ACTS Pune –
PG-DAC.