Q&A-1Explain what an index is and why you would not index every column.
Answer
An index is a separate structure the database maintains so it can find rows without reading the whole table. The default and most important kind is a B-tree, which keeps entries sorted by its key columns, so the engine can descend to a value in logarithmic time and then walk forward in order.
That sorted property determines everything an index can do: equality lookups, range scans, prefix matching, and supplying rows already ordered so a sort is unnecessary. It equally determines what it cannot do: it cannot help a LIKE '%term' because there is no prefix to descend to, and it cannot help a predicate that transforms the column, because the transformed values are not what is sorted.
The reason not to index everything is that every index is maintained on every write. An insert writes to the table and to each index. An update touching an indexed column updates them. Each consumes storage, adds vacuum work, and slows bulk loads. Extra indexes also give the planner more options, and occasionally it picks a worse one.
So an index is a trade: faster reads for slower writes and more storage. The question is never 'would this help a query', almost any index helps some query, but 'does it help enough to justify taxing every write on this table'.
In practice I create the structural ones with the schema: primary keys and unique constraints, which are automatic, plus foreign key columns, which are not automatic and are the most commonly missing index. Then indexes for known critical queries. Then nothing further without measured evidence. And periodically I audit for unused and redundant indexes, which most mature systems accumulate and which are pure cost.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.