Database Systems Course โ€“ Pak Notes Hub
๐Ÿ“˜ University Level Course

Database Systems
Complete Course

ER Diagrams ยท SQL ยท Normalization ยท Transactions ยท Indexing ยท Security โ€” All in Easy English

๐Ÿ“Š 12 Units ๐ŸŽ“ University Level ๐Ÿ’ป SQL Examples ๐Ÿ“ Practice Tasks ๐Ÿš€ Final Project
Unit 1

Introduction to Databases

Start from the very foundation.

What is a Database?

A database is an organized collection of related data stored so it can be easily accessed, managed, and updated. Think of it as a very powerful, structured digital filing cabinet used by software applications.

๐Ÿ’ก Example: When you log into your university portal, your name, roll number, and grades are all stored in a database.

DBMS vs File System

FeatureFile SystemDBMS
Data RedundancyHigh โ€” data repeated in multiple filesLow โ€” centralized storage
Data InconsistencyCommon problemControlled by integrity constraints
Data AccessManual search through filesPowerful query language (SQL)
SecurityLimited file-level permissionsFine-grained user access control
Concurrent AccessNo built-in supportMulti-user access with locking
RecoveryManual backup onlyAutomatic crash recovery

Types of Databases

  • Relational Database โ€” Data stored in tables (e.g., MySQL, PostgreSQL, Oracle)
  • NoSQL Database โ€” Flexible schema for unstructured data (e.g., MongoDB, Cassandra)
  • Hierarchical Database โ€” Tree-like structure (e.g., IBM IMS)
  • Network Database โ€” Graph-like structure with multiple parent-child links
  • Cloud Database โ€” Hosted on cloud platforms (e.g., AWS RDS, Google Firestore)

Database Users & Roles

RoleResponsibility
Database Administrator (DBA)Manages the DBMS, users, backups, and performance
Database DesignerDesigns the schema and ER diagrams
Application DeveloperWrites code that interacts with the database
End UserUses the application to view or enter data
โœ๏ธ Practice Task: List 3 real-world examples of databases used in daily life and identify which type each one is.
Unit 2

Data Models

Different ways to represent and organize data.

What is a Data Model?

A data model is a conceptual framework that defines how data is structured, stored, and manipulated. It acts as the blueprint of a database system.

Relational Model

The most widely used model. Data is organized into tables (relations) with rows (tuples) and columns (attributes). Tables are linked using keys.

Table: Student
+----------+-----------+-----+
| roll_no  | name      | age |
+----------+-----------+-----+
| 101      | Ahmad Ali | 20  |
| 102      | Sara Khan | 21  |
+----------+-----------+-----+

Entity-Relationship (ER) Model

A high-level conceptual model used during database design. It describes data in terms of entities, their attributes, and the relationships between them.

Comparison of Data Models

ModelStructureBest Used ForExample
HierarchicalTree (parent-child)Structured, predictable dataIBM IMS
NetworkGraph (multi-parent)Complex relationshipsIDS
RelationalTablesMost business applicationsMySQL, Oracle
Object-OrientedObjects & classesComplex/multimedia datadb4o
NoSQLFlexible (doc/key-val)Big data, web appsMongoDB, Redis
โœ๏ธ Practice Task: Draw the relational model for a simple Library system with Books and Members tables.
Unit 3

ER Diagrams

Visualize your database before building it.

What is an ER Diagram?

An Entity-Relationship (ER) Diagram is a visual diagram that shows the structure of a database. It is created before writing any SQL code and helps in planning.

๐Ÿ’ก Think of an ER Diagram like an architect’s blueprint โ€” you design the house on paper before building it.

ER Diagram Symbols

SymbolShapeMeaning
EntityRectangleA real-world object (e.g., Student, Course)
AttributeEllipse / OvalProperty of an entity (e.g., name, age)
Primary Key AttributeUnderlined EllipseUniquely identifies each record
RelationshipDiamondAssociation between two entities
Weak EntityDouble RectangleEntity that depends on another entity
Multi-valued AttributeDouble EllipseAttribute with multiple values (e.g., phone numbers)
Derived AttributeDashed EllipseValue calculated from another attribute (e.g., age from DOB)

Cardinality (Relationship Types)

