Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Database

11 topics · 28 Nov 2026
1

DBMS and RDBMS

↑ Index
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).

DBMSRDBMS
Data may be stored as files / documentsData stored in tables (rows and columns)
Relationships not enforcedRelationships through keys (foreign keys)
May not support ACID fullySupports ACID transactions and normalization
File system, XML DBMySQL, 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

  1. 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
KeyMeaning
Super keyAny set of columns that uniquely identifies a row
Candidate keyMinimal super key (no extra column)
Primary keyThe chosen candidate key: unique and NOT NULL, one per table
Alternate keyCandidate keys that were not chosen as primary
Foreign keyColumn that refers to the primary key of another table
Composite keyPrimary key made of two or more columns
Unique keyUnique 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
);
3

ER Diagram

↑ Index
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)

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

Each normal form builds on the previous one

FormRuleExample fix
1NFEvery cell holds one atomic value; no repeating groupsPhone = "017.., 018.." → one row per phone
2NF1NF and no non-key column depends on only part of a composite key(Roll, CourseID) → CourseName depends only on CourseID → move to Course table
3NF2NF and no non-key column depends on another non-key columnRoll → DeptID → DeptName → move DeptName to Department table
BCNFFor every A → B, A must be a super keyStricter version of 3NF

Q & A

  1. 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
TypeFull nameCommands
DDLData Definition LanguageCREATE, ALTER, DROP, TRUNCATE, RENAME
DMLData Manipulation LanguageINSERT, UPDATE, DELETE
DQLData Query LanguageSELECT
DCLData Control LanguageGRANT, REVOKE
TCLTransaction Control LanguageCOMMIT, 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

DELETETRUNCATEDROP
DML, removes chosen rows (WHERE)DDL, removes all rowsDDL, removes the whole table
Can be rolled backUsually cannot be rolled backCannot be rolled back
Slower, row by rowFast, resets auto incrementStructure is gone too
6

SQL Joins ★★★★★

↑ Index
Database

A JOIN combines rows from two tables using a related column.

Shaded area = rows returned

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.

PropertyMeaning
AtomicityAll or nothing: if one step fails, everything is rolled back
ConsistencyThe database moves from one valid state to another (rules and constraints hold)
IsolationConcurrent transactions do not see each other's half-done work
DurabilityOnce 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 levelDirty readNon-repeatable readPhantom read
Read UncommittedPossiblePossiblePossible
Read CommittedNoPossiblePossible
Repeatable Read (MySQL default)NoNoPossible
SerializableNoNoNo
9

Indexing

↑ Index
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);
11

SQL vs NoSQL

↑ Index
Database
SQL (relational)NoSQL
Tables with a fixed schemaFlexible schema: document, key-value, column, graph
Scales vertically (bigger server)Scales horizontally (more servers, sharding)
Strong ACID transactionsOften BASE / eventual consistency
Complex joins and queriesFast simple reads/writes at huge scale
MySQL, PostgreSQL, OracleMongoDB, Redis, Cassandra, Neo4j

CAP theorem: a distributed system can guarantee only two of Consistency, Availability and Partition tolerance at the same time.