How an index works
Up to here the question has been what a query returns. From here it is what the query costs, and almost all of that is indexes.
A note on the examples. The fixture has seven employees. No planner will use
an index on seven rows — a sequential scan of one page beats any index lookup,
and Postgres knows it. So the statements below are runnable and the plans they
produce on this data will say Seq Scan regardless. That is not the examples
failing; it is the planner being right. The reasoning below is about what
happens at a million rows, and
reading a query plan is where you learn to
confirm it on real data.
The mental model
A B-tree index is a sorted structure with a pointer back to the row. That is nearly the whole model, and almost every property follows from it.
Because it is sorted:
- Equality is fast. Descend the tree, find the value.
- Ranges are fast. Find one end, walk sideways.
ORDER BYcan be free. The index is already in order, so the engine can read rows in order instead of sorting them.MIN/MAXcan be free. They are the first and last entries.
Because the pointer leads back to the row, an index lookup is two reads: one in the index, one in the table. That second read — the heap fetch — is why an index is not always a win.
Why the planner sometimes ignores your index
If a query is going to touch a large fraction of the table, the index makes it slower. Reading the table sequentially is one efficient pass; using the index means an index read plus a scattered row read, repeated, in whatever order the index happens to be in.
The crossover is lower than people expect — often single-digit percentages of
the table. So WHERE active = true on a table that is 90% active will
sequential-scan whatever you build, and that is correct. An index pays when it is
selective: when it eliminates most of the table.
This is why EXPLAIN saying Seq Scan is not automatically a bug, and why
“add an index” is not automatically a fix.
Composite indexes: order is the whole thing
CREATE INDEX idx_emp_dept_salary ON employee (department_id, salary);
Think of it as sorted by department_id, and within each department, by
salary. That makes it usable for:
WHERE department_id = 2— the leading columnWHERE department_id = 2 AND salary > 90000— leading column, then a rangeWHERE department_id = 2 ORDER BY salary— ordering for free within the group
And not usable for:
WHERE salary > 90000alone — the index is sorted by department first, so the salaries are scattered across it
This is the leftmost prefix rule: a composite index serves queries that
constrain a prefix of its columns, left to right. An index on (a, b, c) helps
a, a, b and a, b, c. It does not help b or c alone.
The practical consequence: put the equality column first and the range column
last. An index on (salary, department_id) for the query above would find
every row in the salary range and then filter by department, touching far more
of the index.
DROP INDEX idx_emp_dept_salary;
Covering indexes
If an index contains every column a query needs, the engine can answer from the index alone and skip the heap fetch entirely — an index-only scan.
CREATE INDEX idx_emp_covering ON employee (department_id) INCLUDE (name, salary);
INCLUDE adds columns that are stored but not part of the sort key, which is
the right tool when you need them in the output but never in a predicate. The
win is halving the reads on a hot query. The cost is a bigger index, which makes
every write to the table slightly more expensive.
DROP INDEX idx_emp_covering;
Sargability — the predicates that disable an index
A predicate is sargable when the engine can use an index for it. The usual way to destroy that is to wrap the column in something.
Not sargable — the index holds hired_on, not EXTRACT(YEAR FROM hired_on):
SELECT name FROM employee WHERE EXTRACT(YEAR FROM hired_on) = 2023 ORDER BY name;
Sargable — the same question as a range over the bare column:
SELECT name FROM employee
WHERE hired_on >= '2023-01-01' AND hired_on < '2024-01-01'
ORDER BY name;
The rule generalises: keep the column bare on one side of the comparison.
WHERE lower(email) = 'a@b.com'— not sargable against an index onemailWHERE salary * 12 > 1000000— not sargable; writesalary > 1000000 / 12WHERE name LIKE '%smith'— not sargable; a leading wildcard has no prefix to descend to.LIKE 'smith%'is sargableWHERE department_id::text = '2'— a cast on the column, so not sargable
Two escapes when you cannot change the predicate. Index the expression itself:
CREATE INDEX idx_emp_hired_year ON employee (EXTRACT(YEAR FROM hired_on));
DROP INDEX idx_emp_hired_year;
Or index a subset, when the query always carries the same filter:
CREATE INDEX idx_emp_recent ON employee (department_id) WHERE hired_on >= '2022-01-01';
DROP INDEX idx_emp_recent;
A partial index is smaller than the full one and cheaper to maintain, and it is underused.
What an index costs
Every index is a copy of some columns that has to be kept in step. So:
- Writes get slower. Each
INSERT,UPDATEof an indexed column, andDELETEupdates every relevant index. - It takes space, and space it occupies is cache it is not sharing.
- An unused index is pure cost.
pg_stat_user_indexesreports scan counts; an index with zero scans after a representative period is a write tax.
“Add an index” is a trade, not a free action. The question is always “which queries does this serve, and how often do they run compared to the writes”.
Try it
The sargable and non-sargable pair runs in the SQL playground, and both return the same row. They are the same question asked two ways, and only one of them could use an index on a real table.
Drill it with Recent hires by department.
Index choice is a storage-layer decision before it is a query one; the HLD fundamentals cover the system side, and SQL vs NoSQL covers when the access pattern argues for a different store entirely.
Interview questions
1. Why would the planner ignore an index you just created? Because the query is not selective enough. If it will touch a large fraction of the table, a sequential scan is cheaper than an index scan plus scattered heap fetches. The crossover is often a few percent of the table.
2. You have an index on (a, b). Which queries can use it?
Those constraining a leftmost prefix: a, or a and b. Not b alone, because
the index is sorted by a first, so b values are scattered through it.
3. Why is WHERE EXTRACT(YEAR FROM created_at) = 2024 slow, and how do you
fix it?
The index stores created_at, not the expression, so the predicate is not
sargable and the engine must evaluate it per row. Rewrite as a half-open range
on the bare column, or build an index on the expression.
4. What is a covering index?
One containing every column a query needs, so it can be answered from the index
alone without reading the table. In Postgres, INCLUDE adds payload columns
that are stored but not part of the sort key.
5. What does an index cost?
Write amplification on every insert, delete and update of an indexed column;
storage; and cache pressure. An index with no scans is pure overhead, which
pg_stat_user_indexes will tell you.
6. For WHERE tenant_id = ? AND created_at > ?, what column order would you
choose and why?
(tenant_id, created_at). The equality column goes first so the index descends
straight to the tenant’s contiguous block, then walks the date range within it.
Reversed, it would scan every tenant’s rows in the date range.
Next
Reading a query plan — how to check any of this instead of guessing.