Concept · Designing databases

INDEX

An index gives the engine a route to find rows with less work. It can help filters, joins and sorts, but it takes up space and has a maintenance cost.

INDEX example

Suppose a screen keeps querying a customer's orders and shows them in chronological order:

Frequent query
SELECT id, date, total
FROM orders
WHERE customer_id = 1
ORDER BY date, id;

A composite index can start with the equality column and continue with the sorting columns:

SQL
CREATE INDEX idx_orders_customer_date
ON orders (customer_id, date, id);

PRAGMA index_list('orders');

The column order reflects the pattern you want to help: first filter by customer_id and then walk through the rows by date e id. Having the index does not force the optimiser to use it; the teaching table is small and a full scan can still be reasonable.

What changes from case to case

When it usually helps

  • Columns often used in WHERE.
  • Keys used to join tables.
  • Sorts or range searches that the index can support.
  • Constraints such as UNIQUE, which usually rely on an index structure.

Not every index is useful. A small table can be scanned in full at a lower cost; a column with few distinct values may offer little selectivity.

The cost you also need to weigh up

Each INSERT, UPDATE or DELETE may need to update the index. It also takes up space and needs maintenance. Creating indexes “just in case” can slow down writes and make the system more complicated.

Common mix-ups with INDEX

Assuming an index always speeds things up

Check the plan with EXPLAIN and measure a representative workload. An index that goes unused, duplicates another or starts with unhelpful columns adds cost with no clear benefit.