TypeNotationExample
One-to-One (1:1)1 โ”€โ”€ 1One person has one passport
One-to-Many (1:N)1 โ”€โ”€< NOne teacher teaches many students
Many-to-Many (M:N)M >โ”€โ”€< NStudents enroll in many courses; courses have many students

Weak Entities

A weak entity cannot exist without depending on a strong entity. It does not have its own primary key โ€” it uses a partial key combined with the strong entity’s key.

Strong Entity: Employee (emp_id, name)
Weak Entity:   Dependent (dep_name, relation)
               โ€” Cannot exist without Employee
               โ€” Identified by: emp_id + dep_name
โœ๏ธ Practice Task: Draw an ER Diagram for a University system with Entities: Student, Course, Professor, Department.
Unit 4

Relational Model

The mathematical foundation of SQL databases.

Key Terminology

TermMeaningExample
RelationA tableStudent table
TupleA row in a tableOne student’s record
AttributeA column in a tablename, age, roll_no
DomainAllowed values for an attributeage: integers 1โ€“120
DegreeNumber of attributes in a relationStudent has 4 attributes โ†’ degree 4
CardinalityNumber of tuples in a relation50 students โ†’ cardinality 50

Types of Keys

Key TypeDefinitionExample
Super KeyAny set of attributes that uniquely identifies a tuple{roll_no}, {roll_no, name}
Candidate KeyMinimal super key (no redundant attributes){roll_no}, {email}
Primary KeyChosen candidate key for identification{roll_no}
Foreign KeyAttribute referencing primary key of another tabledept_id in Student refs Department
Composite KeyPrimary key made of two or more attributes{student_id + course_id}
Alternate KeyCandidate keys not chosen as primary key{email} if roll_no is PK

Relational Algebra โ€” Basic Operations

OperationSymbolPurpose
Selectฯƒ (sigma)Filter rows based on a condition
Projectฯ€ (pi)Select specific columns
UnionโˆชCombine tuples from two relations
IntersectionโˆฉCommon tuples in two relations
Differenceโˆ’Tuples in one relation but not the other
Cartesian Productร—Combine every tuple of two relations
Joinโ‹ˆCombine related tuples from two relations
โœ๏ธ Practice Task: Given a Student(roll_no, name, dept_id) table, write Relational Algebra to get names of all students in the CS department.
Unit 5

SQL โ€“ Basics

Start writing real database queries.

What is SQL?

SQL (Structured Query Language) is the standard language used to communicate with relational databases. It is used to create tables, insert data, and retrieve information.

DDL โ€” Data Definition Language

Used to define and modify the structure of the database.

-- Create a table
CREATE TABLE Student (
    roll_no   INT PRIMARY KEY,
    name      VARCHAR(50) NOT NULL,
    age       INT,
    dept_id   INT,
    email     VARCHAR(100) UNIQUE
);

-- Add a new column
ALTER TABLE Student ADD COLUMN cgpa FLOAT;

-- Delete the table permanently
DROP TABLE Student;

DML โ€” Data Manipulation Language

Used to insert, update, and delete data inside tables.

-- Insert a record
INSERT INTO Student (roll_no, name, age, dept_id)
VALUES (101, 'Ahmad Ali', 20, 1);

-- Update a record
UPDATE Student SET age = 21 WHERE roll_no = 101;

-- Delete a record
DELETE FROM Student WHERE roll_no = 101;

SELECT โ€” Retrieving Data

-- Get all students
SELECT * FROM Student;

-- Get only name and age
SELECT name, age FROM Student;

-- Filter with WHERE
SELECT name FROM Student WHERE age > 20;

-- Sort results
SELECT name, cgpa FROM Student ORDER BY cgpa DESC;

-- Limit results
SELECT name FROM Student LIMIT 10;
โœ๏ธ Practice Task: Create a Department table and a Student table. Insert 5 students. Retrieve students whose age is greater than 19.
Unit 6

SQL โ€“ Advanced Queries

Master JOINs, Subqueries, and Aggregates.

JOINs โ€” Combining Tables

A JOIN is used to combine rows from two or more tables based on a related column.

