When a query is slow, the cause is often that the database has to read every row to find the few you want. An index is a separate, sorted structure that lets the database jump straight to matching rows, much like a book's index points to pages. Used well, indexes turn seconds into milliseconds. Used carelessly, they slow writes and waste storage.
How an index works
Most relational databases default to B-tree indexes. A B-tree keeps keys in sorted order in a balanced tree, so finding a value, a range or a sorted result requires reading only a few pages instead of the whole table. Because the index is sorted, it supports equality (=), ranges (<, >, BETWEEN), sorting and prefix searches.
Step 1: Measure before you index
Use the query plan. In PostgreSQL:
EXPLAIN ANALYZE
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;If the plan shows a sequential scan over a large table (a "Seq Scan"), and the query returns a small share of the rows, an index may help. Other databases offer equivalents: SQL Server has execution plans, and MySQL has EXPLAIN.
Step 2: Create an index that matches the query
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC);This composite index serves the query above: it finds the customer's rows and returns them already sorted, so the database can stop after 20.
Composite index column order matters
A composite index is sorted by its first column, then the second within it, and so on. A useful rule:
Put columns tested with equality first.
Then the column used for range filtering or sorting.
An index on (customer_id, created_at) helps queries that filter on customer_id, or on both columns. It generally does not help a query that filters only on created_at, because the data is not sorted by that column alone.
Covering indexes
If the index contains every column the query needs, the database can answer from the index without reading the table. SQL Server and PostgreSQL support INCLUDE columns for this:
CREATE INDEX idx_orders_customer_created_incl
ON orders (customer_id, created_at DESC)
INCLUDE (total);Why an index might be ignored
Functions on the column.
WHERE LOWER(email) = 'a@b.com'cannot use a plain index onemail. Create an expression index, or store normalized data.Leading wildcards.
LIKE '%term'cannot use a normal B-tree.LIKE 'term%'usually can.Low selectivity. If a filter matches a large share of the table, scanning may be cheaper than jumping around via an index.
Type mismatches between the column and the value can force conversions.
Stale statistics. The planner relies on table statistics; keep them up to date (for example with
ANALYZEin PostgreSQL).
The cost of indexes
Every index must be updated on insert, update and delete, and it consumes disk space and memory. Do not index every column. Index for the queries you actually run, and drop indexes that no query uses.
Unique and partial indexes
-- Enforce uniqueness
CREATE UNIQUE INDEX ux_users_email ON users (email);
-- PostgreSQL: index only the rows you query often
CREATE INDEX idx_orders_open ON orders (created_at)
WHERE status = 'open';Check that it worked
Run EXPLAIN ANALYZE again after creating the index. Look for an index scan or index-only scan and compare execution time. If the plan did not change, the index is not helping that query, so remove it.
Indexing with Laravel or EF Core
ORMs let you declare indexes in migrations. In Laravel: $table->index(['customer_id', 'created_at']);. In EF Core, use modelBuilder.Entity<Order>().HasIndex(o => new { o.CustomerId, o.CreatedAt });. Learn more about EF Core 10 in our guide to ASP.NET Core 10.