Database
A database is an organised collection of data. A DBMS (Database Management System) is software to store, retrieve and manage it (MySQL, PostgreSQL, Oracle, SQL Server, MongoDB).
| DBMS | RDBMS |
|---|
| Data may be stored as files / documents | Data stored in tables (rows and columns) |
| Relationships not enforced | Relationships through keys (foreign keys) |
| May not support ACID fully | Supports ACID transactions and normalization |
| File system, XML DB | MySQL, PostgreSQL, Oracle |
- Table (relation), row (tuple / record), column (attribute / field).
- Degree = number of columns; cardinality = number of rows.
- Schema = structure of the database; instance = data at a moment.
Q & A
- Advantages of DBMS over a file system?
Less redundancy, consistency, concurrent access, security, backup and recovery, and easy querying with SQL.
2
Keys in DBMS
★★★★★
↑ Index
Database
| Key | Meaning |
|---|
| Super key | Any set of columns that uniquely identifies a row |
| Candidate key | Minimal super key (no extra column) |
| Primary key | The chosen candidate key: unique and NOT NULL, one per table |
| Alternate key | Candidate keys that were not chosen as primary |
| Foreign key | Column that refers to the primary key of another table |
| Composite key | Primary key made of two or more columns |
| Unique key | Unique values but NULL is allowed |
SQL
CREATE TABLE departments (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE students (
roll INT PRIMARY KEY,
email VARCHAR(100) UNIQUE,
name VARCHAR(100) NOT NULL,
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(id)
);
CREATE TABLE enrollments (
roll INT,
course_id INT,
grade CHAR(2),
PRIMARY KEY (roll, course_id) -- composite key
);
Database
An Entity-Relationship diagram models the database before building tables: entities (things), attributes (properties) and relationships.

A student can take many courses and a course has many students (M:N)
- Cardinality: one-to-one (1:1), one-to-many (1:N), many-to-many (M:N).
- Weak entity — cannot be identified by its own attributes (double rectangle), e.g. Dependent of an Employee.
- Derived attribute (dashed ellipse), e.g. Age from DOB; multi-valued (double ellipse), e.g. Phone numbers.
4
Normalization (1NF, 2NF, 3NF, BCNF)
★★★★★
↑ Index
Database
Normalization splits tables to remove redundancy and anomalies (insert, update, delete). It is based on functional dependency: A → B means A decides B.

Each normal form builds on the previous one
| Form | Rule | Example fix |
|---|
| 1NF | Every cell holds one atomic value; no repeating groups | Phone = "017.., 018.." → one row per phone |
| 2NF | 1NF and no non-key column depends on only part of a composite key | (Roll, CourseID) → CourseName depends only on CourseID → move to Course table |
| 3NF | 2NF and no non-key column depends on another non-key column | Roll → DeptID → DeptName → move DeptName to Department table |
| BCNF | For every A → B, A must be a super key | Stricter version of 3NF |
Q & A
- What is denormalization?
Adding some redundancy back on purpose (for example, storing a total) to make reads faster, at the cost of harder updates.
5
SQL Command Types
↑ Index
Database
| Type | Full name | Commands |
|---|
| DDL | Data Definition Language | CREATE, ALTER, DROP, TRUNCATE, RENAME |
| DML | Data Manipulation Language | INSERT, UPDATE, DELETE |
| DQL | Data Query Language | SELECT |
| DCL | Data Control Language | GRANT, REVOKE |
| TCL | Transaction Control Language | COMMIT, ROLLBACK, SAVEPOINT |
SQL
INSERT INTO students (roll, name, dept_id) VALUES (1, 'Rahim', 10);
UPDATE students SET name = 'Karim' WHERE roll = 1;
DELETE FROM students WHERE roll = 1;
ALTER TABLE students ADD COLUMN cgpa DECIMAL(3,2);
SELECT name, cgpa
FROM students
WHERE cgpa >= 3.5 AND name LIKE 'R%'
ORDER BY cgpa DESC
LIMIT 5;
DELETE vs TRUNCATE vs DROP
| DELETE | TRUNCATE | DROP |
|---|
| DML, removes chosen rows (WHERE) | DDL, removes all rows | DDL, removes the whole table |
| Can be rolled back | Usually cannot be rolled back | Cannot be rolled back |
| Slower, row by row | Fast, resets auto increment | Structure is gone too |
6
SQL Joins
★★★★★
↑ Index
Database
A JOIN combines rows from two tables using a related column.

Shaded area = rows returned
SQL
-- INNER JOIN: only students that have a department
SELECT s.name, d.name AS dept
FROM students s
INNER JOIN departments d ON s.dept_id = d.id;
-- LEFT JOIN: every student, dept is NULL when missing
SELECT s.name, d.name AS dept
FROM students s
LEFT JOIN departments d ON s.dept_id = d.id;
-- Students without a department
SELECT s.name
FROM students s
LEFT JOIN departments d ON s.dept_id = d.id
WHERE d.id IS NULL;
-- SELF JOIN: employee with their manager
SELECT e.name, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
CROSS JOIN returns every combination (rows A × rows B). MySQL has no FULL OUTER JOIN: use LEFT JOIN UNION RIGHT JOIN.
7
Aggregate Functions, GROUP BY and HAVING
★★★★★
↑ Index
Database
Aggregate functions: COUNT, SUM, AVG, MIN, MAX. GROUP BY makes one row per group. WHERE filters rows before grouping; HAVING filters groups after.
SQL
SELECT dept_id, COUNT(*) AS total, AVG(cgpa) AS avg_cgpa
FROM students
WHERE cgpa IS NOT NULL
GROUP BY dept_id
HAVING COUNT(*) > 10
ORDER BY avg_cgpa DESC;
Most asked SQL queries · SQL
-- 2nd highest salary
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- Nth highest (N = 3)
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
-- Duplicate emails
SELECT email, COUNT(*) FROM users
GROUP BY email HAVING COUNT(*) > 1;
-- Highest paid employee in each department
SELECT * FROM employees e
WHERE salary = (SELECT MAX(salary) FROM employees WHERE dept_id = e.dept_id);
Order of execution: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT.
8
Transactions and ACID
★★★★★
↑ Index
Database
A transaction is a group of operations that must succeed or fail together, e.g. a money transfer.
| Property | Meaning |
|---|
| Atomicity | All or nothing: if one step fails, everything is rolled back |
| Consistency | The database moves from one valid state to another (rules and constraints hold) |
| Isolation | Concurrent transactions do not see each other's half-done work |
| Durability | Once committed, data survives crashes (written to disk / log) |
SQL
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT; -- or ROLLBACK; if anything went wrong
Isolation levels
| Isolation level | Dirty read | Non-repeatable read | Phantom read |
|---|
| Read Uncommitted | Possible | Possible | Possible |
| Read Committed | No | Possible | Possible |
| Repeatable Read (MySQL default) | No | No | Possible |
| Serializable | No | No | No |
Database
An index is a separate data structure (usually a B+ tree) that lets the database find rows without scanning the whole table, like the index at the back of a book. It speeds up SELECT/WHERE/JOIN/ORDER BY but slows down INSERT/UPDATE/DELETE and uses extra space.
- Clustered index — the table rows are physically stored in index order; only one per table (the primary key in InnoDB).
- Non-clustered index — separate structure pointing to rows; many per table.
- Composite index on (a, b) helps queries on a, or a and b, but not on b alone (leftmost prefix rule).
SQL
CREATE INDEX idx_students_name ON students(name);
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);
EXPLAIN SELECT * FROM students WHERE name = 'Rahim'; -- check if the index is used
10
Views, Stored Procedures and Triggers
↑ Index
Database
SQL
-- View: a saved query that behaves like a table
CREATE VIEW top_students AS
SELECT name, cgpa FROM students WHERE cgpa >= 3.75;
-- Stored procedure: saved, reusable SQL with parameters
DELIMITER //
CREATE PROCEDURE get_dept_students(IN d INT)
BEGIN
SELECT * FROM students WHERE dept_id = d;
END //
DELIMITER ;
CALL get_dept_students(10);
-- Trigger: runs automatically on INSERT / UPDATE / DELETE
CREATE TRIGGER before_student_insert
BEFORE INSERT ON students
FOR EACH ROW SET NEW.name = UPPER(NEW.name);
Database
| SQL (relational) | NoSQL |
|---|
| Tables with a fixed schema | Flexible schema: document, key-value, column, graph |
| Scales vertically (bigger server) | Scales horizontally (more servers, sharding) |
| Strong ACID transactions | Often BASE / eventual consistency |
| Complex joins and queries | Fast simple reads/writes at huge scale |
| MySQL, PostgreSQL, Oracle | MongoDB, Redis, Cassandra, Neo4j |
CAP theorem: a distributed system can guarantee only two of Consistency, Availability and Partition tolerance at the same time.