-- INNER JOIN: only matching rows from both tables
SELECT Student.name, Department.dept_name
FROM Student
INNER JOIN Department ON Student.dept_id = Department.dept_id;

-- LEFT JOIN: all rows from left + matching from right
SELECT Student.name, Department.dept_name
FROM Student
LEFT JOIN Department ON Student.dept_id = Department.dept_id;

Types of JOINs

JOIN TypeReturns
INNER JOINOnly rows where condition matches in BOTH tables
LEFT JOINAll rows from left table; NULL for non-matching right rows
RIGHT JOINAll rows from right table; NULL for non-matching left rows
FULL OUTER JOINAll rows from both tables; NULL where no match
SELF JOINA table joined with itself

Aggregate Functions

SELECT COUNT(*) FROM Student;              -- Total students
SELECT AVG(cgpa) FROM Student;             -- Average CGPA
SELECT MAX(cgpa) FROM Student;             -- Highest CGPA
SELECT MIN(cgpa) FROM Student;             -- Lowest CGPA
SELECT SUM(fee)  FROM Student;             -- Total fee

GROUP BY & HAVING

GROUP BY groups rows. HAVING filters groups (like WHERE but for groups).

-- Count students per department
SELECT dept_id, COUNT(*) AS total
FROM Student
GROUP BY dept_id;

-- Departments with more than 10 students
SELECT dept_id, COUNT(*) AS total
FROM Student
GROUP BY dept_id
HAVING COUNT(*) > 10;

Subqueries

-- Students with CGPA higher than average
SELECT name FROM Student
WHERE cgpa > (SELECT AVG(cgpa) FROM Student);
โœ๏ธ Practice Task: Write a query to find the department with the highest number of students using GROUP BY and ORDER BY.
Unit 7

Normalization

Organize your database to remove redundancy.

What is Normalization?

Normalization is the process of organizing a database to reduce data redundancy (repeated data) and improve data integrity. It involves dividing large tables into smaller ones.

๐Ÿ’ก Redundancy problem: If a student’s department name is stored in every row, changing the name requires updating hundreds of rows โ€” and errors can creep in.

Functional Dependency

If attribute A uniquely determines attribute B, we write: A โ†’ B

roll_no  โ†’ name         (roll_no determines name)
roll_no  โ†’ dept_id      (roll_no determines dept_id)
dept_id  โ†’ dept_name    (dept_id determines dept_name)

Normal Forms

Normal FormRuleProblem it Solves
1NFAll attributes must be atomic (single value). No repeating groups.Removes multi-valued cells
2NFMust be in 1NF. No partial dependency โ€” non-key attribute must depend on the FULL primary key.Removes partial dependencies
3NFMust be in 2NF. No transitive dependency โ€” non-key attribute must not depend on another non-key attribute.Removes transitive dependencies
BCNFStronger version of 3NF. For every dependency Aโ†’B, A must be a super key.Handles anomalies 3NF misses

Example: Normalizing a Table

-- BEFORE (Unnormalized): Redundancy problem
| roll_no | name  | dept_id | dept_name  |
| 101     | Ahmad | 1       | Computer   |
| 102     | Sara  | 1       | Computer   |   โ† dept_name repeated!

-- AFTER 3NF: Split into two tables
Student:    (roll_no, name, dept_id)
Department: (dept_id, dept_name)
โœ๏ธ Practice Task: Given table Order(order_id, customer_id, customer_name, product_id, product_name, qty). Normalize it to 3NF.
Unit 8

Transaction Management

Ensure data stays safe and consistent.

What is a Transaction?

A transaction is a sequence of database operations treated as a single unit. Either ALL operations succeed, or NONE of them are applied.

-- Bank Transfer Example
BEGIN TRANSACTION;
    UPDATE Account SET balance = balance - 5000 WHERE acc_id = 1;
    UPDATE Account SET balance = balance + 5000 WHERE acc_id = 2;
COMMIT;    -- Save both changes

-- If anything goes wrong:
ROLLBACK;  -- Undo all changes

ACID Properties

LetterPropertyMeaning
AAtomicityAll operations complete or none do โ€” no partial updates
CConsistencyDatabase moves from one valid state to another valid state
IIsolationConcurrent transactions don’t interfere with each other
DDurabilityOnce committed, changes are permanent even after system crash

