Skip to content
We areTOP 1%

What is indexing in DBMS, and why does it make queries faster?

EasyConceptIndexing & Query Optimization
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

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 is O(log n) and usually touches only 3 or 4 pages, even for millions of rows.
  • Indexes also speed up joins, ORDER BY and range conditions such as BETWEEN.
  • The cost: every insert, update and delete must also update each index, and indexes use disk space.
  • Index columns that appear often in WHERE, JOIN and ORDER BY and 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

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account