Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to Database
Understanding Database Indexes

Understanding Database Indexes

DatabaseBy Muhammad Fareed
databaseunderstandingindexes

Short answer: a database index is a separate data structure that lets the database find rows quickly without scanning the entire table, like the index at the back of a book. Indexes make reads much faster but use extra storage and slow down writes a little, so you add them where queries need them.

The problem indexes solve

Without an index, a query like SELECT * FROM users WHERE email = 'a@x.com' must check every row (a full table scan). On a table with millions of rows that is slow. An index on email lets the database jump straight to the matching row.

A B-tree index lookup narrows the search at every levelQuery: WHERE id = 42. Root node: Points to a branch. Branch node: Narrows the key range. Leaf node: Holds key and row pointer. Table row: Fetched directlyQueryWHERE id = 42Root nodePoints to a branchBranch nodeNarrows the key rangeLeaf nodeHolds key and row pointerTable rowFetched directly
Diagram: A B-tree index lookup narrows the search at every level.

How a B-tree index works

Most relational databases (MySQL, PostgreSQL, SQL Server) use a balanced tree called a B-tree. Values are stored in sorted order, so the database can search by repeatedly narrowing the range, which takes a handful of steps even for huge tables (logarithmic time). Sorted order also helps range searches (BETWEEN, >, <) and ORDER BY.

Creating an index

CREATE INDEX idx_users_email ON users (email);

-- Unique index: also enforces uniqueness
CREATE UNIQUE INDEX idx_users_email_unique ON users (email);

-- Remove an index
DROP INDEX idx_users_email ON users;      -- MySQL
-- DROP INDEX idx_users_email;            -- PostgreSQL

Primary keys are indexed automatically, and unique constraints create unique indexes.

Composite (multi-column) indexes

CREATE INDEX idx_orders_customer_date ON orders (customer_id, created_at);

Column order matters. This index helps queries that filter on customer_id, or on customer_id and created_at, but not queries that filter on created_at alone. This is the leftmost prefix rule. Put the column used for equality first, and range columns later.

Check that an index is used

EXPLAIN SELECT * FROM users WHERE email = 'a@x.com';

Look for an index lookup instead of a full scan (in MySQL the type column shows ref or const rather than ALL; in PostgreSQL look for "Index Scan"). If the plan still scans the table, the index may not match the query.

When to add an index

  • Columns used in WHERE filters on large tables
  • Foreign key columns used in JOIN conditions; see MySQL joins
  • Columns used in ORDER BY or GROUP BY on big result sets
  • Columns that must be unique

The costs

  • Slower writes: every insert, update and delete must also update the indexes.
  • More storage: each index takes disk space and memory.
  • Maintenance: too many indexes confuse the planner and need upkeep.

When an index will not help

Query patternWhy the index may be ignored
WHERE LOWER(email) = ...A function on the column prevents index use (use a functional index where supported)
WHERE name LIKE '%son'A leading wildcard cannot use the sort order
Low-selectivity columns (e.g. a boolean)The database may find a scan cheaper
Small tablesA scan is already fast
Type mismatch (WHERE id = '5' on a number)Implicit conversion can skip the index

Other index types

  • Hash: equality lookups only.
  • Full-text: searching words in text.
  • GIN / GiST (PostgreSQL): arrays, JSON, geospatial data.
  • Covering index: includes every column a query needs so the table itself is not read.

MongoDB has the same idea; see MongoDB indexing best practices and MySQL indexes. For schema design, read database normalization.

FAQs

How many indexes should a table have?

As few as needed. Start from your slowest, most frequent queries and add indexes that serve them.

Do indexes need rebuilding?

The database maintains them automatically. Occasional maintenance may help on very write-heavy tables.

Does an index guarantee faster queries?

No. The planner decides whether to use it. Always confirm with EXPLAIN.

What is the difference between a clustered and non-clustered index?

A clustered index defines the physical order of the table rows (one per table). A non-clustered index is a separate structure pointing to the rows.