Concurrency Problems

ProblemDescription
Dirty ReadTransaction reads data that another transaction modified but not yet committed
Non-Repeatable ReadSame data read twice gives different values because another transaction modified it
Phantom ReadA query returns different rows because another transaction inserted/deleted rows
Lost UpdateTwo transactions update the same data; one update is lost

Deadlock

T1 locks Row A, waits for Row B
T2 locks Row B, waits for Row A
--> Neither can proceed = DEADLOCK

Solutions:
- Deadlock Prevention (acquire all locks at start)
- Deadlock Detection (kill one transaction)
- Timeout (abort transaction if waiting too long)
โœ๏ธ Practice Task: Explain with an example how ACID properties protect a bank transfer transaction from failure.
Unit 9

Indexing & Hashing

Speed up database queries dramatically.

Why Indexing?

Without an index, the database scans every row to find data. An index is a special data structure that allows the database to find rows much faster โ€” like an index at the back of a book.

๐Ÿ’ก Without index: Search 1,000,000 rows one by one. With index: Jump directly to the result. Speed difference: minutes vs milliseconds!

Types of Indexes

Index TypeDescriptionBest For
Clustered IndexRows stored physically in index order. Only one per table.Primary key lookups, range queries
Non-Clustered IndexSeparate structure; pointer to actual row. Many per table.Frequently searched non-PK columns
Unique IndexEnsures all values in indexed column are uniqueEmail, username columns
Composite IndexIndex on two or more columnsMulti-column WHERE conditions
Full-Text IndexOptimized for searching inside textSearch engines, article content

SQL โ€” Creating Indexes

-- Create an index
CREATE INDEX idx_name ON Student(name);

-- Create unique index
CREATE UNIQUE INDEX idx_email ON Student(email);

-- Drop an index
DROP INDEX idx_name ON Student;

-- Check if a query uses an index
EXPLAIN SELECT * FROM Student WHERE name = 'Ahmad';

B+ Tree vs Hash Index

FeatureB+ Tree IndexHash Index
Best forRange queries (>, <, BETWEEN)Exact match (=) queries only
OrderMaintains sorted orderNo order maintained
SpeedO(log n)O(1) average
โœ๏ธ Practice Task: Create indexes on a Student table for name and email columns. Use EXPLAIN to verify the query uses the index.
Unit 10

Query Processing & Optimization

Understand how the database executes your queries.

Query Processing Steps

StepNameWhat Happens
1ParsingSQL query checked for syntax errors and converted to a parse tree
2TranslationParse tree converted to relational algebra expression
3OptimizationQuery optimizer finds the most efficient execution plan
4EvaluationThe chosen plan is executed and results are returned

Using EXPLAIN

-- See execution plan in MySQL
EXPLAIN SELECT s.name, d.dept_name
FROM Student s
JOIN Department d ON s.dept_id = d.dept_id
WHERE s.cgpa > 3.0;

-- Key output fields:
-- type: ALL=bad (full scan), ref=good, const=best
-- key:  which index is being used
-- rows: estimated rows examined

Optimization Tips

  • Use indexes on columns used in WHERE, JOIN, and ORDER BY clauses.
  • Avoid SELECT * โ€” only retrieve columns you actually need.
  • Use JOINs instead of subqueries where possible โ€” often faster.
  • Filter early โ€” apply WHERE conditions before JOINs to reduce data size.
  • Avoid functions on indexed columns โ€” WHERE YEAR(date) = 2024 disables the index.
  • Use LIMIT when you only need a few results.
โœ๏ธ Practice Task: Write two versions of a query (with and without index). Use EXPLAIN to compare and explain the difference.
Unit 11

Database Security & Authorization

Protect your data from unauthorized access.

Why Database Security?

Databases contain sensitive information โ€” student records, financial data, passwords. Without proper security, this data can be stolen, modified, or destroyed by attackers or unauthorized users.

SQL Injection Attack

One of the most dangerous attacks. An attacker injects malicious SQL code through user input fields to manipulate the database.

-- Vulnerable login query (bad practice):
SELECT * FROM users WHERE username = [user_input] AND password = [pass];

