DBMS Complete Notes
DBMS Complete Notes
UNIT-1
Introduction to Data
Data refers to raw, unorganized facts that need to be processed to be
meaningful. It can be numbers, characters, symbols, images, audio, or video.
Examples of Data:
• A list of names
• Marks scored by students
• Product prices
• Sensor readings
Types of Data:
• Numeric Data (e.g., 25, 49.5)
• Text Data (e.g., "John", "Apple")
• Boolean Data (True/False)
• Multimedia Data (Images, Videos)
Introduction to Database
A Database is a structured collection of data that can be easily accessed,
managed, and updated.
Characteristics:
• Organized in tables (rows and columns)
• Reduces redundancy
• Can handle large volumes of data
• Allows multiple users to access data simultaneously
Example:
A library database might store:
• Book titles
• Authors
• Issued books
P a g e 1 | 100
DATABASE MANAGEMENT SYSTEMS
• Student records
Applications of DBMS
A DBMS is used to manage data efficiently in different types of applications
across industries. It helps in storing, retrieving, and managing large volumes of
data securely and quickly. Below are some of the major real-world applications
of DBMS:
1. Banking Systems
• Use of DBMS: To manage customer accounts, transactions, loan details,
and financial records.
• Examples:
P a g e 2 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 3 | 100
DATABASE MANAGEMENT SYSTEMS
6. Telecommunication
• Use of DBMS: To store call records, billing details, user information, and
mobile usage data.
• Examples:
o Call data records (CDRs)
o SMS logs and internet data usage
P a g e 4 | 100
DATABASE MANAGEMENT SYSTEMS
Advantages of DBMS
1. Reduced Data Redundancy
• DBMS avoids storing duplicate data by using a centralized system.
2. Improved Data Sharing
• Multiple users can access data simultaneously without conflict.
3. Better Data Security
• Access can be restricted to authorized users only.
4. Data Integrity
• Ensures accuracy and consistency through constraints and validation.
5. Backup and Recovery
• Automatic backups and recovery features protect against data loss.
6. Data Independence
• Data and application programs are independent; changing the database
does not require changing applications.
Disadvantages of DBMS
1. Complexity
• DBMS systems can be complex to set up and use for beginners.
2. High Cost
• Enterprise DBMS software can be expensive (hardware, licensing,
maintenance).
3. Large Size
• DBMS software requires significant memory and storage space.
P a g e 5 | 100
DATABASE MANAGEMENT SYSTEMS
4. Performance Issues
• In large-scale systems, performance might decrease if not optimized
properly.
5. Need for Trained Staff
• Skilled professionals are required to manage and maintain DBMS.
P a g e 6 | 100
DATABASE MANAGEMENT SYSTEMS
2. Application Programmers
• Write code (Java, Python, PHP, etc.) to create programs that interact
with the database.
• They use APIs like JDBC, ODBC to connect applications to databases.
3. Database Designers
• They design the structure of the database (schemas, tables, constraints).
• Decide how data should be stored, related, and optimized.
• Ensure the system supports business requirements.
4. System Analysts
• Act as a bridge between users and developers.
• Analyze business needs and propose a database-based solution.
P a g e 7 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 8 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 9 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 10 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 12 | 100
DATABASE MANAGEMENT SYSTEMS
In the above-given figure, we have few students and few course-enroll and a
course can be assigned to a single student only, but a student can enroll in any
number of courses and with this the relationship becomes one-to-many. We can
represent the given hierarchical model like the below relational tables:
John CSE CA
Jake CSE SE
STUDENT Table
Gami CA 2.0
P a g e 13 | 100
DATABASE MANAGEMENT SYSTEMS
Mary SE 3.0
Mayen SE 4.0
Security: This database system can enforce varying degree of security feature
unlike flat file system.
Efficiency: The hierarchical database model is a very efficient one when the
database contains a large number of 1: N relationships (one-to-many
relationships) and when the users require large number of transactions, using
data whose relationships are fixed.
Operational Anomalies: Hierarchical model suffers from the insert, delete and
update anomalies, also retrieval operation is difficult.
P a g e 14 | 100
DATABASE MANAGEMENT SYSTEMS
In the above figure, member TWO has only one owner 'ONE' whereas member
FIVE has two owners i.e, TWO and THREE. Here, each link between the two
record types represents 1 : M relationship between them. This model consists of
both lateral and top-down connections between the nodes. Therefore, it allows
1: 1, 1 : M, M : N relationships among the given entities which helps in
avoiding data redundancy problems as it supports multiple paths to the same
record.
Conceptual Simplicity: Just like hierarchical model it also simple and easy to
implement.
Ease to Access Data: The data access is easier than the hierarchical model.
P a g e 15 | 100
DATABASE MANAGEMENT SYSTEMS
Data Integrity: Since it is based on the parent child relationship, there is always
a link between the parent segment and the child segment under it.
System Complexity: All the records have to maintain using pointers thus the
database structure becomes more complex.
P a g e 16 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 17 | 100
DATABASE MANAGEMENT SYSTEMS
3. Super Key
A Super Key is a set of attributes that can uniquely identify a tuple. It may
contain extra attributes that are not necessary for uniqueness.
4. Foreign Key
A Foreign Key is an attribute in one relation that refers to the primary key of
another relation. It establishes relationships between
tables. Example: BRANCH_CODE in the STUDENT table is a foreign key
that refers to the primary key BRANCH_CODE in the BRANCH table.
P a g e 18 | 100
DATABASE MANAGEMENT SYSTEMS
5. Composite Key
A Composite Key is formed by combining two or more attributes to uniquely
identify a tuple. Example: A combination
of FIRST_NAME and LAST_NAME could be a composite key if no one in the
database shares the same full name.
Simplicity: We have seen that both the hierarchical and network models are
conceptually simple, but relational model is simpler than both of those two.
Ease of Use: Users can easily access/retrieve the required information from the
database. The Relational model in DBMS is easy as tables consisting of rows
and columns are quite
Cost: The relational database system is costly to set up and maintain. The initial
cost of the software alone can be quite high for smaller businesses.
P a g e 19 | 100
DATABASE MANAGEMENT SYSTEMS
Lack of Scalability: While using the relational database over multiple servers,
its structure changes and becomes difficult to handle, especially when the
quantity of the data is large. Due to this, the data is not scalable on different
physical storage servers. Ultimately, its performance is affected i.e. lack of
availability of data and load time etc.
2. Attributes and Methods: Every object has certain characteristics. These are
represented using Attributes. The behaviour of the objects is represented using
Methods.
3. Class: Similar attributes and methods are grouped together using a class. An
object can be called as an instance of the class.
P a g e 20 | 100
DATABASE MANAGEMENT SYSTEMS
4. Inheritance: A new class can be derived from the original class. The derived
class contains attributes and methods of the original class as well as its own
Advantages:
• Supports complex data types (e.g., images, audio, video).
• Good for multimedia, CAD/CAM, AI applications.
• Closer to real-world modelling.
Disadvantages:
• Complex to implement.
• Not widely supported like relational databases.
• Slower performance for large datasets.
In database design, keys are used to uniquely identify rows (records) in a table
and define relationships between tables.
They are fundamental to maintaining data integrity, eliminating redundancy,
and enforcing uniqueness.
1. Primary Key
Definition:
A Primary Key is a column or group of columns that uniquely identifies each
row in a table.
It cannot be NULL and must be unique.
Rules:
• Only one primary key per table.
• Cannot have duplicate or NULL values.
Example:
P a g e 21 | 100
DATABASE MANAGEMENT SYSTEMS
STUDENT Table
StudentID (PK) Name Age
101 Rohan 20
102 Meena 21
Here, StudentID is the Primary Key because it uniquely identifies each student.
2. Candidate Key
Definition:
A Candidate Key is any column or set of columns that can uniquely identify
rows in a table.
Among all candidate keys, one is chosen as the primary key.
Characteristics:
• All primary keys are candidate keys.
• A table can have multiple candidate keys.
• Candidate keys are minimal (no extra attribute).
Example:
EMPLOYEE Table
EmpID Email Mobile
E001 john@[Link] 9876543210
E002 jane@[Link] 9876543222
Candidate keys:
• EmpID
• Email
• Mobile
(Any of these can uniquely identify a record)
3. Super Key
Definition:
A Super Key is any set of attributes (columns) that can uniquely identify a
row.
It may include extra attributes not necessary for uniqueness.
Difference with Candidate Key:
• Super Key = Candidate Key + Extra columns.
• Candidate Key is a minimal super key.
Example:
P a g e 22 | 100
DATABASE MANAGEMENT SYSTEMS
4. Foreign Key
Definition:
A Foreign Key is a column (or group of columns) in one table that refers to the
primary key of another table.
Purpose:
• Creates a relationship between two tables.
• Ensures referential integrity – i.e., values in the foreign key must match
values in the referenced primary key.
Example:
DEPARTMENT Table
DeptID (PK) DeptName
1 IT
2 HR
EMPLOYEE Table
EmpID Name DeptID (FK)
101 John 1
102 Alia 2
• DeptID in the EMPLOYEE table is a foreign key referencing the
DEPARTMENT table.
5. Composite Key
Definition:
A Composite Key is a primary key made up of two or more columns.
Together, these columns uniquely identify a record, but individually they
may not.
Example:
ENROLLMENT Table
StudentID CourseID Grade
101 C101 A
P a g e 23 | 100
DATABASE MANAGEMENT SYSTEMS
2. Unique Key
Definition:
A Unique Key constraint ensures that all values in a column or a combination
of columns are unique across the table.
• Allows one NULL value (unlike Primary Key).
• Can be applied to multiple columns.
Example: SQL
CREATE TABLE Employee (
P a g e 24 | 100
DATABASE MANAGEMENT SYSTEMS
3. Surrogate Key
Definition:
A Surrogate Key is a system-generated unique identifier for a record,
typically an auto-incrementing number.
• Not derived from application data.
• Has no business meaning; used internally.
Example:
EmpID (Surrogate Key) Name NationalID
1 Raj IN123456
2 Meera IN654321
• EmpID is a surrogate key (auto-incremented).
• NationalID is business data but not used as the primary key.
TABLE CONSTRAINTS
Constraints are rules applied on table columns to enforce data integrity.
SQL
P a g e 25 | 100
DATABASE MANAGEMENT SYSTEMS
4. UNIQUE Constraint
• Ensures all values in the column are unique.
• Allows only one NULL.
sql
CREATE TABLE Users (
UserID INT,
Email VARCHAR (100) UNIQUE
);
5. CHECK Constraint
• Ensures values meet a specific condition.
• Used to validate data input.
sql
CREATE TABLE Account (
AccNo INT,
Balance DECIMAL CHECK (Balance >= 0)
);
P a g e 26 | 100
DATABASE MANAGEMENT SYSTEMS
Introduction of ER Model
P a g e 27 | 100
DATABASE MANAGEMENT SYSTEMS
Entities
Definition:
An Entity is a real-world object or concept that can be clearly identified and
stored in a database.
Entities can be:
• Physical objects: Student, Car, Book
• Conceptual objects: Course, Department, Company
Types of Entities:
• Strong Entity: Exists independently and has a primary key
Example: Student, Employee
• Weak Entity: Cannot exist without a related strong entity
Example: OrderItem (dependent on Order)
Attribute
P a g e 28 | 100
DATABASE MANAGEMENT SYSTEMS
What is an Attribute?
In the Entity-Relationship (ER) Model, an attribute is a property or
characteristic that describes an entity.
• An entity is a real-world object (like a Student, Employee, Book, etc.)
• Attributes store data values related to the entity.
Example:
For the entity Student, typical attributes might be:
• Roll Number
• Name
• Date of Birth
• Email
• Phone Number
Types of Attributes
Attributes are categorized based on their structure, value, and how they relate to
the entity. The main types are:
1. Key Attribute
The attribute which uniquely identifies each entity in the entity set is called the
key attribute. For example, Roll_No will be unique for each student. In ER
diagram, the key attribute is represented by an oval with an underline.
Key Attribute
2. Composite Attribute
An attribute composed of many other attributes is called a composite attribute.
For example, the Address attribute of the student Entity type consists of Street,
City, State, and Country. In ER diagram, the composite attribute is represented
by an oval comprising of ovals.
P a g e 29 | 100
DATABASE MANAGEMENT SYSTEMS
Composite Attribute
3. Multivalued Attribute
An attribute consisting of more than one value for a given entity. For example,
Phone_No (can be more than one for a given student). In ER diagram, a
multivalued attribute is represented by a double oval.
Multivalued Attribute
4. Derived Attribute
An attribute that can be derived from other attributes of the entity type is known
as a derived attribute. e.g.; Age (can be derived from DOB). In ER diagram, the
derived attribute is represented by a dashed oval.
Derived Attribute
The Complete Entity Type Student with its Attributes can be represented as:
P a g e 30 | 100
DATABASE MANAGEMENT SYSTEMS
22
P a g e 31 | 100
DATABASE MANAGEMENT SYSTEMS
What is Schema?
A schema is the blueprint or structure that defines how data is organized and
stored in a database. It outlines the tables, fields, relationships, views, indexes,
and other elements within the database. The schema defines the logical view of
the entire database and specifies the rules that govern the data, including its
types, constraints, and relationships.
P a g e 32 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 33 | 100
DATABASE MANAGEMENT SYSTEMS
1. Physical Level
physical level of a database describes how the data is being stored in secondary
storage devices like disks and tapes and also gives insights on additional storage
details.
2. Conceptual Level
3. External Level
An external level specifies a view of the data in terms of conceptual level
tables. Each external level view is used to cater to the needs of a particular
category of users. For Example, FACULTY of a university is interested in
looking course details of students, STUDENTS are interested in looking at all
details related to academics, accounts, courses and hostel details as well. So,
different views can be generated for different users. The main focus of external
level is data abstraction.
P a g e 34 | 100
DATABASE MANAGEMENT SYSTEMS
UNIT-2
P a g e 35 | 100
DATABASE MANAGEMENT SYSTEMS
1. Selection(σ)
The Selection Operation is basically used to filter out rows from a given table
based on certain given condition. It basically allows us to retrieve only those
rows that match the condition as per condition passed during SQL Query.
Example: If we have a relation R with attributes A, B, and C, and we want to
select tuples where C > 3, we write:
A B C
1 2 4
2 2 3
3 2 3
4 3 4
P a g e 36 | 100
DATABASE MANAGEMENT SYSTEMS
Output:
A B C
1 2 4
4 3 4
Explanation: The selection operation only filters rows but does not display or
change their order. The projection operator is used for displaying specific
columns.
2. Projection(π)
While Selection operation works on rows, similarly projection operation of
relational algebra works on columns. It basically allows us to pick specific
columns from a given relational table based on the given condition and ignoring
all the other remaining columns.
Example: Suppose we want columns B and C from Relation R.
Output:
B C
2 4
2 3
3 4
SET OPERATIONS
3. Union(U)
The Union Operator is basically used to combine the results of two queries into
a single result. The only condition is that both queries must return same number
P a g e 37 | 100
DATABASE MANAGEMENT SYSTEMS
of columns with same data types. Union operation in relational algebra is the
same as union operation in set theory.
Example: Consider the following table of Students having different optional
subjects in their course.
FRENCH
Student_Name Roll_Number
Ram 01
Mohan 02
Vivek 13
Geeta 17
GERMAN
Student_Name Roll_Number
Vivek 13
Geeta 17
Shyam 21
Rohan 25
Ram
Mohan
P a g e 38 | 100
DATABASE MANAGEMENT SYSTEMS
Student_Name
Vivek
Geeta
Shyam
Rohan
Explanation: The only constraint in the union of two relations is that both
relations must have the same set of Attributes.
4. Intersection (∩)
The Intersection Operator is used to fetch common tuples that exist in the
result of both queries. In relational algebra, the intersection operation follows
the same rules as in set theory.
The condition is that both relations must have the same number of
columns and the same data types (i.e., they must be union-compatible).
Example:
Consider the following tables representing students who have chosen different
optional subjects:
FRENCH
Student_Name Roll_Number
Ram 01
Mohan 02
Vivek 13
Geeta 17
P a g e 39 | 100
DATABASE MANAGEMENT SYSTEMS
GERMAN
Student_Name Roll_Number
Vivek 13
Geeta 17
Shyam 21
Rohan 25
π(Student_Name)(FRENCH) ∩ π(Student_Name)(GERMAN)
Output:
Student_Name
Vivek
Geeta
Explanation:
• The intersection returns only those student names that appear in both
FRENCH and GERMAN relations.
• Like union, intersection also requires the same set of attributes in both
relations (here, Student_Name).
P a g e 40 | 100
DATABASE MANAGEMENT SYSTEMS
5. Set Difference(-)
Set difference basically provides the rows that are present in one table, but not
in another tables. Set Difference in relational algebra is the same set difference
operation as in set theory.
Example: To find students enrolled only in FRENCH but not in GERMAN,
we write:
π(Student_Name)(FRENCH) - π(Student_Name)(GERMAN)
Student_Name
Ram
Mohan
Explanation: The only constraint in the Set Difference between two relations is
that both relations must have the same set of Attributes.
6. Rename(ρ)
Rename operator basically allows you to give a temporary name to a specific
relational table or to its columns. It is very useful when we want to avoid
ambiguity, especially in complex Queries. Rename is a unary operation used for
renaming attributes of a relation.
Example: We can rename an attribute B in relation R to D
A B C
1 2 4
2 2 3
3 2 3
4 3 4
P a g e 41 | 100
DATABASE MANAGEMENT SYSTEMS
A D C
1 2 4
2 2 3
3 2 3
4 3 4
7. Cartesian Product(X)
The Cartesian product combines every row of one table with every row of
another table, producing all the possible combination. It's mostly used as a
precursor to more complex operation like joins. Let’s say A and B, so the cross
product between A X B will result in all the attributes of A followed by each
attribute of B. Each record of A will pair with every record of B.
Relation A:
Name Age Sex
Ram 14 M
Sona 15 F
Kim 20 M
Relation B:
ID Course
1 DS
2 DBMS
Output: If relation A has 3 rows and relation B has 2 rows, the Cartesian
product A × B will result in 6 rows.
P a g e 42 | 100
DATABASE MANAGEMENT SYSTEMS
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
Kim 20 M 2 DBMS
Explanation: If A has 'n' tuples and B has 'm' tuples then A X B will have 'n*m'
tuples.
P a g e 43 | 100
DATABASE MANAGEMENT SYSTEMS
ere Salary > 50000 will return employees in departments with a salary
greater than 50,000
• Equi Join: An equi join is a type of conditional join where the condition
is specifically equality (=) between columns from both
relations. Example: Joining Customers and Orders on CustomerID where
both relations have this column, returning only matching records.
• Natural Join: A natural join automatically combines relations based on
columns with the same name and type, removing duplicate columns in the
result. It’s a more efficient way of
joining. Example: Joining Students and Enrollments where StudentID is
common in both, and the result contains only unique columns.
Outer Join
An outer join returns all rows from one relation, and the matching rows from
the other relation. If there is no match, the result will still include all rows from
the outer relation with NULL values in the columns from the unmatched
relation.
• Left Outer Join: A left outer join returns all rows from the left relation
and the matching rows from the right relation. If there is no match, the
result will include NULL values for the right relation’s
attributes. Example: Joining Employees with Departments using a left
outer join ensures all employees are listed, even those who aren't assigned
to any department, with NULL values for the department columns.
• Right Outer Join: A right outer join returns all rows from the right
relation and the matching rows from the left relation. If no match exists,
the left relation's columns will
contain NULL values. Example: Joining Departments with Employees u
sing a right outer join includes all departments, even those with no
employees assigned, filling unmatched employee columns with NULL.
• Full Outer Join: A full outer join returns all rows when there is a match
in either the left or right relation. If a row from one relation does not have
a match in the other, NULL values are included for the missing
side. Example: Joining Customers and Orders using a full outer join will
return all customers and orders, even if there’s no corresponding order for
a customer or no customer for an order.
P a g e 44 | 100
DATABASE MANAGEMENT SYSTEMS
Division (÷)
The Division Operator is used to find tuples in one relation that are related to
all tuples in another relation. It’s typically used for "for all" queries.
Student_Course (Dividend Table):
Student_ID Course_ID
101 C1
101 C2
102 C1
103 C1
103 C2
C1
C2
Example: Query is to find students who are enrolled in all courses listed in
the Course table. In this case, students must be enrolled in both C1 and C2.
Student_Course(Student_ID, Course_ID)÷ Course(Course_ID)
Output:
Student_ID
101
103
P a g e 45 | 100
DATABASE MANAGEMENT SYSTEMS
Relational Calculus
Relational calculus is a non-procedural query language used in the context of
relational algebra. It focuses on what data to retrieve, rather than how to
retrieve it, making it different from relational algebra, which is procedural.
In relational calculus, queries are expressed using logical formulas that
describe the desired result, without specifying the exact steps to get there.
There are two types of Relational Calculus
1. Tuple Relational Calculus(TRC)
2. Domain Relational Calculus(DRC)
For example, let's say we have a table called "Employees" with the
following attributes:
Employee ID
Name
Salary
Department ID
To retrieve the names of all employees who earn more than $50,000 per year,
we can use the following TRC query:
{ t | Employees(t) ∧ [Link] > 50000 }
P a g e 46 | 100
DATABASE MANAGEMENT SYSTEMS
Saurabh A7 Patiala
Mehak B6 Jalandhar
Sumiti D9 Ludhiana
Ria A5 Patiala
Table Branch
Branch name Branch City
ABC Patiala
DEF Ludhiana
GHI Jalandhar
Table Account
Account number Branch name Balance
P a g e 47 | 100
DATABASE MANAGEMENT SYSTEMS
Table Loan
Loan number Branch name Amount
Table Borrower
Customer name Loan number
Saurabh L33
Mehak L49
Ria L98
Table Depositor
Customer name Account number
Saurabh 1111
Mehak 1113
Suniti 1114
P a g e 48 | 100
DATABASE MANAGEMENT SYSTEMS
Example 1: Find the loan number, branch, and amount of loans greater than or
equal to 10000 amount.
{t| t ∈ loan ∧ t[amount]>=10000}
Resulting relation:
Loan number Branch name Amount
L33
L35
L98
SQL Commands
SQL commands are the fundamental building blocks for communicating with
a database management system (DBMS). It is used to interact with the database
with some operations. It is also used to perform specific tasks, functions,
and queries of data. SQL can perform various tasks like creating a table, adding
data to tables, dropping the table, modifying the table, set permission for users.
SQL Commands are mainly categorized into five categories:
• DDL – Data Definition Language
P a g e 49 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 50 | 100
DATABASE MANAGEMENT SYSTEMS
procedure, and
triggers)
Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);
In this example, a new table called employees is created with columns for
employee ID, first name, last name and hire date.
P a g e 51 | 100
DATABASE MANAGEMENT SYSTEMS
Delete records
DELETE FROM table_name WHERE
DELETE from a database
condition;
table
Table control
LOCK LOCK TABLE table_name IN lock_mode;
concurrency
Call a PL/SQL
CALL or JAVA CALL procedure_name(arguments);
subprogram
Describe the
EXPLAIN EXPLAIN PLAN FOR SELECT * FROM
access path to
PLAN table_name;
data
Example:
INSERT INTO employees (first_name, last_name, department)
VALUES ('Jane', 'Smith', 'HR');
This query inserts a new record into the employees table with the first name
'Jane', last name 'Smith' and department 'HR'.
P a g e 52 | 100
DATABASE MANAGEMENT SYSTEMS
UPDATE Command
This command is used to alter existing table records. Within a table, it modifies
data from one or more records. This command is used to alter the data which is
already present in a table.
Syntax:
UPDATE <table_name>
SET <column_name = value>
WHERE condition;
Example:
UPDATE students
SET due_fees = 20000
WHERE stu_name = 'Mini';
DELETE Command
It deletes all archives from a table. This command is used to erase some or all of
the previous table's records. If we do not specify the 'WHERE' condition then
all the rows would be erased or deleted.
Syntax:
DELETE FROM <table_name>
WHERE <condition>;
Example:
DELETE FROM students
WHERE stu_id = '001';
Advantages of DML
• DML statements could alter the data that is contained or stored in the
database.
• It delivers effective human contact with the machine.
• User could specify what data is required.
• DML aims to have many different varieties and functionalities between
vendors providing databases.
Disadvantages of DML
• We cannot use DML to change the structure of the database.
• Limit table view i.e., it could conceal some columns in tables.
P a g e 53 | 100
DATABASE MANAGEMENT SYSTEMS
• Access the data without having the data stored in the object.
• Unable to build or erase lists or sections using DML.
SQL Aggregate Functions are used to perform calculations on a set of rows and
return a single value. These functions are particularly useful when we need to
summarize, analyze, or group large datasets in SQL databases. Whether you are
working with sales data, employee records or product inventories, aggregate
functions help us derive meaningful insights.
They are often used with the GROUP BY clause in SQL to summarize data for
each group. Commonly used aggregate functions include COUNT(), SUM(),
AVG(), MIN() and MAX(). In this article, we will explain the most commonly
used SQL aggregate functions, their syntax, practical examples, and how to
make the best use of them in your queries.
Examples:
-- Total number of records in the table
SELECT COUNT(*) AS TotalRecords FROM Employee;
2. SUM()
The SUM() function calculates the total sum of a numeric column.
SUM(column_name): Returns the total sum of all non-NULL values in a
column.
Examples:
-- Calculate the total salary
SELECT SUM(Salary) AS TotalSalary FROM Employee;
P a g e 55 | 100
DATABASE MANAGEMENT SYSTEMS
Examples:
-- Find the highest salary
SELECT MAX(Salary) AS HighestSalary FROM Employee;
SQL Logical Operators are essential tools used to test the truth of conditions
in SQL queries. They return Boolean values such as TRUE, FALSE,
or UNKNOWN, making them invaluable for filtering, retrieving,
or manipulating data. These operators allow developers to build complex
queries by combining, negating, or comparing conditions effectively.
We will use the following employee table throughout the examples. This table
represents employee details, including their unique ID, name, city,
and country.
P a g e 56 | 100
DATABASE MANAGEMENT SYSTEMS
1. AND Operator
The AND operator is used to combine two or more conditions in an SQL
query. It returns records only when all conditions specified in the query
are true. This operator is commonly used when filtering data that must satisfy
multiple criteria simultaneously.
Example
Retrieve the records of employees from the employees table who are located
in 'Allahabad' and belong to 'India', ensuring that both conditions are met.
Query:
2. IN Operator
The IN operator simplifies the process of checking if a value matches any
value in a list, making it more efficient and readable compared to using
multiple OR conditions. This operator is especially helpful when we need to
filter results based on multiple possible values for a given column, reducing
the complexity of the query.
Example
Retrieve the records of employees from the employee table who are located in
either 'Allahabad' or 'Patna'.
Query:
SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');
Output
P a g e 57 | 100
DATABASE MANAGEMENT SYSTEMS
3. NOT Operator
The NOT operator is used to reverse the result of a condition,
returning TRUE when the condition is FALSE. It is typically used to exclude
records that match a specific condition, making it useful for filtering out
unwanted data.
Example
Retrieve the records of employees from the employee table whose city names
do not start with the letter 'A'.
Query:
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output
4. OR Operator
The OR operator combines multiple conditions in a SQL query and
returns TRUE if at least one of the conditions is satisfied. It is ideal for
situations where you want to retrieve records that meet any of several possible
conditions.
Example
Retrieve the records of employees from the employee table who are either
from 'Varanasi' or have 'India' as their country.
Query
SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country =
'India';
Output
P a g e 58 | 100
DATABASE MANAGEMENT SYSTEMS
5. LIKE Operator
The LIKE operator in SQL is used in the WHERE clause to search for a
specified pattern in a column. It is particularly useful when we want to perform
pattern matching on string data. The LIKE operator works with two main
wildcards:
• %: Represents zero or more characters. It allows matching any sequence
of characters in the string.
• _: Represents exactly one character. It is used when you want to match a
specific number of characters at a given position.
Example
Retrieve the records of employees from the employee table whose city names
start with the letter 'P'.
Query:
SELECT * FROM employee WHERE emp_city LIKE 'P%';
Output
6. BETWEEN Operator
The BETWEEN operator in SQL allows us to test if a value or expression lies
within a specified range. The BETWEEN condition is inclusive, meaning it
includes both the lower and in the results. This operator is particularly useful
when we need to filter records based on a range of values, such as numerical
ranges, dates, or even text values.
Example
Retrieve the records of employees from the employee table
whose emp_id values fall within the range of 101 to 104 (inclusive).
Query:
SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;
Output
P a g e 59 | 100
DATABASE MANAGEMENT SYSTEMS
7. ALL Operator
The ALL operator in SQL is used to compare a value to all values returned by a
subquery. It returns TRUE if the condition specified is TRUE for all values
retrieved by the subquery. The ALL operator is commonly used
with SELECT, WHERE, and HAVING clauses to ensure that a value satisfies
a condition when compared to a set of values.
Example
Retrieve the records of employees whose emp_id is equal to all emp_id values
in the employees table where the emp_city is 'Varanasi'.
Query:
SELECT * FROM employee WHERE emp_id = ALL
(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
Output
8. ANY Operator
The ANY operator in SQL is used to compare a value with the results of
a subquery. It returns TRUE if the value satisfies the condition with any of the
values returned by the subquery. This operator allows for greater flexibility
when you want to check if a value matches at least one of the results in a set of
values.
Example
Retrieve the records of employees whose emp_id matches any of
the emp_id values in the employees table where the emp_city is 'Varanasi'.
Query:
SELECT * FROM employee WHERE emp_id = ANY
(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
P a g e 60 | 100
DATABASE MANAGEMENT SYSTEMS
Output
9. EXISTS Operator
The EXISTS operator in SQL is used to check whether a subquery returns any
rows. It evaluates to TRUE if the subquery results in one or more rows.
The EXISTS operator is typically used with SELECT, UPDATE, INSERT,
and DELETE statements to determine if any rows exist that meet a specified
condition. It is often used in correlated subqueries where the subquery
references columns from the outer query.
Example
Retrieve the names of employees from the employee table if there are any
employees in the employee table who are located in 'Patna'.
Query
SELECT emp_name FROM employee WHERE EXISTS
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Output
P a g e 61 | 100
DATABASE MANAGEMENT SYSTEMS
Example
Retrieve the records of employees from the employee table where the emp_id is
less than any of the emp_id values from employees located in 'Patna'.
Query:
SELECT * FROM employee WHERE emp_id < SOME
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Output
1. LIKE Predicate
Purpose: Used to search for a specified pattern in a column (mostly with
CHAR, VARCHAR).
Syntax:
SELECT * FROM table_name WHERE column_name LIKE pattern;
Wildcards:
• % – matches any sequence of characters (including none)
• _ – matches a single character
P a g e 62 | 100
DATABASE MANAGEMENT SYSTEMS
Examples:
-- Names starting with 'A'
SELECT * FROM students WHERE name LIKE 'A%';
2. BETWEEN Predicate
Purpose: Filters data that lies within a specific range (inclusive).
Syntax:
SELECT * FROM table_name WHERE column_name BETWEEN value1
AND value2;
Examples:
-- Salaries between 30000 and 50000
SELECT * FROM employees WHERE salary BETWEEN 30000 AND 50000;
3. DISTINCT Predicate
Purpose: Removes duplicate values from the result set.
Syntax:
SELECT DISTINCT column1, column2 FROM table_name;
Examples:
-- Unique department names
SELECT DISTINCT department FROM employees;
P a g e 63 | 100
DATABASE MANAGEMENT SYSTEMS
-- Table alias
SELECT [Link], d.department_name
FROM employees AS e
JOIN departments AS d ON e.department_id = [Link];
HAVING condition;
Example:
• Example:
-- List of employees sorted by salary (highest first)
SELECT name, salary
FROM employees
ORDER BY salary DESC;
Syntax (MySQL):
SELECT * FROM table_name LIMIT 5;
Syntax (SQL Server):
SELECT TOP 5 * FROM table_name;
P a g e 65 | 100
DATABASE MANAGEMENT SYSTEMS
Example:
-- Top 3 highest-paid employees
SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;
Functional Dependencies
In this case:
• Roll_No → Name (Each roll number uniquely identifies a name)
• Roll_No → Department (Each roll number belongs to one department)
• But Name → Roll_No is NOT true (Because "Alice" can have multiple
roll numbers)
P a g e 66 | 100
DATABASE MANAGEMENT SYSTEMS
Notation:
If X → Y, and Y ⊆ X, then it is a trivial dependency.
Example:
• A→A
• AB → A
These are always true for any table.
4. Partial Dependency
Definition:
A functional dependency is partial if a non-prime attribute is functionally
dependent on part of a candidate key or composite primary key.
Occurs in:
2NF normalization.
Example:
P a g e 67 | 100
DATABASE MANAGEMENT SYSTEMS
5. Transitive Dependency
Definition: A transitive dependency is a type of functional dependency
which happens when it is indirectly formed by two functional dependencies.
A functional dependency X → Z is transitive if:
• X → Y and
• Y → Z,
Then X → Z is transitive.
Occurs in:
3NF normalization.
Example:
• EmpID → DeptID
• DeptID → DeptName
→ So, EmpID → DeptName (transitive dependency)
7. Join Dependency
Definition:
A join dependency occurs when a table can be split into two or more relations
and reconstructed by joining them without data loss.
Occurs in:
5NF (Project-Join Normal Form)
Example:
P a g e 68 | 100
DATABASE MANAGEMENT SYSTEMS
Armstrong's Axioms
P a g e 69 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 70 | 100
DATABASE MANAGEMENT SYSTEMS
P a g e 71 | 100
DATABASE MANAGEMENT SYSTEMS
In 1NF:
Student Course
Raj DBMS
Raj OS
Definition:
A relation is in 2NF if:
1. It is already in 1NF, and
2. No partial dependency exists (i.e., no non-prime attribute depends on a
part of a composite primary key).
Applies only when the primary key is composite.
Example:
Before 2NF:
StudentID CourseCode StudentName
1 DB101 Aditi
1 OS102 Aditi
Definition:
A relation is in 3NF if:
1. It is in Second Normal Form (2NF)
2. No transitive dependency exists — i.e., every non-prime attribute is
only dependent on a candidate key, not on another non-prime attribute.
P a g e 72 | 100
DATABASE MANAGEMENT SYSTEMS
Formal Rule:
For any functional dependency X → A, at least one of the following must be
true:
• A is a prime attribute (i.e., part of a candidate key)
• X is a super key
Example:
EmpID EmpName DeptID DeptName
1 Alice 10 CSE
2 Bob 20 ECE
FDs:
• EmpID → EmpName, DeptID
• DeptID → DeptName
P a g e 73 | 100
DATABASE MANAGEMENT SYSTEMS
Convert to BCNF:
Instructor Table
Instructor → Course
Enrolment Table
Student, Instructor
Now all FDs have super keys on LHS
Denormalization
Definition:
Denormalization is the process of combining normalized tables into fewer
tables to improve read performance at the cost of redundancy.
Why Denormalize?
Benefit Cost
Faster query performance Increased redundancy
Fewer joins Update anomalies possible
Simpler data retrieval Larger storage
Example:
After normalizing:
Employee Table
EmpID | Name | DeptID
Department Table
DeptID | DeptName
P a g e 74 | 100
DATABASE MANAGEMENT SYSTEMS
UNIT -3
ACID Properties:
In Database Management Systems (DBMS), ACID properties are the key
principles that ensure reliable transactions. They stand for:
1. Atomicity
• "All or nothing" rule: A transaction is treated as a single unit.
• Either all operations in the transaction are performed, or none are.
Example: In a banking transaction, if ₹1000 is transferred from Account A to
Account B:
• Deduction from A and addition to B both must happen.
• If any part fails, the whole transaction is rolled back.
2. Consistency
• A transaction must bring the database from one valid state to another.
• Ensures that all defined rules, constraints, and triggers are maintained.
Before and after the transaction, the total money in the system remains
same.
Example: If A = ₹1000 and B = ₹2000, total = ₹3000.
After transfer → A = ₹500, B = ₹2500, total still = ₹3000.
3. Isolation
• Transactions occur independently of one another.
• The intermediate state of a transaction is invisible to others.
• Example: If two people book the last movie ticket at the same time,
isolation ensures that only one transaction succeeds, preventing double-
booking.
Or
If two people try to transfer money from the same account at the
same time, each transaction runs independently.
One transaction will finish first, then the other executes — preventing
incorrect balances.
4. Durability
• Once a transaction is committed, it is permanently recorded in the
database, even if the system crashes.
P a g e 75 | 100
DATABASE MANAGEMENT SYSTEMS
Transaction in DBMS
Operations of Transaction
A user can make different types of requests to access and modify the contents of
a database. So, we have different types of operations relating to a transaction.
They are discussed as follows:
1) Read(X)
A read operation is used to read the value of a particular database element X and
stores it in a temporary buffer in the main memory for further actions such as
displaying that value.
Example: For a banking system, when a user checks their balance, a Read
operation is performed on their account balance:
SELECT balance FROM accounts WHERE account_id = 'A123';
This updates the balance of the user's account after withdrawal.
2) Write(X)
P a g e 76 | 100
DATABASE MANAGEMENT SYSTEMS
A write operation stores updated data from main memory back to the database.
It usually follows a read, where data is fetched, modified (e.g., arithmetic
changes), and then written back to save the updated value.
Example: For the banking system, if a user withdraws money,
a Write operation is performed after the balance is updated:
UPDATE accounts SET balance = balance - 100 WHERE account_id = 'A123';
This updates the balance of th e user’s account after withdrawal.
3) Commit
This operation in transactions is used to maintain integrity in the database. Due
to some failure of power, hardware, or software, etc., a transaction might get
interrupted before all its operations are completed. This may cause ambiguity in
the database, i.e. it might get inconsistent before and after the transaction.
Example: After a successful money transfer in a banking system,
a Commit operation finalizes the transaction:
COMMIT;
Once the transaction is committed, the changes to the database are permanent,
and the transaction is considered successful.
4) Rollback
A rollback undoes all changes made by a transaction if an error occurs, restoring
the database to its last consistent state. It helps prevent data inconsistency and
ensures safety.
Example: Suppose during the money transfer process, the system encounters an
issue, like insufficient funds in the sender’s account. In that case, the transaction
is rolled back:
ROLLBACK;
Transaction Schedules
When multiple transaction requests are made at the same time, we need to
decide their order of execution. Thus, a transaction schedule can be defined as a
chronological order of execution of multiple transactions. Example: After a
successful transfer, the updated balance remains safe despite a power failure.
There are broadly two types of transaction schedules discussed as follows:
i) Serial Schedule
In a serial schedule, transactions execute one at a time, ensuring database
consistency but increasing waiting time and reducing system throughput. To
improve throughput while maintaining consistency, concurrent schedules with
strict rules are used, allowing safe simultaneous execution of transactions.
P a g e 77 | 100
DATABASE MANAGEMENT SYSTEMS
Concurrency in DBMS
• In a DBMS, concurrency means that multiple users or transactions can
access the database at the same time.
• Example: In an online shopping system:
o One user is placing an order.
o Another is updating their profile.
o Another is browsing products.
All these transactions are running concurrently on the same
database.
2. Lost Update
• Definition: Two transactions update the same data at the same time, and
one update overwrites the other.
• Example:
o Balance in account = ₹1000.
o T1: Withdraws ₹200 → plans to update balance to ₹800.
o T2: Deposits ₹500 → plans to update balance to ₹1500.
o If both read the balance as ₹1000 before updating, and then both
write:
▪ T1 writes 800, then
P a g e 78 | 100
DATABASE MANAGEMENT SYSTEMS
2. Locking in DBMS
• Locking is a concurrency control technique in DBMS.
• It ensures that when one transaction is accessing or modifying a piece of
data, other transactions must wait until the lock is released.
Types of Locks:
1. Shared Lock (S-Lock)
o Allows multiple transactions to read the same data at the same
time.
o But no one can write until all readers are finished.
o Example: Many users checking their account balance.
2. Exclusive Lock (X-Lock)
o Allows only one transaction to read/write the data.
o Prevents others from accessing the same data until the lock is
released.
o Example: Only one user can update the account balance at a time.
P a g e 79 | 100
DATABASE MANAGEMENT SYSTEMS
Crash Recovery
The goal is to ensure that the database continues to satisfy the ACID
properties, even after a crash.
Recovery Techniques
Crash recovery is based on logs (Write-Ahead Logging - WAL principle).
1. Write-Ahead Logging (WAL)
• Every change is first written to a log file before being applied to the
database.
• Ensures durability and recoverability.
P a g e 80 | 100
DATABASE MANAGEMENT SYSTEMS
2. Log-Based Recovery
Logs keep track of:
• START T → transaction started
• UPDATE T, X, old_v alue, new_value → transaction modified data
• COMMIT T → transaction completed successfully
• ROLLBACK T → transaction was und one
3. Checkpointing
• A checkpoint is a snapshot of the database + log at a certain point.
• It reduces recovery time by marking a safe point from where recovery can
start.
• Example: Instead of scanning the entire log, recovery starts from the last
checkpoint.
4. Shadow Paging
• Instead of updating pages directly, DB creates a shadow copy.
• If the transaction commits → new copy replaces old copy.
• If it crashes → old copy remains intact.
• Simple but less efficient for large systems.
P a g e 81 | 100
DATABASE MANAGEMENT SYSTEMS
Types of 2PL
1. Basic 2PL – Just follow the two phases.
2. Conservative (Static) 2PL – Transaction requests all locks at the start
before execution. Prevents deadlock but reduces concurrency.
3. Strict 2PL – All exclusive (write) locks are released only after
commit/rollback. Ensures recoverability and prevents cascading
rollbacks.
4. Rigorous 2PL – All locks (read + write) are released only at commit.
Strongest isolation.
Example
Transaction T1: Reads and updates A.
Transaction T2: Reads and updates B.
• T1 acquires lock on A → updates A.
• T2 acquires lock on B → updates B.
• If both try to lock each other’s items, 2PL ensures order and
serializability.
2. Serializability
Definition:
Serializability ensures that the concurrent execution of transactions is
equivalent to some serial execution (i.e., one transaction after another).
P a g e 82 | 100
DATABASE MANAGEMENT SYSTEMS
Types of Serializability
1. Conflict Serializability
o Two schedules are conflict equivalent if you can swap non-
conflicting operations to transform one schedule into the other.
o Conflict = when two operations access the same data item and at
least one is a write.
o Ensured by precedence (serialization) graphs.
2. View Serializability
o Two schedules are view equivalent if:
1. They read the same initial values.
2. Transactions read the same values written by others.
3. Final writes are the same.
o Weaker but more general than conflict serializability.
Example
Schedule:
T1: Read(A), Write(A)
T2: Read(A), Write(A)
If T1 writes A first, then T2 overwrites, it must be equivalent to serial order (T1
→ T2).
3. Deadlocks
Definition:
A deadlock occurs when two or more transactions are waiting for each other’s
locks and none of them can proceed.
It’s like two people holding one key each but needing both keys to continue.
Deadlock Example
• T1 locks A, requests B.
• T2 locks B, requests A.
• Neither can proceed → deadlock.
Deadlock Handling
1. Deadlock Prevention
P a g e 83 | 100
DATABASE MANAGEMENT SYSTEMS
4. Lock Management
Definition:
Lock management is the system mechanism that handles how locks are
requested, granted, and released to maintain consistency and concurrency.
Types of Locks
1. Shared Lock (S) – For reading. Multiple transactions can hold it.
2. Exclusive Lock (X) – For writing. Only one transaction can hold it.
3. Intention Locks – Used in multi-granularity locking (table vs. row).
o IS (Intention Shared) – Intend to acquire shared lock at finer level.
o IX (Intention Exclusive) – Intend to acquire exclusive lock at finer
level.
o SIX – Shared + intention exclusive.
1. File Organization
File organization refers to the way records (rows/tuples) are physically stored in
the database on disk. The choice of organization affects how efficiently data can
be inserted, retrieved, updated, or deleted.
Common Types of File Organization:
• Heap (Unordered) Files
o Records are stored in no particular order.
o New records are simply appended at the end of the file.
o Fast insertion but slower searches (linear scan required).
• Sequential (Ordered) Files
P a g e 84 | 100
DATABASE MANAGEMENT SYSTEMS
2. Index Structures
An index is a data structure that improves the speed of searching and
retrieving rows in a database table. It works like the index in a book, pointing to
the location of needed data.
Common Index Structures:
• Single-Level Index
o A simple list of key values and pointers to records.
o Works like a phone book.
• Multi-Level Index
o Uses multiple levels of indexes for large datasets.
o Example: First-level index points to second-level indexes, which
point to actual data blocks.
• B+ Tree Index
o Most commonly used index in databases.
o Balanced tree structure where internal nodes act as a directory, and
leaf nodes store actual data pointers.
o Supports both equality and range queries efficiently.
• Hash Index
o Uses hash functions to map keys directly to locations.
o Very fast for equality lookups (e.g., WHERE id=101) but poor for
range queries.
P a g e 85 | 100
DATABASE MANAGEMENT SYSTEMS
• Bitmap Index
o Uses bitmaps to represent the existence of a value.
o Efficient for columns with a small number of distinct values (e.g.,
gender, status).
3. Index Tuning
Index tuning means optimizing the use of indexes to improve database
performance.
Activities in Index Tuning:
• Choosing appropriate indexes
o E.g., creating indexes on columns often used in WHERE, JOIN,
GROUP BY, ORDER BY.
• Dropping unused or redundant indexes
o Too many indexes slow down insert/update/delete operations
because all indexes need to be updated.
• Balancing read vs. write performance
o Indexes speed up read operations but add overhead to write
operations.
• Monitoring query performance
o Using tools like query optimizers and execution plans to check
whether indexes are being used effectively.
• Index maintenance
o Rebuilding or reorganizing fragmented indexes to keep them
efficient.
P a g e 86 | 100
DATABASE MANAGEMENT SYSTEMS
Unit-4
Introduction to NoSQL
NoSQL
What is NoSQL?
• NoSQL = “Not Only SQL.”
• A type of database that provides non-relational ways to store and
manage data.
• Designed to handle large-scale, unstructured, and semi-structured
data that traditional relational databases (RDBMS) struggle with.
P a g e 88 | 100
DATABASE MANAGEMENT SYSTEMS
Use of NoSQL
• Big Data Applications: Efficiently stores and processes massive amounts
of unstructured and semi-structured data.
• Real-Time Analytics: Supports fast queries and analysis for use cases
like recommendation engines or fraud detection.
P a g e 89 | 100
DATABASE MANAGEMENT SYSTEMS
• Scalable Web Applications: Handles high traffic and large user bases by
scaling horizontally across servers.
• Flexible Data Storage: Manages diverse data formats (JSON, key-value,
documents, graphs) without rigid schemas.
NoSQL databases can be classified into four main types, based on their data
storage and retrieval methods:
1. Document-based databases
2. Key-value stores
3. Column-oriented databases
4. Graph-based databases
Each type has unique advantages and use cases, making NoSQL a preferred
choice for big data applications, real-time analytics, cloud computing and
distributed systems.
P a g e 90 | 100
DATABASE MANAGEMENT SYSTEMS
Key Features
1. Schema-less → No fixed schema like SQL tables. Each document can
have different fields.
2. Human-readable format → JSON-style documents are easy to
understand.
3. Flexible structure → Can store complex/nested data in a single
document.
4. Indexing support → Allows indexing on fields for fast queries.
5. Horizontal scalability → Easy to scale across multiple servers.
Firebase
Real-time apps, chat applications
Firestore
2. Key-Value Stores
A key-value store is a nonrelational database. The simplest form of a NoSQL
database is a key-value store. Every data element in the database is stored in
key-value pairs. The data can be retrieved by using a unique key allotted to
each element in the database. The values can be simple data types like
P a g e 91 | 100
DATABASE MANAGEMENT SYSTEMS
Amazon
Cloud-based scalable applications
DynamoDB
P a g e 92 | 100
DATABASE MANAGEMENT SYSTEMS
4. Graph-Based Databases
Graph-based databases focus on the relationship between the elements. It
stores the data in the form of nodes in the database. The connections between
the nodes are called links or relationships, making them ideal for complex
relationship-based queries.
• Data is represented as nodes (objects) and edges (connections).
• Fast graph traversal algorithms help retrieve relationships quickly.
• Used in scenarios where relationships are as important as the data itself.
Key features of Graph Database
• Relationship-Centric Storage: Perfect for social networks, fraud
detection, recommendation engines.
• Real-Time Query Processing: Queries return results almost instantly.
• Schema Flexibility: Easily adapts to evolving relationship structures
Popular Graph Databases & Use Cases
Database Use Case
P a g e 93 | 100
DATABASE MANAGEMENT SYSTEMS
Why only 2 of 3?
Because:
• If the system tries to be Consistent + Available, it cannot tolerate
partitions.
• If the system is Consistent + Partition tolerant, some requests may be
denied (low availability).
• If the system is Available + Partition tolerant, it may serve outdated
data (no strong consistency).
P a g e 94 | 100
DATABASE MANAGEMENT SYSTEMS
Real-World Analogy
Imagine an ATM network:
• Consistency → Every ATM shows the exact same account balance.
• Availability → You can always withdraw cash, even if the bank server is
busy.
• Partition Tolerance → ATMs still work even if some servers lose
connection.
You can’t have all 3 at once:
• If the ATM is available during a partition, it might give outdated balance
(AP).
• If the ATM insists on consistency, it may refuse service when
disconnected (CP).
3. BASE vs ACID
Feature ACID (Relational DB) BASE (NoSQL DB)
Atomicity, Consistency, Basically Available, Soft
Stands for
Isolation, Durability State, Eventually Consistent
Data
Strong, reliable Relaxed, flexible
Integrity
Immediate (strong
Consistency Eventual consistency
consistency)
Supports complex
Transaction Lightweight transactions
transactions
Banking, finance, Big Data, real-time apps,
Use Case
sensitive data IoT, social networks
4. CRUD Operations
CRUD = Create, Read, Update, Delete → Fundamental operations for any
database.
• Create → Insert new data (SQL: INSERT, MongoDB: insertOne).
• Read → Retrieve data (SQL: SELECT, MongoDB: find).
• Update → Modify existing data (SQL: UPDATE, MongoDB:
updateOne).
• Delete → Remove data (SQL: DELETE, MongoDB: deleteOne).
P a g e 95 | 100
DATABASE MANAGEMENT SYSTEMS
MongoDB operators
MongoDB operators are special keywords used inside queries and updates to
perform operations like filtering, comparisons, logical conditions, updates,
and aggregation.
2. Logical Operators
Used to combine multiple conditions.
Operator Meaning Example
Returns documents matching { $and: [ { age: { $gt: 18 }
$and
all conditions }, { city: "Delhi" } ] }
Returns documents matching { $or: [ { age: 18 }, { city:
$or
at least one condition "Delhi" } ] }
{ age: { $not: { $gt: 30 } }
$not Negates a condition
}
Opposite of OR (none of the { $nor: [ { age: 18 }, { city:
$nor
conditions should match) "Delhi" } ] }
P a g e 96 | 100
DATABASE MANAGEMENT SYSTEMS
3. Element Operators
Used to check presence/type of fields.
Operator Meaning Example
$exists Checks if a field exists { email: { $exists: true } }
$type Checks data type { age: { $type: "int" } }
4. Evaluation Operators
Used for pattern matching or condition evaluation.
Operator Meaning Example
Matches regex { name: { $regex: "^A" } } →
$regex
patterns names starting with A
Allows expressions in { $expr: { $gt: ["$salary",
$expr
queries "$expenses"] } }
$text Performs text search { $text: { $search: "developer" } }
5. Array Operators
Work with arrays inside documents.
Operator Meaning Example
Matches arrays containing { tags: { $all: ["mongodb",
$all
all specified elements "database"] } }
Matches if at least one array { scores: { $elemMatch: {
$elemMatch
element satisfies condition $gt: 80, $lt: 90 } } }
Matches arrays of a specific
$size { tags: { $size: 3 } }
size
6. Update Operators
Used in updateOne, updateMany, etc.
Operator Meaning Example
$set Updates a field’s value { $set: { age: 30 } }
$unset Removes a field { $unset: { email: "" } }
$inc Increments a field { $inc: { age: 1 } }
$mul Multiplies a field { $mul: { salary: 2 } }
P a g e 97 | 100
DATABASE MANAGEMENT SYSTEMS
7. Aggregation Operators
Used in aggregation pipeline for analytics.
Operator Meaning Example
{ $group: { _id: null, total: { $sum:
$sum Sums values
"$salary" } } }
{ $group: { _id: null, avgAge: { $avg:
$avg Average value
"$age" } } }
{ $group: { _id: null, maxSalary: {
$max Maximum value
$max: "$salary" } } }
{ $group: { _id: null, minSalary: {
$min Minimum value
$min: "$salary" } } }
Groups
$group Group by department, etc.
documents
Filters
$match Similar to find() conditions
documents
Selects specific
$project { $project: { name: 1, salary: 1 } }
fields
P a g e 98 | 100
DATABASE MANAGEMENT SYSTEMS
1. Hadoop Overview
Hadoop is an open-source framework for distributed storage and
processing of Big Data.
Core Components of Hadoop
1. HDFS (Hadoop Distributed File System)
o Stores very large files across clusters.
o Data is split into blocks and replicated for fault tolerance.
2. MapReduce
o A programming model for batch processing.
o Splits tasks into smaller parts, processes them in parallel, and
combines results.
3. YARN (Yet Another Resource Negotiator)
o Manages cluster resources.
P a g e 99 | 100
DATABASE MANAGEMENT SYSTEMS
2. Cassandra Overview
Apache Cassandra is a distributed NoSQL database built to handle huge
volumes of data across many servers with no single point of failure.
Key Features of Cassandra
• Decentralized (Peer-to-Peer) Architecture → No master-slave model.
• AP Model (Availability + Partition Tolerance) from CAP theorem.
• Wide-Column Store → Data is stored in tables with flexible columns.
• Linear Scalability → Adding new nodes increases performance.
• Fault-Tolerant → Data replicated across multiple nodes.
• High Write Performance → Optimized for fast inserts.
When to use Cassandra?
• Applications needing 24/7 uptime.
• Systems requiring high-speed writes (logs, sensor data, IoT).
• Social media apps, messaging apps, recommendation engines.
Use Cases:
• Netflix, Instagram, Uber use Cassandra for real-time data handling.
P a g e 100 | 100