Database Systems
Complete Course
ER Diagrams ยท SQL ยท Normalization ยท Transactions ยท Indexing ยท Security โ All in Easy English
๐ Table of Contents โ 12 Units
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.
DBMS vs File System
| Feature | File System | DBMS |
|---|---|---|
| Data Redundancy | High โ data repeated in multiple files | Low โ centralized storage |
| Data Inconsistency | Common problem | Controlled by integrity constraints |
| Data Access | Manual search through files | Powerful query language (SQL) |
| Security | Limited file-level permissions | Fine-grained user access control |
| Concurrent Access | No built-in support | Multi-user access with locking |
| Recovery | Manual backup only | Automatic 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
| Role | Responsibility |
|---|---|
| Database Administrator (DBA) | Manages the DBMS, users, backups, and performance |
| Database Designer | Designs the schema and ER diagrams |
| Application Developer | Writes code that interacts with the database |
| End User | Uses the application to view or enter data |
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
| Model | Structure | Best Used For | Example |
|---|---|---|---|
| Hierarchical | Tree (parent-child) | Structured, predictable data | IBM IMS |
| Network | Graph (multi-parent) | Complex relationships | IDS |
| Relational | Tables | Most business applications | MySQL, Oracle |
| Object-Oriented | Objects & classes | Complex/multimedia data | db4o |
| NoSQL | Flexible (doc/key-val) | Big data, web apps | MongoDB, Redis |
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.
ER Diagram Symbols
| Symbol | Shape | Meaning |
|---|---|---|
| Entity | Rectangle | A real-world object (e.g., Student, Course) |
| Attribute | Ellipse / Oval | Property of an entity (e.g., name, age) |
| Primary Key Attribute | Underlined Ellipse | Uniquely identifies each record |
| Relationship | Diamond | Association between two entities |
| Weak Entity | Double Rectangle | Entity that depends on another entity |
| Multi-valued Attribute | Double Ellipse | Attribute with multiple values (e.g., phone numbers) |
| Derived Attribute | Dashed Ellipse | Value calculated from another attribute (e.g., age from DOB) |
Cardinality (Relationship Types)
| Type | Notation | Example |
|---|---|---|
| One-to-One (1:1) | 1 โโ 1 | One person has one passport |
| One-to-Many (1:N) | 1 โโ< N | One teacher teaches many students |
| Many-to-Many (M:N) | M >โโ< N | Students 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_nameRelational Model
The mathematical foundation of SQL databases.
Key Terminology
| Term | Meaning | Example |
|---|---|---|
| Relation | A table | Student table |
| Tuple | A row in a table | One student’s record |
| Attribute | A column in a table | name, age, roll_no |
| Domain | Allowed values for an attribute | age: integers 1โ120 |
| Degree | Number of attributes in a relation | Student has 4 attributes โ degree 4 |
| Cardinality | Number of tuples in a relation | 50 students โ cardinality 50 |
Types of Keys
| Key Type | Definition | Example |
|---|---|---|
| Super Key | Any set of attributes that uniquely identifies a tuple | {roll_no}, {roll_no, name} |
| Candidate Key | Minimal super key (no redundant attributes) | {roll_no}, {email} |
| Primary Key | Chosen candidate key for identification | {roll_no} |
| Foreign Key | Attribute referencing primary key of another table | dept_id in Student refs Department |
| Composite Key | Primary key made of two or more attributes | {student_id + course_id} |
| Alternate Key | Candidate keys not chosen as primary key | {email} if roll_no is PK |
Relational Algebra โ Basic Operations
| Operation | Symbol | Purpose |
|---|---|---|
| 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 |
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;
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 Type | Returns |
|---|---|
| INNER JOIN | Only rows where condition matches in BOTH tables |
| LEFT JOIN | All rows from left table; NULL for non-matching right rows |
| RIGHT JOIN | All rows from right table; NULL for non-matching left rows |
| FULL OUTER JOIN | All rows from both tables; NULL where no match |
| SELF JOIN | A 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);
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.
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 Form | Rule | Problem it Solves |
|---|---|---|
| 1NF | All attributes must be atomic (single value). No repeating groups. | Removes multi-valued cells |
| 2NF | Must be in 1NF. No partial dependency โ non-key attribute must depend on the FULL primary key. | Removes partial dependencies |
| 3NF | Must be in 2NF. No transitive dependency โ non-key attribute must not depend on another non-key attribute. | Removes transitive dependencies |
| BCNF | Stronger 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)
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
| Letter | Property | Meaning |
|---|---|---|
| A | Atomicity | All operations complete or none do โ no partial updates |
| C | Consistency | Database moves from one valid state to another valid state |
| I | Isolation | Concurrent transactions don’t interfere with each other |
| D | Durability | Once committed, changes are permanent even after system crash |
Concurrency Problems
| Problem | Description |
|---|---|
| Dirty Read | Transaction reads data that another transaction modified but not yet committed |
| Non-Repeatable Read | Same data read twice gives different values because another transaction modified it |
| Phantom Read | A query returns different rows because another transaction inserted/deleted rows |
| Lost Update | Two 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)
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.
Types of Indexes
| Index Type | Description | Best For |
|---|---|---|
| Clustered Index | Rows stored physically in index order. Only one per table. | Primary key lookups, range queries |
| Non-Clustered Index | Separate structure; pointer to actual row. Many per table. | Frequently searched non-PK columns |
| Unique Index | Ensures all values in indexed column are unique | Email, username columns |
| Composite Index | Index on two or more columns | Multi-column WHERE conditions |
| Full-Text Index | Optimized for searching inside text | Search 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
| Feature | B+ Tree Index | Hash Index |
|---|---|---|
| Best for | Range queries (>, <, BETWEEN) | Exact match (=) queries only |
| Order | Maintains sorted order | No order maintained |
| Speed | O(log n) | O(1) average |
Query Processing & Optimization
Understand how the database executes your queries.
Query Processing Steps
| Step | Name | What Happens |
|---|---|---|
| 1 | Parsing | SQL query checked for syntax errors and converted to a parse tree |
| 2 | Translation | Parse tree converted to relational algebra expression |
| 3 | Optimization | Query optimizer finds the most efficient execution plan |
| 4 | Evaluation | The 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.
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
Emerging Trends & Final Project
Modern databases and a complete real-world project.
NoSQL Databases
| NoSQL Type | Description | Examples |
|---|---|---|
| Document Store | Data stored as JSON-like documents | MongoDB, CouchDB |
| Key-Value Store | Simple key โ value pairs | Redis, DynamoDB |
| Column-Family | Data grouped by columns, not rows | Cassandra, HBase |
| Graph Database | Nodes and edges for relationship data | Neo4j, ArangoDB |
Distributed Databases
| Concept | Meaning |
|---|---|
| Replication | Same data copied to multiple servers for reliability |
| Sharding / Partitioning | Data split across servers based on a key (e.g., by region) |
| CAP Theorem | A 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.
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
| # | Unit | Key Skill |
|---|---|---|
| 1 | Introduction to Databases | DBMS concepts & roles |
| 2 | Data Models | ER & Relational models |
| 3 | ER Diagrams | Database design & diagramming |
| 4 | Relational Model | Keys & Relational Algebra |
| 5 | SQL Basics | DDL, DML, SELECT |
| 6 | SQL Advanced | JOINs, Aggregates, Subqueries |
| 7 | Normalization | 1NF, 2NF, 3NF, BCNF |
| 8 | Transactions | ACID & Concurrency |
| 9 | Indexing & Hashing | Query performance |
| 10 | Query Optimization | EXPLAIN & best practices |
| 11 | Security | Privileges, Views, SQL Injection |
| 12 | Emerging Trends | NoSQL, Distributed DB, Project |
www.paknoteshub.online ยท More courses coming soon!

