Loading W Code...
Architectural Deep Dive into Transactions, Normalization, Indexing & Storage
DBMS Theory: Comprehensive guide covering Database Internals, ACID Integrity, B+ Tree Indexing, Normalization, and Relational Algebra.
A Database Management System (DBMS) is specialized software designed to define, store, manage, and query structured data securely. It serves as an abstraction layer between application software and raw storage disks.
-- Relational DDL Architecture Example
CREATE DATABASE EnterpriseCore;
USE EnterpriseCore;
CREATE TABLE Users (
user_id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(64) NOT NULL UNIQUE,
email VARCHAR(128) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;Storing production data in raw text or CSV files leads to critical architectural flaws as data scales:
-- Eliminating Anomalies via Foreign Keys
CREATE TABLE Departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(100) NOT NULL
);
CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
dept_id INT,
CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES Departments(dept_id)
ON DELETE SET NULL
ON UPDATE CASCADE
);Every relational transaction must strictly satisfy the four ACID properties:
Transactions complete entirely or abort cleanly. If a single statement fails, every modification is reversed via undo logs.
Data moves from one valid state to another, strictly adhering to schema constraints and domain rules.
Concurrent execution of transactions produces the same state as executing them serially.
Once committed, modifications survive power outages or system crashes by flushing Write-Ahead Logs (WAL) to disk before updating table files.
-- Atomic Fund Transfer Transaction
START TRANSACTION;
-- Step 1: Deduct from Source Account
UPDATE Accounts SET balance = balance - 500.00 WHERE account_id = 101 AND balance >= 500.00;
-- Step 2: Add to Destination Account
UPDATE Accounts SET balance = balance + 500.00 WHERE account_id = 202;
-- Verify & Commit
COMMIT; -- Changes permanently flushed via WALKeys uniquely identify rows within a table and establish relationships across entities.
CREATE TABLE StudentCourses (
student_id INT NOT NULL,
course_id INT NOT NULL,
enrollment_date DATE,
-- Composite Primary Key
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES Students(student_id),
FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);Normalization structures relational schemas into standard normal forms to remove data duplication:
-- 3NF Normalized Schema Design
CREATE TABLE Instructors (
instructor_id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50)
);
CREATE TABLE Courses (
course_id INT PRIMARY KEY,
course_title VARCHAR(100),
instructor_id INT,
FOREIGN KEY (instructor_id) REFERENCES Instructors(instructor_id)
);ER Modeling maps real-world domains into visual structural representations before creating physical tables.
User, Order).OrderItem).-- Mapping Many-to-Many (M:N) Relationship to Junction Table
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE Products (
product_id INT PRIMARY KEY,
title VARCHAR(100),
price DECIMAL(10,2)
);
-- Junction Table for M:N Relationship
CREATE TABLE OrderLineItems (
order_id INT,
product_id INT,
quantity INT DEFAULT 1,
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES Orders(order_id),
FOREIGN KEY (product_id) REFERENCES Products(product_id)
);When thousands of transactions execute simultaneously, database isolation prevents concurrency anomalies:
READ UNCOMMITTED (Fastest, permits all anomalies).READ COMMITTED (Prevents Dirty Reads, default in PostgreSQL/Oracle).REPEATABLE READ (Prevents Dirty & Non-Repeatable Reads, default in InnoDB).SERIALIZABLE (Strict lock-based execution, prevents all anomalies).-- Setting Session Isolation Level in MySQL/PostgreSQL
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
START TRANSACTION;
SELECT SUM(balance) FROM Accounts WHERE region = 'APAC';
-- Guarantee: Re-executing this query inside the transaction yields identical results
COMMIT;An Index is an auxiliary data structure (typically a B+ Tree) that reduces lookups from an $O(N)$ full table scan down to $O(\log N)$ disk reads.
-- Composite Index Creation
CREATE INDEX idx_user_status_date ON Users(status, created_at);
-- Query utilizing the composite index (Leftmost prefix match)
EXPLAIN SELECT * FROM Users WHERE status = 'ACTIVE' AND created_at >= '2026-01-01';A View is a saved SQL query representing a virtual table. Views simplify complex joins and restrict access to sensitive fields.
-- Creating Security View for HR Data
CREATE VIEW PublicEmployeeDirectory AS
SELECT emp_id, first_name, last_name, department, work_email
FROM Employees
WHERE employment_status = 'ACTIVE';
-- Grant access ONLY to the view, hiding salary & SSN fields
GRANT SELECT ON PublicEmployeeDirectory TO auditor_role;INSERT, UPDATE, or DELETE operations.-- Audit Logging Trigger Example
DELIMITER //
CREATE TRIGGER audit_salary_update
AFTER UPDATE ON Employees
FOR EACH ROW
BEGIN
IF OLD.salary <> NEW.salary THEN
INSERT INTO AuditLogs (emp_id, old_salary, new_salary, modified_by)
VALUES (NEW.emp_id, OLD.salary, NEW.salary, CURRENT_USER());
END IF;
END //
DELIMITER ;Relational Algebra is the procedural mathematical query language underlying SQL optimization engine:
WHERE).SELECT col1, col2).CROSS JOIN).INNER JOIN).-- Relational Algebra Formula: π(name, salary)(σ(dept = 'CS')(Employees))
-- Equivalent SQL Statement:
SELECT name, salary
FROM Employees
WHERE dept = 'CS';ACID Guarantees: Atomicity (Undo Logs), Consistency (Constraints), Isolation (Locks/MVCC), Durability (Write-Ahead Logs).
B+ Tree Advantage: Leaf nodes are linked sequentially, providing fast range scans and logarithmic $O(\\log N)$ equality lookups.
3NF vs BCNF: 3NF allows $X \\to Y$ if $Y$ is a prime attribute; BCNF strictly requires $X$ to be a Super Key.