1. What is a database index, and what are the costs of adding one?
A strong answer covers:
- An index is a separate data structure, usually a B-tree, that speeds up lookups
- It helps WHERE, JOIN and ORDER BY on the indexed columns
- It uses extra disk and memory
- Every INSERT, UPDATE and DELETE must also update the index, so writes get slower
- Unused or duplicate indexes should be removed
Show model answer
An index is an extra data structure that lets the database find rows without scanning the whole table, a bit like the index at the back of a book. The most common type is a B-tree, which keeps values sorted, so it helps equality lookups, ranges, joins and ORDER BY on those columns. The cost is that indexes take disk space and memory, and every INSERT, UPDATE or DELETE must update each index on the table, which slows writes. Too many indexes also make the planner's job harder. So I add indexes based on real slow queries, check that they are used with EXPLAIN, and regularly look for unused or duplicate indexes, for example with pg_stat_user_indexes in PostgreSQL, and drop them.