Advanced DataBase
Advanced DataBase
1. What is a Database?
A database is an organized collection of data that can be easily accessed, managed, and
updated.
👉 Simple words:
It’s like a digital storage system where data is stored in a structured way.
Example
University system → stores student records
Bank system → stores account details
WhatsApp → stores messages, contacts, media
b) Row (Tuple)
A single record in a table.
👉 Example:
101, Ali, 20
c) Column (Attribute)
A field representing a property of data.
👉 Example:
Name, Age, Student_ID
d) Primary Key
A unique identifier for each record.
👉 Example:
Student_ID (no duplicates allowed)
e) Foreign Key
A key used to link two tables.
👉 Example:
Student_ID in another table referencing main table
f) Schema
Structure/design of database.
👉 Example:
Defines tables, columns, relationships
b) Non-Relational (NoSQL)
Flexible structure
Used for large-scale apps
👉 Example: MongoDB
6. Advantages of Databases
Organized data storage
Easy access & retrieval
Data consistency
Security features
Supports multiple users
7. Disadvantages
Costly setup
Requires skilled management
Can be complex
System failure risk
b) Normalization
Process of organizing data to reduce redundancy.
👉 Example:
Separate student and course tables instead of repeating data
c) Transactions
A group of operations executed together.
👉 Example: Bank transfer:
Deduct from A
Add to B
e) Concurrency Control
Allows multiple users to access database safely.
g) Data Security
Includes:
Authentication
Authorization
Encryption
5. Cons
More complex
Requires expertise
Higher cost
Exam-Focused Summary
Database = organized data
DBMS = software to manage database
Table, Row, Column = basic structure
Primary key = unique identifier
CRUD = basic operations
Indexing = speed
Normalization = reduce redundancy
Transactions + ACID = reliability
Key Concepts
a) Object
An object contains:
Data (attributes)
Functions (methods)
👉 Example:
Object: Student
Attributes: name, age
Methods: getDetails()
b) Class
A blueprint for creating objects.
👉 Example:
Class: Student
c) Encapsulation
Data + methods combined together.
d) Inheritance
One class can inherit properties from another.
👉 Example:
Person → Student
Example (Real World)
Instead of storing only:
Name = Ali
Age = 20
You store a Student object with:
Data
Functions like calculateGrade()
Usage
Multimedia systems
CAD systems
AI applications
Advantages
Represents real-world entities better
Supports complex data types
Code reusability (inheritance)
Easier integration with programming languages
Disadvantages
Complex design
Not widely used commercially
Performance can be slower
Key Features
a) User-Defined Types
You can create custom data types.
👉 Example:
Address type = street, city, zip
c) Inheritance Support
Tables can inherit from other tables.
d) Methods Support
Functions can be attached to data.
Example
Instead of simple table:
Name Address
Usage
PostgreSQL (supports OR features)
Oracle Object-Relational features
Advantages
Combines best of both worlds
Handles complex data
Maintains relational structure
More flexible than pure relational
Disadvantages
More complex than relational
Requires deeper understanding
Can increase system overhead
5. Comparison: Relational vs OOP vs Object-Relational
Feature Relational Object-Oriented Object-Relational
Structure Tables Objects Tables + Objects
Data Type Simple Complex Complex
Methods No Yes Yes
Inheritance No Yes Yes
Flexibility Low High Medium-High
3. Code Reusability
Inheritance allows reuse
5. Improved Maintainability
Easier to update and manage complex systems
Example
Insert records:
Ali, 20
Ahmed, 22
Sara, 19
Stored exactly in insertion order (random).
Advantages
Very fast insertion
Simple to implement
No overhead of sorting
Disadvantages
Very slow searching (linear search)
Not suitable for large data
Deletion can be messy
Usage
Small systems
Temporary data storage
3. Sequential Files
Definition
Data is stored in a sorted order, usually based on a key.
How it Works
Records are arranged in sequence
Searching can use binary search
Example
Sorted by Student_ID:
101 → Ali
102 → Ahmed
103 → Sara
Advantages
Faster searching than heap
Good for range queries
Efficient for batch processing
Disadvantages
Insertion is slow (must maintain order)
Deletion requires shifting
Not flexible
Usage
Banking systems
Report generation
4. Hashing
Definition
Hashing uses a hash function to map data to a specific location.
How it Works
You apply a function:
Hash(Key) → Address
👉 Example:
ID = 105
Hash function → 105 % 10 = 5
Store at index 5
Advantages
Very fast searching (O(1))
Fast insertion and deletion
Direct access
Disadvantages
Collisions (two keys → same location)
Not good for range queries
Requires good hash function
Usage
Indexing
Password storage
Caching systems
Key Idea
Data is stored in sorted form
Tree remains balanced
All actual data is stored in leaf nodes
Important Properties
All leaves are at same level
Leaf nodes are linked (like a chain)
Supports fast traversal
Advantages
Fast searching (O(log n))
Efficient for large databases
Supports range queries
Keeps data sorted
Disadvantages
More complex to implement
Slight overhead for maintaining balance
Usage
Database indexing
File systems
Search engines
Quick Revision
File structure = physical storage
Heap = unordered
Sequential = sorted
Hashing = direct access
B+ Tree = balanced + best overall
Example
Without index:
You scan entire table → slow
With index:
You jump directly to the record → fast
Why Trees?
Because they:
Keep data sorted
Allow fast searching, insertion, deletion
Work well for large databases
Structure Recap
Root node → starting point
Internal nodes → guide search
Leaf nodes → store actual data (or pointers)
👉 Important:
Leaf nodes are linked together
All leaves are at the same level
b) Secondary Index
Definition
Index built on non-key attribute.
👉 Example:
Search by Name instead of ID
Features
Data not necessarily sorted
Can have duplicates
c) Clustered Index
Definition
Data is physically stored in the same order as the index.
👉 Only one clustered index per table
d) Non-Clustered Index
Definition
Index is separate from actual data.
👉 Contains pointers to data
Definition
An access path is the method used by DBMS to retrieve data from storage.
👉 Simple idea:
“How database decides to get your data”
c) Indexed Access
Uses index (like B+ tree)
Most common in modern DBMS
Example
Query:
SELECT * FROM Students WHERE ID = 50;
👉 DBMS may use:
Index → fast
Full scan → slow
9. Disadvantages
Extra storage required
Index maintenance overhead
Slightly slower insert/update
1. What is a Transaction?
Definition
A transaction is a sequence of operations performed as a single unit of work in a
database.
👉 Simple idea:
Either all operations happen, or none happen.
Real-Life Example (Very Important)
Bank Transfer
You transfer Rs. 1000 from Account A to B:
1. Deduct 1000 from A
2. Add 1000 to B
👉 If step 2 fails and step 1 already happened → problem ❌
👉 So both must succeed together ✔️
Key Point
A transaction ensures:
Data stays correct
No partial updates
ACID Properties
Example
If money deducted but not added → rollback
System restores original state
Keyword
👉 “All or Nothing”
2. Consistency
Definition
After transaction, database must remain in a valid state.
Example
Total balance before = after
No invalid data
Keyword
👉 “Data remains correct”
3. Isolation
Definition
Transactions run independently without affecting each other.
Example
Two users updating same account
One should not see incomplete changes of other
Keyword
👉 “No interference”
4. Durability
Definition
Once a transaction is committed, it is permanently saved.
Example
Even if system crashes → data محفوظ
Keyword
👉 “Permanent storage”
1. Active State
Transaction is executing
Operations are running
2. Partially Committed
Last operation executed
But not yet saved permanently
3. Committed
Transaction successfully completed
Changes are saved permanently
4. Failed
Error occurs
Transaction cannot continue
5. Aborted
Transaction is rolled back
Database restored to previous state
6. Terminated
Transaction ends completely
Resources are released
Simple Explanation
Start working → Active
Finished operations → Partially committed
Saved → Committed
Error → Failed
Undo → Aborted
6. Advantages of Transactions
Ensures data accuracy
Prevents data loss
Maintains integrity
Supports multi-user environment
7. Disadvantages
Performance overhead
Complex to manage
Requires recovery mechanisms
1. What is Concurrency?
Definition
Concurrency means multiple transactions executing at the same time in a database.
👉 Simple idea:
Many users accessing and modifying data simultaneously.
Example
Ali is transferring money
Ahmed is checking balance
👉 Both happening at the same time = concurrency
2. Concurrency Problems
Example
Initial balance = 1000
Transaction T1:
Reads balance → 1000
Adds 500 → 1500
Transaction T2:
Reads balance → 1000
Subtracts 200 → 800
👉 If T2 writes after T1:
Final value = 800 ❌
(But correct should be 1300)
Why it Happens
No proper synchronization
Both transactions read same old value
Solution (Idea)
Use locking
Use isolation levels
Example
Transaction T1:
Updates balance → 2000
Not committed yet
Transaction T2:
Reads balance → 2000
Why it Happens
Reading data before it is finalized
Solution
Do not allow reading uncommitted data
Use higher isolation levels
3. Deadlock
Definition
A deadlock occurs when two or more transactions are waiting for each other forever.
Example
Transaction T1:
Locks Account A
Wants Account B
Transaction T2:
Locks Account B
Wants Account A
👉 Result:
T1 waiting for T2
T2 waiting for T1
No one proceeds ❌
Simple Analogy
Two people:
One holds pen
One holds paper
Each waiting for the other
👉 Stuck forever
Why it Happens
Circular waiting
Improper locking
Solutions
Deadlock prevention
Deadlock detection
Timeout (cancel one transaction)
3. Summary Table
Problem Cause Result
👉 Deadlock vs Others
Deadlock → system stops
Others → wrong data but system runs
6. Disadvantages
Data inconsistency
Complex control
Risk of deadlocks
👉 Keywords to remember:
Lost Update → overwrite
Dirty Read → uncommitted
Deadlock → waiting forever
Quick Revision
Concurrency = multiple transactions
Lost update = overwrite problem
Dirty read = uncommitted data
Deadlock = stuck forever
Definition
Locking is a method where a transaction must lock a data item before accessing it.
👉 Like:
“Don’t touch this data, I’m using it.”
Types of Locks
Simple Rule
Operation Lock Type
Read Shared Lock
Write Exclusive Lock
Example
Transaction T1:
Locks record (exclusive)
Updates value
Transaction T2:
Must wait until T1 finishes
1. Growing Phase
Acquires locks
Cannot release any lock
2. Shrinking Phase
Releases locks
Cannot acquire new locks
👉 Ensures consistency
Advantages of Locking
Prevents lost updates
Ensures data consistency
Easy to understand
Disadvantages
Can cause deadlocks
Waiting time increases
Performance overhead
Definition
Each transaction is assigned a timestamp (unique time value), and execution is controlled
based on that order.
👉 Simple idea:
“Who came first gets priority.”
How it Works
Every transaction gets a timestamp:
T1 = 1
T2 = 2
👉 T1 is older, so it has higher priority
Rules
Older transaction executes first
If conflict occurs:
o Newer transaction is delayed or rejected
Example
T1 (older) wants to write
T2 (newer) already wrote
👉 Conflict → T2 is rolled back
Key Idea
Maintains serial order based on time
Advantages
No deadlocks ✔️
Simple ordering mechanism
Good for high concurrency
Disadvantages
Transactions may be restarted frequently
Can cause starvation (some never complete)
Complex to manage timestamps
👉 Keywords:
Locking → shared, exclusive
2PL → growing + shrinking
Timestamp → priority by time
Quick Revision
Concurrency control = manage multiple transactions
Locking = control using locks
Timestamp = control using time order
Locking → deadlock possible
Timestamp → no deadlock
1. What is MVCC?
Definition
Multiversion Concurrency Control (MVCC) is a method where the database keeps
multiple versions of data to allow transactions to work without interfering with each
other.
👉 Simple idea:
Instead of locking data, DBMS creates different copies (versions) of the same data.
👉 In locking:
T2 must wait ❌
👉 In MVCC:
T2 reads old version (1000) ✔️
Key Insight
Readers don’t block writers
Writers don’t block readers
1. Version Creation
Every time data is updated:
A new version is created
Old version is kept
2. Timestamp Assignment
Each transaction gets a timestamp.
3. Visibility Rule
A transaction can only see:
Data versions that were committed before it started
Simple Flow
Old Version → New Version → Newer Version
Transactions read the correct version based on time.
5. Important Concepts
a) Read Consistency
Each transaction sees a consistent snapshot
b) Snapshot
A “view” of database at a specific time
c) Version Control
Multiple versions stored temporarily
6. Advantages of MVCC
1. No Dirty Reads
Only committed data is visible
2. No Locking Delays
Reads don’t wait
3. High Concurrency
Many users can work simultaneously
4. Better Performance
Especially for read-heavy systems
7. Disadvantages
2. Complexity
Harder to implement
9. Real-World Usage
MVCC is used in:
MySQL (InnoDB)
PostgreSQL
Oracle
👉 That’s why modern systems feel fast even with many users.
👉 Keywords:
Multiple versions
Snapshot
No blocking
High concurrency
Quick Revision
MVCC = multiple copies of data
Readers don’t wait
Uses timestamps + versions
Prevents dirty reads
Improves performance
Simple Idea
Database should behave like:
“Nothing bad happened, everything is still correct”
Example
Bank transaction:
Money deducted
System crashes before adding to receiver
👉 Recovery ensures:
Either both steps happen
Or nothing happens
What is a Log?
A log file stores:
Transaction start
Read/write operations
Commit or abort
Example Log
T1: START
T1: WRITE A = 100
T1: COMMIT
Definition
In deferred update, changes are not written to database immediately. They are stored
and applied only after transaction commits.
How it works
1. Transaction starts
2. Changes stored in log only
3. No database update yet
4. After commit → changes applied
Example
T1:
Update balance = 500
System crashes before commit
👉 Result:
No change in database ✔️
No undo needed
Key Idea
👉 “Wait until commit before writing”
Advantages
No undo required
Safe from partial updates
Simple recovery
Disadvantages
Slower performance
Uses memory for temporary storage
B) Immediate Update
Definition
In immediate update, changes are written to the database as soon as they happen, even
before commit.
How it works
1. Transaction starts
2. Update database immediately
3. Log stores old value (for undo)
4. Commit confirms changes
Example
T1:
Writes balance = 500
System crashes before commit
👉 Recovery:
Undo using log ✔️
Restore old value
Key Idea
👉 “Write immediately, fix later if needed”
Advantages
Faster execution
Real-time updates
Disadvantages
Requires undo mechanism
More complex recovery
Risk of inconsistency during crash
1. Undo Operation
Reverses changes
Used in immediate update
2. Redo Operation
Reapplies changes
Used in both systems
Why important?
Because if crash happens:
Log is used to recover everything
8. Disadvantages
Extra storage (logs)
Performance overhead
Complex system design
👉 If question:
“Differentiate Deferred and Immediate”
Draw table (like above) + example
1. Shadow Paging
Definition
Shadow paging is a recovery technique where the database keeps a copy (shadow) of
the page table before making changes.
👉 Simple idea:
You never overwrite original data directly. You work on a “shadow copy”.
How it Works
Database maintains:
Current page table
Shadow page table (backup)
Steps:
1. Transaction starts
2. Copy page table → shadow table
3. Make changes in new pages
4. If commit → switch pointer to new table
5. If crash → discard changes, use shadow table
Example
Before update:
A = 100
Transaction updates A = 200:
Shadow still has A = 100
New page has A = 200
👉 If crash → system uses shadow (100)
Advantages
No undo/redo needed
Very simple recovery
Crash-safe
Disadvantages
Waste of storage
Copying page tables is expensive
Not good for large systems
Key Idea
👉 “Never overwrite, always copy first”
2. Checkpoints
Definition
A checkpoint is a point in time where the DBMS saves its current state to reduce
recovery time.
How it Works
At checkpoint:
All committed data is written to disk
Log is saved
Active transactions recorded
Simple Flow
Transaction log → → → CHECKPOINT → → → crash → recovery starts here
Types of Checkpoints
1. Simple Checkpoint
Stop all transactions temporarily
Save everything
2. Fuzzy Checkpoint
Does NOT stop transactions
Works in background (modern systems)
Advantages
Faster recovery
Reduces log scanning
Improves efficiency
Disadvantages
Overhead during checkpoint
Complex in fuzzy mode
Key Idea
👉 “Save progress so recovery is faster”
Core Idea
ARIES uses:
Logging
Undo/Redo
Checkpoints
👉 It is most advanced recovery method
1. Analysis Phase
Purpose:
Find:
What transactions were active
What needs redo/undo
👉 DBMS scans log from last checkpoint
2. Redo Phase
Purpose:
Reapply all changes from log
👉 Ensures database reflects all committed work
3. Undo Phase
Purpose:
Remove effects of incomplete transactions
👉 Fixes uncommitted work
Simple Flow
Analysis → Redo → Undo
2. Repeating History
Redo everything (even if already done)
3. Fine-Grained Undo
Undo only failed transactions
6. Advantages of ARIES
Very reliable
Used in real DBMS
Handles crashes efficiently
Supports high concurrency
7. Disadvantages
Very complex
Requires large logs
Hard to implement
8. Comparison Table
Feature Shadow Paging Checkpoints ARIES
👉 If question:
“Explain Checkpoints”
Definition
Purpose
Types
👉 If question:
“Explain ARIES”
Write:
3 phases
WAL
Redo + Undo concept
Topic 11: Integrity Constraints (Primary Key, Foreign Key, CHECK, Domain)
Definition
A Primary Key is a column (or set of columns) that uniquely identifies each record in a table.
Rules
Must be unique
Cannot be NULL
Only one primary key per table
Example
Student_ID Name Age
101 Ali 20
102 Ahmed 21
Key Idea
👉 “One record = one unique identity”
Advantages
Ensures uniqueness
Helps fast searching (indexing)
Prevents duplicate records
Disadvantages
Cannot allow NULL values
Must be carefully chosen
3. Foreign Key Constraint
Definition
A Foreign Key is a column that creates a relationship between two tables.
👉 It refers to the Primary Key of another table.
Example
Table 1: Students
Student_ID Name
101 Ali
Table 2: Courses
Course_ID Student_ID
C1 101
Key Idea
👉 “Foreign key connects tables”
Rules
Must match primary key in parent table
Can have duplicates
Can be NULL (sometimes allowed)
Advantages
Maintains relationships
Ensures referential integrity
Avoids orphan records
Disadvantages
Slows insert/update
Complex dependency management
4. CHECK Constraint
Definition
A CHECK constraint ensures that values in a column satisfy a specific condition.
Example
Age must be greater than 18:
Age > 18
Table Example
Name Age
Ali 20
Sara 17 ❌
👉 17 is not allowed
Key Idea
👉 “Value must satisfy condition”
Advantages
Prevents invalid data
Enforces business rules
Disadvantages
Cannot handle complex logic easily
May slow inserts slightly
5. Domain Constraint
Definition
A domain constraint defines the type of values a column can accept.
👉 It controls:
Data type
Range
Format
Example
Age column:
Only integers
Range: 0–120
Age: INTEGER (0–120)
Name column:
Only text
Cannot accept numbers
Key Idea
👉 “Defines valid value set for a column”
Advantages
Prevents wrong data types
Maintains consistency
Improves data quality
Disadvantages
Less flexible
Requires strict design
6. Summary Table
Constraint Purpose Example
Primary Key Unique identity Student_ID
Foreign Key Relationship Student_ID in another table
CHECK Condition rule Age > 18
Domain Data type rules Integer, String, Range
👉 CHECK vs Domain
CHECK = condition rule
Domain = data type + range definition
👉 Keywords to remember:
Primary key → uniqueness
Foreign key → relationship
CHECK → condition
Domain → data type rules
Definition
Referential integrity ensures that relationships between tables remain consistent and
valid.
👉 Simple idea:
If one table refers to another, that reference must always be valid.
Example
Table 1: Students
Student_ID Name
101 Ali
102 Ahmed
Table 2: Enrollments
Course Student_ID
CS101 101
CS102 999 ❌
👉 Problem:
Student_ID = 999 does not exist in Students table
Rules
Foreign key must match a primary key in parent table
Cannot insert invalid foreign key
Cannot delete parent record if child depends on it (unless cascade)
Actions on Delete/Update
1. CASCADE
If parent deleted → child also deleted
2. SET NULL
Child foreign key becomes NULL
3. RESTRICT / NO ACTION
Prevent deletion if dependency exists
Advantages
Maintains consistency between tables
Prevents orphan records
Keeps relationships valid
Disadvantages
Slower updates/deletes
Adds complexity
Key Idea
👉 “No broken links between tables”
4. Authentication
Definition
Authentication is the process of verifying the identity of a user.
👉 Simple idea:
“Who are you?”
Examples
Username + password
OTP verification
Fingerprint / Face ID
How it works
User tries to log in:
1. System asks credentials
2. System checks database
3. If correct → access granted
Advantages
Prevents unauthorized access
First layer of security
Disadvantages
Passwords can be stolen
Weak passwords reduce security
Key Idea
👉 “Identity check”
5. Authorization
Definition
Authorization determines what an authenticated user is allowed to do.
👉 Simple idea:
“You are allowed to do THIS, but not THAT”
Example
After login:
Admin → can delete data
Student → can only view data
Types of Permissions
Read
Write
Update
Delete
Advantages
Controls access levels
Protects sensitive data
Prevents misuse
Disadvantages
Complex role management
Misconfiguration risk
Key Idea
👉 “Access control after identity check”
7. Summary Table
Concept Meaning
Referential Integrity Valid relationships between tables
👉 If question:
“Authentication vs Authorization”
Always draw table + short explanation
9. Quick Revision
Referential integrity = valid table relationships
Authentication = identity check
Authorization = permission control
Security = protect database
2. Responsibilities of DBA
1. Database Design
Designing tables, relationships, schema
Choosing data structures
2. Security Management
Controlling who can access data
Setting authentication and authorization
4. Performance Tuning
Making queries faster
Optimizing indexing
Reducing system load
5. User Management
Creating user accounts
Assigning roles and permissions
7. Monitoring System
Checking database health
Fixing errors and issues
Key Idea
👉 “DBA ensures database runs smoothly, securely, and efficiently”
Disadvantages
Requires expert knowledge
High responsibility
Can be costly for organizations
2. What is a Role?
A role is a set of permissions grouped together.
Example
Role Permissions
3. How it works
1. Create role (Admin, User, etc.)
2. Assign permissions to role
3. Assign role to user
Advantages
Easier management
More secure
Scalable for large systems
Disadvantages
Role complexity increases in big systems
Misconfiguration risk
Key Idea
👉 “Manage users through roles, not individual permissions”
2. Limitations of RDBMS
2. Scalability Issues
Difficult to scale for very large distributed systems
Big data handling is weak
3. Performance Overhead
Joins between large tables are slow
Complex queries reduce performance
4. Rigid Schema
Fixed structure (columns must be defined beforehand)
Hard to modify structure frequently
6. Cost
Enterprise RDBMS systems are expensive
Key Idea
👉 “RDBMS is powerful but not flexible for modern large-scale, unstructured data”
👉 If question:
“Limitations of RDBMS”
Always write:
Structured only
Scalability issues
Performance overhead
Not good for multimedia
👉 If question:
“Role management”
Define role
Example (Admin/User)
Advantages
5. Quick Revision
DBA = database manager
Role = group of permissions
Role management = assign roles instead of users
RDBMS limitations = rigid, slow for big/unstructured data