Database Index Timing: A Workload Guide
In this article
You should add a database index when a specific query pattern repeatedly scans more rows than it returns, and the cost of maintaining the index is lower than the time saved. The decision hinges on your workload's read-to-write ratio, the size of your tables, and the latency targets you must meet. This guide walks through the signals that indicate an index is needed, how to choose the right columns, and the trade-offs involved.
How Database Indexes Work
An index is a separate data structure, typically a B-tree, that stores a sorted copy of selected columns along with pointers to the full rows. When a query filters on an indexed column, the database can traverse the tree in logarithmic time instead of scanning every row sequentially. For example, a query like SELECT * FROM orders WHERE customer_id = 42 on a table with 10 million rows might scan all 10 million rows without an index, but with an index on customer_id, it can find the matching rows in milliseconds.
Indexes also speed up sorting and joins. A query that orders by created_at can read the index in order rather than sorting the entire result set. Similarly, a join between two tables on a foreign key column benefits from an index on that column in the child table. However, indexes are not free: every insert, update, or delete must update the index, adding overhead to write operations. The database also stores the index on disk, consuming space.
Signs Your Workload Needs an Index
You can identify missing indexes by observing query performance and execution plans. Common indicators include:
- Slow queries: Queries that take seconds or minutes when the table has millions of rows, especially when the result set is small.
- High sequential scans: The execution plan shows a "Seq Scan" (PostgreSQL) or "Table Scan" (SQL Server) on a large table for a query with a selective filter.
- Frequent queries on the same column: Your application repeatedly runs
WHEREclauses on the same column, such as a status field or a foreign key. - Sorting or grouping: Queries with
ORDER BY,GROUP BY, orDISTINCTthat cause temporary sorts on large datasets. - Join bottlenecks: Nested loop joins that repeatedly scan the inner table because no index exists on the join column.
Most databases provide tools to identify missing indexes. PostgreSQL's pg_stat_user_indexes and pg_stat_user_tables show index usage and table scans. MySQL's SHOW INDEX FROM table and the slow query log help. SQL Server has the Missing Index DMV. These tools give you concrete numbers on how often a query runs and how many rows it scans.
How to Choose the Right Columns
Once you identify a query that needs an index, you must decide which columns to include. The general rule is to index columns that appear in WHERE clauses, join conditions, and ORDER BY clauses. For composite indexes (multiple columns), the order matters: place the most selective column first, meaning the column with the highest cardinality (distinct values). For example, an index on (status, created_at) is better than (created_at, status) if you often filter by status and then sort by created_at.
Consider covering indexes, which include all columns needed by a query, so the database can answer the query entirely from the index without touching the table. For instance, if a query selects only customer_id and total from orders where status = 'paid', an index on (status, customer_id, total) covers it. This reduces I/O but increases index size and write overhead.
Be cautious with low-cardinality columns. An index on a boolean column like is_active may not help if the query returns a large fraction of the table. The database might still choose a full scan because it is faster than reading the index and then fetching rows. In such cases, a partial index (PostgreSQL) or filtered index (SQL Server) that includes only rows where is_active = true can be more effective.
Index Maintenance and Write Overhead
Every index adds cost to write operations. When you insert a new row, the database must add an entry to each index. When you update a column that is part of an index, the database must update the index entry. Deletes also remove entries. On a table with many indexes, write throughput can degrade significantly. For example, a table with five indexes might see a 20-30% slowdown on inserts compared to the same table with no indexes, depending on the database and hardware.
You should measure the write-to-read ratio of your workload. If your application is write-heavy (e.g., logging, telemetry, or high-frequency inserts), adding many indexes can hurt performance. Consider batching writes or using a separate table for high-volume logs. Conversely, if your workload is read-heavy (e.g., reporting, dashboards, or user-facing search), indexes are usually worth the overhead.
Index bloat is another concern. Over time, as rows are updated and deleted, indexes can become fragmented, wasting space and slowing scans. Most databases offer a REINDEX or ALTER INDEX REBUILD command to rebuild indexes. Regular maintenance, such as VACUUM in PostgreSQL or OPTIMIZE TABLE in MySQL, helps keep indexes efficient.
Common Mistakes and Misconceptions
One common mistake is indexing every column that appears in a query, leading to excessive storage and write overhead. Another is using a single-column index when a composite index would serve multiple queries. For example, if you have queries filtering on customer_id and on (customer_id, status), a single composite index on (customer_id, status) covers both, whereas two separate single-column indexes might not be used as efficiently.
Another misconception is that an index on a foreign key is always needed. While it is often beneficial, if you never join on that column or filter by it, the index is wasted. Similarly, indexing a column with very few distinct values (like a status flag) may not help because the database can't narrow the search enough.
Also, beware of using functions on indexed columns in the WHERE clause. For example, WHERE YEAR(created_at) = 2023 prevents the database from using an index on created_at because it must compute the function for every row. Instead, use a range condition: WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'.
When Not to Add an Index
There are situations where adding an index is counterproductive. If a table is very small (e.g., fewer than a few hundred rows), a full scan is faster than an index lookup because the index adds overhead. Similarly, if a query returns a large percentage of the table (e.g., more than 10-20%), the database will likely choose a sequential scan anyway. Indexing a column that is rarely used in queries is wasteful.
Write-heavy tables with strict latency requirements may not tolerate the extra index maintenance. For example, a real-time analytics ingest that handles thousands of inserts per second should minimize indexes. Instead, consider partitioning the table or using a columnar store for analytics.
Also, avoid indexing columns that are updated frequently, such as a "last_login" timestamp. Each update to that column requires an index update, which can cause contention and slow down the system. If you must index such a column, consider whether the query benefits outweigh the write cost.
Monitoring and Iterative Tuning
Indexing is not a one-time decision. You should monitor index usage and remove unused indexes. Most databases track how often an index is used. In PostgreSQL, query pg_stat_user_indexes to see idx_scan counts. If an index has zero scans over a long period, drop it. In MySQL, the performance_schema provides similar data.
When you add an index, measure the impact on both query latency and write performance. Use EXPLAIN ANALYZE (PostgreSQL) or SET STATISTICS IO ON (SQL Server) to compare execution plans before and after. Also, test with realistic data volumes; an index that helps on a million rows may not help on a billion rows, or vice versa.
Consider using a tool like pg_hint_plan (PostgreSQL) or query hints (SQL Server) to force the database to use a specific index for testing, but do not rely on hints in production. Instead, let the query planner make the decision based on updated statistics. Run ANALYZE (PostgreSQL) or UPDATE STATISTICS (SQL Server) after significant data changes to keep the planner informed.
Frequently Asked Questions
How many indexes should a table have?
There is no fixed number. A good rule of thumb is to have indexes for the most critical query patterns, typically 3-5 indexes per table. More than that can hurt write performance. Monitor index usage and remove any that are not used.
Should I index every foreign key?
Not necessarily. Index foreign keys that are used in joins or filters. If you never query on that column, the index is unnecessary. However, some databases require an index on the referencing column to avoid locking issues during deletes (e.g., MySQL InnoDB). Check your database's documentation.
What is the difference between a clustered and non-clustered index?
A clustered index determines the physical order of rows in the table. There can be only one per table. A non-clustered index is a separate structure that points to the rows. Clustered indexes are often on the primary key, but you can choose another column if it is frequently used for range queries.
Can an index make a query slower?
Yes, in some cases. If the query planner chooses to use an index that is not selective, it may perform many random I/O reads, which can be slower than a sequential scan. Also, if the index is large and does not fit in memory, accessing it can cause disk I/O. Always test with realistic data.
How do I know if an index is being used?
Use the database's monitoring tools. In PostgreSQL, query pg_stat_user_indexes for idx_scan counts. In MySQL, use SHOW INDEX and check the Cardinality column, or enable the slow query log. In SQL Server, use the sys.dm_db_index_usage_stats DMV.
What is a covering index?
A covering index contains all columns needed to satisfy a query, so the database can return results directly from the index without accessing the table. This reduces I/O but increases index size and write overhead. Use them for hot queries that run frequently.