Skip to main content
CodingMarble

Programming fundamentals

Database Indexing Explained: When It Helps and When It Hurts

A database index is a separate, sorted structure that lets the engine jump to matching rows instead of reading the whole table, at the cost of extra storage and slower writes. It only helps when your queries can actually use it, so the habit to build is checking the query plan with EXPLAIN rather than adding indexes on a hunch.

By CodingMarble · Published · 5 min read

A laptop turned on showing code
Photo: Andras Vas on Unsplash

What an index is, in plain terms

Think of the index at the back of a textbook. To find every page that mentions caching you do not read the whole book; you look up the word in an alphabetical list and jump to the page numbers. A database index does the same job for a column. Without one, finding the orders of customer 42 means reading every row, which is called a full table scan. With an index on customer_id, the engine looks up 42 in a sorted structure and goes straight to the matching rows.

Most relational databases use a B-tree for ordinary indexes. Picture a tree where each level narrows the search range: the root says which branch holds values from A to M, the next level splits that further, and a few steps later you reach a leaf pointing to the row. Because the tree stays balanced, finding one value takes a handful of steps even when there are millions of rows. The sorted order also makes range queries and ORDER BY cheap, which a plain hash lookup cannot do.

The price you pay: writes and storage

An index is a second copy of part of your data, kept in sorted order. Every INSERT must add an entry to each index on the table. Every DELETE must remove one. Every UPDATE of an indexed column must move the entry. So an index trades faster reads for slower writes and more disk and memory. A table with a dozen indexes can make a write-heavy workload noticeably slower, and the unused ones give nothing back.

That is why the answer is never index everything. Index the columns your real queries filter, join and sort on, and no more. Primary keys and unique constraints are normally indexed automatically; check your database documentation for what else is created for you, such as foreign keys, because the behaviour differs between engines.

SQL· Creating and removing a single-column index
CREATE INDEX idx_orders_customer_id ON orders (customer_id);

-- Remove it if EXPLAIN and usage statistics show it is never used.
-- (MySQL needs: DROP INDEX idx_orders_customer_id ON orders;)
DROP INDEX idx_orders_customer_id;

Composite indexes and column order

A composite index covers several columns, such as (customer_id, created_at). It is sorted by the first column, then by the second within each first value, exactly like a phone book sorted by surname then first name. That order decides what it can serve. It works well for a filter on customer_id alone, and for customer_id plus a date range. It cannot efficiently serve a filter on created_at alone, just as a phone book is useless for finding everyone named Priya regardless of surname.

The usual guidance is to put columns tested with equality first and the column used for a range or sort last. Real planners vary, so treat it as a starting point and confirm with EXPLAIN. A composite index on (a, b) also makes a separate index on (a) redundant, since the first column of the composite already answers queries on a.

SQL· One composite index serving a filter, a range and a sort
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at);

SELECT id, item
FROM orders
WHERE customer_id = 42
  AND created_at >= '2026-01-01'
ORDER BY created_at;

Selectivity and covering queries

Selectivity describes how well a column narrows the rows. A column with many distinct values, such as an email address, is highly selective: one value matches almost nothing. A column with two values, such as is_active, is poorly selective, and an index on it may not help because half the table still matches and the planner may decide that scanning is cheaper. Low-selectivity columns are best as trailing columns in a composite index or combined with something selective.

A covering index contains every column a query needs, so the engine answers entirely from the index without visiting the table rows. If a query selects only customer_id and created_at and filters on those same columns, the composite index above covers it. Some databases let you add extra non-key columns to an index for this purpose, with syntax that differs by product, so check the documentation. Covering is a useful tool for hot queries, but wide indexes cost more to maintain, so use it deliberately.

Checking with EXPLAIN

EXPLAIN shows the plan the database intends to use for a query, without guessing. Put it in front of your SELECT and read whether it reports a scan of the whole table or a lookup using a named index. The exact words differ by engine, for instance a sequential scan in PostgreSQL versus a full table scan or type ALL in MySQL, and the output format changes between versions, so read your database's documentation for the vocabulary.

SQL· Ask the database how it will run the query
EXPLAIN
SELECT id, item
FROM orders
WHERE customer_id = 42;

-- Look for: the name idx_orders_customer_id in the plan
-- Worry about: a scan over the whole orders table

Some engines also offer EXPLAIN ANALYZE, which actually runs the query and reports real timings and row counts. Be careful using it on statements that modify data. Also remember that on a tiny table the planner may correctly choose a scan even when an index exists, because reading a few pages is cheap. Test with data volumes close to production.

Why an index sometimes is not used

The most common reason is wrapping the indexed column in a function. The index stores raw values, so a condition on LOWER(email) or on DATE(created_at) cannot use an ordinary index on those columns. Rewrite the condition so the column stands alone, for example a range on created_at, or create an index on the expression if your database supports it.

  • Leading wildcards: LIKE '%shirt' cannot use a normal B-tree because the start of the value is unknown, while LIKE 'shirt%' can. For searching inside text, look at your database's full-text features.
  • Type mismatches: comparing a numeric column to a string can force a conversion on every row.
  • Low selectivity: the planner may reasonably prefer a scan when most rows match.
  • Composite order: filtering only on the second column of a composite index skips the sorted part.
  • Stale statistics: the planner relies on table statistics, and outdated ones lead to poor plans, so check how your database refreshes them.

Common mistakes to avoid

The first mistake is adding indexes before measuring, which leaves a pile of unused ones that slow every write. The second is the opposite: never indexing foreign key columns used in joins, so every join scans. The third is creating overlapping indexes, such as one on (a) and another on (a, b), when one would do. Finally, adding an index to a very large live table can lock it or consume heavy resources on some engines, so read your database's guidance on online index creation before running it in production.

Practical tip: find your five slowest or most frequent queries from the database's slow-query log or monitoring, run EXPLAIN on each, and fix them one at a time. After adding an index, run EXPLAIN again and confirm it appears in the plan; if it does not, drop it rather than leave it costing you on every write.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.