SQL Indexes (The Book Index) πΒΆ
Prerequisites: SELECT Statement, Table Management
Mentor's Note: Imagine a 1,000-page textbook. If you want to find "SQL Joins", would you read every page from 1 to 1,000? No! You go to the index at the back, find the page number, and flip straight to it. An Index does the exact same thing for your database! π‘
π The Scenario: The Search Challenge πΒΆ
- Full Table Scan: Looking at every single row in a table of 1 million users to find "Vishnu". (Slow! π’)
- Indexed Search: Using a pre-sorted list of names to jump directly to the row ID. (Instant! β‘)
π 1. The Two Main TypesΒΆ
A. Clustered Index (The Book Itself)ΒΆ
- Logic: The actual data rows are sorted and stored in this order.
- Analogy: A Phone Book sorted by Last Name.
- Rule: You can only have ONE per table (because data can only be physically sorted one way!).
- Default: In most systems, the Primary Key is automatically a Clustered Index.
B. Non-Clustered Index (The Index at the Back)ΒΆ
- Logic: A separate structure that points to the data rows.
- Analogy: The "Index" at the back of a textbook.
- Rule: You can have many per table.
π» 2. Basic SyntaxΒΆ
-- Create an index on 'email' to speed up logins
CREATE INDEX idx_user_email
ON users (email);
-- Unique Index (Prevents duplicates and speeds up search)
CREATE UNIQUE INDEX idx_roll_no
ON students (roll_no);
-- Remove an index
DROP INDEX idx_user_email;
π Comparison TableΒΆ
| Feature | Clustered Index | Non-Clustered Index |
|---|---|---|
| Physical Sorting | β Yes | β No |
| Storage | Uses the table itself | Requires extra disk space |
| Speed | Fastest for ranges | Fast for specific lookups |
| Quantity | Max 1 | Multiple (999+) |
β οΈ The "Tax" of IndexingΒΆ
While indexes make Reading (SELECT) faster, they make Writing (INSERT/UPDATE/DELETE) slower. - Why? Because every time you add a row, the database has to update all the indexes too!
π‘ Pro TipΒΆ
"Only index columns that you use frequently in
WHEREorJOINclauses. Don't index every column, or your 'Insert' speed will crawl to a halt!"