How do indexes work? When does a database not use an index?
Most relational databases use B-tree (B+tree) indexes: a balanced tree of sorted keys whose leaves point to table rows (or, in MySQL InnoDB, the primary key). A lookup is O(log n) instead of a full table scan, and range queries and ORDER BY can read keys in order.
Kinds of index
- Primary / clustered: in InnoDB and Oracle IOTs the table itself is stored in primary-key order. PostgreSQL tables are heaps; all indexes are secondary.
- Composite (multi-column):
(customer_id, created_at). Follows the leftmost prefix rule: it helps filters oncustomer_id, or oncustomer_idandcreated_at, but not oncreated_atalone. - Covering: contains every column the query needs (PostgreSQL
INCLUDE, or extra key columns), allowing an index-only scan without touching the table. - Unique, partial / filtered (
WHERE status = 'OPEN'), expression / function-based (LOWER(email)). - Others: hash, GIN (arrays, JSONB, full text), GiST/BRIN in PostgreSQL; bitmap indexes in Oracle.
When the index is not used
- A function or calculation on the column:
WHERE YEAR(created_at) = 2026orWHERE amount * 2 > 100. Rewrite as a range, or index the expression. - Implicit type conversion (comparing a
VARCHARcolumn with a number). - A leading wildcard:
LIKE '%son'. - Low selectivity: if a condition matches a large fraction of the table, a sequential scan is cheaper and the optimiser chooses it.
- Wrong column order in a composite index, or
ORacross different columns. - Stale statistics; run
ANALYZE.
Costs
Every index slows down INSERT/UPDATE/DELETE and uses storage and memory. Index for your real query patterns and remove unused indexes.
Example
sql
CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at DESC);
-- Uses the index (leftmost prefix + range + order)
SELECT id, amount FROM orders
WHERE customer_id = 42 AND created_at >= DATE '2026-01-01'
ORDER BY created_at DESC
LIMIT 20;
-- Cannot use it efficiently: function on the column
SELECT * FROM orders WHERE EXTRACT(YEAR FROM created_at) = 2026;
-- Sargable rewrite
SELECT * FROM orders WHERE created_at >= DATE '2026-01-01' AND created_at < DATE '2027-01-01';
-- Check the plan
EXPLAIN ANALYZE SELECT id FROM orders WHERE customer_id = 42;Follow-up questions interviewers ask
Try answering each one before you open it.
How do you decide the column order in a composite index?
Put columns compared with equality first, then the column used for a range or sort. Among equality columns, order by the query patterns you need to serve (the leftmost column must be useful on its own). Selectivity matters less than matching the queries.