How it works
A primary index finds a row by its key. To find rows by something else, such as all orders for one customer, the engine must scan the table unless you add a secondary index: a separate sorted structure from that column’s value to the matching rows. In Postgres an entry points at the row’s physical location; in InnoDB it holds the primary key, so a lookup then walks a second tree. Column order matters in a composite index. An index on (customer_id, created_at) serves one customer’s orders by date, but not all customers’ orders on one date.
A covering index goes further and holds every column a query needs, so the engine can answer from the index without fetching rows. If a page shows a customer’s 20 newest orders with their totals, an index on (customer_id, created_at) that also stores total can avoid up to 20 fetches from scattered pages. The price is a bigger index, and more updates, since changing total now touches it too.
An insert must change the table and every index. As an example, 2,000 inserts per second into a table with 6 secondary indexes means about 14,000 page changes per second, each logged. Dropping 3 unused indexes cuts that to 8,000. Indexes also take disk space and compete for memory with the data they describe. So index for queries you have measured, check usage counts (Postgres reports them in pg_stat_user_indexes), and skip indexes on tiny tables and for queries that read most rows anyway.
An orders table has 9 indexes, and the nightly bulk import no longer fits its 6-hour window. Usage stats show that 4 indexes serve regular queries, and the other 5 show almost no scans over the last 30 days. What do you do?
Check the 5 idle indexes against less frequent jobs such as quarterly reports, which a 30-day window misses, then drop the ones nothing needs. If the import still runs long, consider dropping the rest for the load and rebuilding them afterward, because building an index from sorted data is usually faster than inserting entries row by row. That only works if queries can tolerate the missing indexes during the rebuild; otherwise split the import into smaller batches.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Every index speeds some reads and adds work to every write that touches its columns.
- A covering index trades storage and write cost for skipping the row fetch.
- Index for measured queries, and drop the ones nothing uses.