π 1. What is an Index?
Think of a database index like the index in the back of a book:
π Without an index:
π To find every mention of “performance,” you’d have to read the entire book page by page.
π In database terms, this is a full table scan (slow!).
π With an index:
π You flip to the back, find “performance,” and see a list of page numbers.
π You jump straight there.
π In database terms, an index is a small, sorted data structure with pointers to rows — so you can quickly locate data.
✅ In short: An index is a data structure (often a B‑Tree) that speeds up lookups in a table or collection.
π 2. Why are Indexes Important?
✅ Mainly used for SELECT
queries — especially with:
-
WHERE
clauses -
JOIN
conditions -
ORDER BY
-
GROUP BY
They don’t usually help INSERT/UPDATE speed — they help you READ data faster.
π¦ Scenario: An E‑commerce Database
Customers Table:
customer_id | first_name | last_name | registration_date | country | is_active |
---|
Now run:
SELECT * FROM Customers WHERE country = 'USA';
π Without an index:
The database reads every row:
-
Row 1 → check country
-
Row 2 → check country
-
Row 3 → check country
… until all 10 million are checked.
π Very slow.
It’s like reading an entire phone book from A to Z looking for every “John Smith.” ππ©
π Rows vs Columns — Don’t get confused!
π A row = one record (e.g., product_id=1, name='Laptop', …)
π A column = one field across records (e.g., all “category” values).
⚡ Example Without Index
Table: Products
Query:
SELECT * FROM Products WHERE category = 'Apparel';
Process:
-
Check Row 1 (Electronics) → ❌
-
Check Row 2 (Apparel) → ✅ add to result
-
Check Row 3 (Electronics) → ❌
-
Check Row 4 (Apparel) → ✅ add to result
-
Check Row 5 (Electronics) → ❌
π Full table scan.
✨ Same Example WITH Index
Create an index:
CREATE INDEX idx_products_category ON Products (category);
✅ What happens now?
-
The database jumps to the index (sorted list of categories).
-
It quickly finds
Apparel
entries in the index:-
Apparel → product_id = 2
-
Apparel → product_id = 4
-
-
It directly fetches those rows from the table.
π Much faster! π
π‘ Key Takeaways
✅ An index is like a book’s index — faster lookups.
✅ Without an index → full table scan (slow).
✅ With an index → quick jumps to matching rows.
✅ Use them wisely for large tables and common query patterns.
Comments
Post a Comment