The Power of Indexing in Database Tables
When working with databases, most developers understand the concept of an index and why it's used: to speed up data retrieval. But the real impact of indexing often becomes clear only when you compare scenarios with and without it.
Do you Know what Happens Without an Index?
Imagine a table with three columns: Name, Age, and MobileNumber.
.png)
Now, consider this query:
.png)
If the Age column does not have an index, the database engine will:
- Check if the WHERE condition field has an index.
- If not, it will scan the entire table (a full table scan).
- For each row, it will check the Age value and return matches.
This means the engine traverses the entire data structure, which is time-consuming for large tables.
What Happens With an Index?
Now, if the Age column is indexed, the process changes dramatically:
- The engine goes directly to the index structure.
- It finds the node for Age = 26.
- The index points to the corresponding record IDs in the main table.
- The result is fetched almost instantly.
This is why indexing is such a powerful optimization tool.
A Real-Life Lesson
Recently, we encountered an interesting situation that highlighted the importance of indexes.
Our table had 5 records, and the Age column was indexed. Then, by mistake, we deleted two entries from the index structure (not from the main table). These entries corresponded to IDs X001 and X005, both having Age = 26.
.png)
When we ran:
SELECT ID, Age, EmpId, Mobile, NameFROM Company.Employee WHERE Age = 26
We expected 3 records (since the main table still had them), but only 2 records appeared.
.png)
Why? Because the query relied on the index, and the index was incomplete.
Key Takeaway
Indexes are powerful, but they must be maintained properly. If an index is accidentally deleted or corrupted, don’t worry, you can rebuild the index using the below command:
Do ##Class(Company.Employee).%BuildIndices()
.png)
Moral of the story: Indexes make queries fast, but they also become a single point of truth for retrieval. Handle them carefully!😅