What is indexing in DBMS, and why does it make queries faster?
EasyConceptIndexing & Query Optimization
Answer
An index is a separate, sorted data structure that maps column values to the locations of the matching rows, so the database can find them without reading every row. Most relational databases use a B+ tree index by default.
- Without an index, a lookup scans the whole table, which is
O(n). A B+ tree lookup isO(log n)and usually touches only 3 or 4 pages, even for millions of rows. - Indexes also speed up joins,
ORDER BYand range conditions such asBETWEEN. - The cost: every insert, update and delete must also update each index, and indexes use disk space.
- Index columns that appear often in
WHERE,JOINandORDER BYand that are selective, meaning they have many distinct values.
Example:
-- 1 million rows and no index: full table scan
SELECT * FROM students WHERE roll = 50231;
CREATE INDEX idx_roll ON students(roll);
-- now the database walks the B+ tree: root -> branch -> leaf -> row
An index on an is_active column with only two values would rarely help, because each value matches a large part of the table.
More in Indexing & Query Optimization
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is indexing in DBMS, and why does it make queries faster? | Concept | Easy | Read the answer to What is indexing in DBMS, and why does it make queries faster? | |||
| 2 | What is the difference between a B tree and a B+ tree? | Concept | Medium | Read the answer to What is the difference between a B tree and a B+ tree? | |||
| 3 | What is the difference between a clustered and a non-clustered index? | Concept | Medium | Read the answer to What is the difference between a clustered and a non-clustered index? | |||
| 4 | What is the difference between a dense index and a sparse index? | Concept | Medium | Read the answer to What is the difference between a dense index and a sparse index? | |||
| 5 | How would you find and fix a slow SQL query? | Concept | Hard | Read the answer to How would you find and fix a slow SQL query? |