-- Attacker types as username:  ' OR 1=1 --
-- The query becomes: WHERE username = '' OR 1=1 --
-- Result: ALL users returned, login bypassed!

-- Safe fix: Use Prepared Statements
SELECT * FROM users WHERE username = ? AND password = ?;

User Privileges (GRANT & REVOKE)

-- Create a new user
CREATE USER 'ali'@'localhost' IDENTIFIED BY 'password123';

-- Give SELECT permission only
GRANT SELECT ON university_db.* TO 'ali'@'localhost';

-- Give full access
GRANT ALL PRIVILEGES ON university_db.* TO 'admin'@'localhost';

-- Remove a privilege
REVOKE INSERT ON university_db.* FROM 'ali'@'localhost';

FLUSH PRIVILEGES;

Views for Security

A view is a virtual table that shows only specific data. It hides sensitive columns from certain users.

-- Create a view that hides salary
CREATE VIEW public_employee AS
SELECT emp_id, name, department FROM Employee;

-- User only sees emp_id, name, department
-- salary column is completely hidden
โœ๏ธ Practice Task: Create a user with only SELECT privilege on the Student table. Test that they cannot INSERT or DELETE data.
Unit 12

Emerging Trends & Final Project

Modern databases and a complete real-world project.

NoSQL Databases

NoSQL TypeDescriptionExamples
Document StoreData stored as JSON-like documentsMongoDB, CouchDB
Key-Value StoreSimple key โ†’ value pairsRedis, DynamoDB
Column-FamilyData grouped by columns, not rowsCassandra, HBase
Graph DatabaseNodes and edges for relationship dataNeo4j, ArangoDB
๐Ÿ’ก SQL is great for structured data with complex queries. NoSQL is better for large-scale, flexible, or real-time data like social media feeds.

Distributed Databases

ConceptMeaning
ReplicationSame data copied to multiple servers for reliability
Sharding / PartitioningData split across servers based on a key (e.g., by region)
CAP TheoremA distributed system can only guarantee 2 of 3: Consistency, Availability, Partition Tolerance

๐ŸŽฏ Final Project โ€” University Database System

Design and implement a complete University Database using all concepts learned in this course.

โœ… Design ER Diagram (6+ entities)
โœ… Normalize all tables to 3NF
โœ… Create tables with keys & constraints
โœ… Write JOIN & GROUP BY queries
โœ… GPA calculation query
โœ… Create indexes on key columns
โœ… Create views for access control
โœ… Set up users with limited privileges

Starter Schema

CREATE TABLE Department (
    dept_id   INT PRIMARY KEY,
    dept_name VARCHAR(50)
);

CREATE TABLE Student (
    roll_no INT PRIMARY KEY,
    name    VARCHAR(50),
    cgpa    FLOAT,
    dept_id INT,
    FOREIGN KEY (dept_id) REFERENCES Department(dept_id)
);

CREATE TABLE Course (
    course_id INT PRIMARY KEY,
    title     VARCHAR(100),
    credits   INT,
    dept_id   INT
);

CREATE TABLE Enrollment (
    roll_no   INT,
    course_id INT,
    grade     CHAR(2),
    PRIMARY KEY (roll_no, course_id),
    FOREIGN KEY (roll_no)   REFERENCES Student(roll_no),
    FOREIGN KEY (course_id) REFERENCES Course(course_id)
);

๐ŸŽ‰ Congratulations!

You have completed the Database Systems Course by Pak Notes Hub!

You now know ER Diagrams, SQL, Normalization, Transactions, Indexing, and Security.

๐Ÿ“Š Course Summary

#UnitKey Skill
1Introduction to DatabasesDBMS concepts & roles
2Data ModelsER & Relational models
3ER DiagramsDatabase design & diagramming
4Relational ModelKeys & Relational Algebra
5SQL BasicsDDL, DML, SELECT
6SQL AdvancedJOINs, Aggregates, Subqueries
7Normalization1NF, 2NF, 3NF, BCNF
8TransactionsACID & Concurrency
9Indexing & HashingQuery performance
10Query OptimizationEXPLAIN & best practices
11SecurityPrivileges, Views, SQL Injection
12Emerging TrendsNoSQL, Distributed DB, Project

www.paknoteshub.online  ยท  More courses coming soon!