QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Database structure

What is an index and why is it needed?

An index is a separate ordered structure, most often a B-tree, that finds rows in a few steps instead of reading the whole table (Seq Scan). It speeds up reads but takes space and slows down writes. PostgreSQL indexes PRIMARY KEY and UNIQUE itself, while foreign keys must be indexed by hand. Whether an index works shows only in the query plan.

SQL · Constraints and indexes

The transactions filter is instant on dev and takes 4 seconds on a staging with millions of rows. What to check?

The feature works, tests are green, but on a staging close to production the history page opens in seconds. On dev there were a hundred rows and any way of searching looked fast. The first hypothesis in such a case: there is no index for this filter. The lesson explains what an index is, why it speeds up reads and slows down writes, and how to check that it really works.

How it works and why. Without an index, to find the rows of one account the database reads the whole table: Seq Scan, and the time grows with the number of rows. An index is a separate ordered structure, most often a B-tree: keys are stored sorted and a lookup descends the tree in a few steps instead of scanning everything. The analogy with a book's subject index is exact. The price is real too: an index takes space, and every INSERT, UPDATE of a key column and DELETE must update it as well. So you index not everything but what is searched, joined and sorted by.

PostgreSQL creates an index itself for PRIMARY KEY and UNIQUE, but not for foreign keys: the account_id column in transactions must be indexed by hand, otherwise JOINs and cascading deletes read the whole table. The planner decides itself whether to use an index: on a small table, or when the filter returns most rows, Seq Scan is cheaper, and that is fine.

Example: a composite index and column order. The query from the history tab: an account and a period.

CREATE INDEX idx_transactions_account_created
  ON transactions (account_id, created_at);

-- on a big live table, without blocking writes
CREATE INDEX CONCURRENTLY idx_transactions_status
  ON transactions (status);

The composite index (account_id, created_at) is sorted first by account and inside it by date. So it serves the filter "account = 10" and "account = 10 and date from…" well, and also sorting by date within an account. A filter on created_at alone it usually serves badly: rows of one date are scattered across all accounts. (Newer PostgreSQL versions can sometimes skip the first column, but do not rely on it.) Such a filter needs its own index on the date. Hence the rule: the first column is the one you always filter by, usually by equality.

The (account_id, created_at) index: what fits

Fits

account_id = 10

Also account_id = 10 AND created_at >= date, and ORDER BY created_at within an account.

Poor

created_at >= …

No first column: mostly Seq Scan or a slow pass over the whole index.

Figure 1. The column order of a composite index decides which filters it speeds up.

Another trap: an index that exists but is not used. A function over the column, such as lower(email), does not match an index on email. The same goes for LIKE '%abc' (a B-tree searches by the start of a string) and for comparing with another type that forces a cast of the column.

-- an index on email will not help this query
SELECT * FROM users WHERE lower(email) = 'ana@test.com';

-- an expression index will help
CREATE INDEX idx_users_email_lower ON users (lower(email));

The existing indexes are visible in the catalogue:

SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'transactions';

Limits and alternatives. A plain CREATE INDEX blocks writes to the table while it builds, so on a live table CREATE INDEX CONCURRENTLY is used (it is slower and cannot run inside a transaction). Extra indexes slow writes, so they are reviewed too: an unused index is a cost with no benefit. A B-tree is not the only kind: for full-text search and JSON there is GIN, for ranges and geography GiST. For frequent filters on a small subset of rows there are partial indexes (WHERE status = 'pending'). An index does not cure a bad query: SELECT * without a limit and fetching half the table stay slow.

Common mistakes.

  • Judging speed on a dev with a hundred rows: the plan depends on volume and statistics.
  • Indexing every column "just in case": writes slow down with no benefit.
  • Forgetting an index on a foreign key: JOINs and cascading deletes read the whole table.
  • Getting the column order of a composite index wrong.
  • Assuming an index "exists, so it works": that is visible only in the query plan.

Check yourself

There is an index (account_id, created_at). A query filters only WHERE created_at >= '2026-09-01'. Should you expect this index to work fast?

Answer

Usually not: the index is sorted by account_id first, so rows of one date are scattered across it. A separate index on created_at or another column order is needed if such a filter is common. EXPLAIN gives the real answer.

users.email has a plain index, but WHERE lower(email) = 'ana@test.com' does a Seq Scan. Why, and what to do?

Answer

The index is built on the value of email while the query compares lower(email): a different expression, so the index does not match. The fix: an expression index CREATE INDEX ON users (lower(email)) or a query that does not wrap the column in a function.

In an interview. Junior: An index is a separate structure, like a book's index: it lets you find rows without scanning the whole table. It speeds up search, JOIN and sorting, but takes space and slows down writes. Middle/Senior: The first hypothesis for a slow filter on large data: there is no index or it is not used. I remember that PostgreSQL does not index foreign keys itself, that the column order of a composite index matters and that a function over a column breaks the match. I confirm the hypothesis with the query plan, not a guess.

More articles in this chapter