Speeding Up Queries
An index is a data structure that improves the speed of data retrieval operations. Without an index, the database must scan every row in a table (a full table scan) to find matching records. With an index, it can jump directly to the right rows โ like using the index at the back of a book instead of reading every page.
Creating Indexes
-- Single column index
CREATE INDEX idx_student_name ON Students(Name);
-- Composite index
CREATE INDEX idx_student_dept_age ON Students(DeptID, Age);
-- Unique index (enforces uniqueness)
CREATE UNIQUE INDEX idx_student_email ON Students(Email);
-- Check existing indexes
SHOW INDEX FROM Students; -- MySQL
\di -- PostgreSQL
When to Use Indexes
How Indexes Work (B-Tree)
B-Tree Index Structure:
โโโโโโโโโโโ
โ 50 โ
โโโฌโโโโโโฌโโ
โโโโโโ โโโโโโ
โโโโโโดโโโโโ โโโโโโดโโโโโ
โ 25 โ โ 75 โ
โโโฌโโโโโโฌโโ โโโฌโโโโโโฌโโ
โโโโ โโโโ โโโโ โโโโ
โโโดโโ โโโโโดโ โโโดโโ โโโโโดโ
โ10 โ โ30 โ โ60 โ โ90 โ
โโโโโ โโโโโโ โโโโโ โโโโโโ
To find value 30:
Start at root (50) โ go left (< 50)
โ node (25) โ go right (> 25)
โ found (30)!
Only 3 steps instead of scanning all rows!