Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Why Database Queries Slow Down as Data Grows and How Indexes Help

· 8 min read · Home Tech

In this article
  1. Background: How Databases Store and Read Data
  2. How Indexes Work: The Sorted Lookup
  3. Why Queries Slow Down Even With Indexes
  4. How to Choose Indexes: Practical Guidelines
  5. Common Problems and Misconceptions
  6. Alternatives to Indexes for Large Data
  7. Costs and Trade-offs of Indexes
  8. Frequently Asked Questions

Database queries slow down as data grows because the database must scan more rows to find the ones you need, and indexes help by acting like a sorted lookup table that lets the database jump directly to the relevant rows instead of reading everything. Without an index, a query on a large table becomes a full table scan, and the time grows roughly in proportion to the number of rows. With a well-chosen index, the same query can often return results in milliseconds even on tables with millions of rows.

Background: How Databases Store and Read Data

To understand why queries slow down, you need to know how a database physically stores data. Most relational databases (like PostgreSQL, MySQL, and SQL Server) store table rows in fixed-size blocks or pages, typically 4 to 16 KB each. When you run a query, the database reads these pages from disk into memory. Reading from disk is thousands of times slower than reading from memory, so the number of pages the database must read is the main factor in query speed.

When a table is small, all its pages might fit in memory, and even a full scan is fast. As data grows, the table spans more pages, and eventually the database must read pages from disk. A full table scan reads every page, so the time grows linearly with the number of rows. For a table with 1 million rows, a full scan might read 100,000 pages; for 10 million rows, it reads 1 million pages. That is why queries that were instant on a small table become seconds or minutes later.

How Indexes Work: The Sorted Lookup

An index is a separate data structure, usually a B-tree, that stores a sorted copy of one or more columns along with pointers to the actual rows. Think of it like the index at the back of a book: instead of reading every page to find a topic, you look up the topic in the index and jump straight to the page.

When you create an index on a column, the database builds a balanced tree. The tree is sorted, so finding a specific value takes O(log n) steps, where n is the number of rows. For a table with 1 million rows, that is about 20 steps; for 1 billion rows, about 30 steps. This is dramatically faster than scanning all rows. Once the database finds the index entry, it follows the pointer to the actual row in the table.

Indexes also help with sorting and joins. If a query uses ORDER BY on an indexed column, the database can read the index in order without sorting. If a query joins two tables on an indexed column, the database can use the index to find matching rows quickly.

Why Queries Slow Down Even With Indexes

An index is not a magic bullet. Several factors can still cause slowdowns:

  • Selectivity: If an index column has few distinct values (like a boolean flag), the index may return a large fraction of the table, and the database might decide a full scan is faster.
  • Index size: Indexes themselves take up space and must be read from disk. A large index can be slower than a small table scan if the query returns a high percentage of rows.
  • Random I/O: When an index points to rows scattered across many pages, the database must perform many random disk reads. Sequential reads (as in a full scan) are faster than random reads, so for queries that return more than a few percent of rows, a full scan can win.
  • Index maintenance: Every insert, update, or delete must update the index. This adds overhead to write operations, so a table with many indexes can slow down data ingestion.
  • Outdated statistics: The database uses statistics about data distribution to choose a query plan. If statistics are stale, it may pick a bad plan, such as ignoring a useful index.

How to Choose Indexes: Practical Guidelines

Choosing the right indexes requires understanding your queries. Here are common steps:

  1. Find the slow queries in your database logs or query analyzer.
  2. Look at the WHERE clause columns. These are the primary candidates for indexes.
  3. Consider columns used in JOIN conditions. Indexing foreign keys is almost always beneficial.
  4. For queries with multiple conditions, create a composite index that matches the order of the conditions. For example, a query filtering on last_name and first_name benefits from an index on (last_name, first_name).
  5. Use EXPLAIN to see whether the database is using the index and how many rows it estimates.
  6. Drop unused indexes. Each index adds write overhead and takes disk space.

A common mistake is indexing every column. That wastes space and slows writes without helping queries. Indexes should be tailored to the queries you actually run.

Common Problems and Misconceptions

One common misconception is that an index on a column automatically speeds up every query on that column. In reality, the database's query planner decides whether to use the index based on cost estimates. If the query returns a large portion of the table, the planner may skip the index because a full scan is cheaper.

Another issue is leading wildcard searches. A query like WHERE last_name LIKE '%son%' cannot use a normal B-tree index because the wildcard is at the start. The index is sorted by the first character, so a search for a substring anywhere in the column requires a full scan. For such cases, full-text indexes or trigram indexes (in PostgreSQL) can help.

Indexes also do not help with functions applied to columns. A query like WHERE YEAR(created_at) = 2024 will not use a normal index on created_at because the function transforms the column before comparison. A functional index on YEAR(created_at) would work, but it is often simpler to use a range condition like WHERE created_at BETWEEN '2024-01-01' AND '2024-12-31'.

Alternatives to Indexes for Large Data

When indexes are not enough, other techniques can help:

  • Partitioning: Splitting a large table into smaller pieces based on a key (like date) so queries only scan relevant partitions.
  • Materialized views: Precomputing and storing the result of a complex query, then refreshing it periodically.
  • Denormalization: Adding redundant columns or tables to avoid expensive joins.
  • Columnar storage: Using a column-oriented database (like ClickHouse or Amazon Redshift) for analytical queries that scan many rows but few columns.
  • Caching: Storing frequently accessed query results in memory (e.g., Redis) to avoid hitting the database at all.

Each alternative has trade-offs. Partitioning adds complexity, materialized views can be stale, denormalization can cause data inconsistency, and caching requires invalidation logic. Indexes remain the first line of defense for most OLTP workloads.

Costs and Trade-offs of Indexes

Indexes are not free. Every index consumes disk space and memory. For a large table, a composite index can be as large as the table itself. More importantly, every write operation (INSERT, UPDATE, DELETE) must update all indexes on the table. This can significantly slow down data ingestion, especially in high-volume systems.

There is also a maintenance cost. As data changes, indexes can become fragmented, and the database may need to reorganize them. Some databases do this automatically, but large tables may require manual maintenance. Finally, the query planner needs accurate statistics to use indexes well, so you may need to run ANALYZE or UPDATE STATISTICS periodically.

In practice, a table with 5-10 indexes is common for a busy OLTP system, but adding more than that often yields diminishing returns. The key is to measure: use EXPLAIN to see whether an index is actually being used, and monitor write performance to catch overhead.

Frequently Asked Questions

Why does my query get slower even though I have an index?

An index may not be used if the query returns a large percentage of rows, if the index column has low selectivity, or if the query uses a function on the column. Also, the database might have stale statistics, causing it to underestimate the index's usefulness. Run ANALYZE and check the query plan with EXPLAIN.

Do indexes slow down inserts?

Yes. Every insert must add entries to all indexes on the table. With many indexes, insert performance can drop noticeably. However, for most applications, the read speedup outweighs the write overhead. If writes are critical, consider fewer indexes or using a database that handles index maintenance efficiently.

Can I index a column that contains NULL values?

Yes. In most databases, NULL values are stored in the index. However, a query like WHERE column IS NULL may or may not use the index depending on the database. Some databases (like PostgreSQL) can use an index for IS NULL queries, while others may not. Test with EXPLAIN.

What is a composite index and when should I use it?

A composite index is an index on multiple columns, like (last_name, first_name). It is useful when queries filter on both columns, especially if the first column has high selectivity. The order of columns matters: the index can only be used for range conditions on the first column, and the second column is only used if the first is an equality condition.

How do I know if an index is being used?

Use the EXPLAIN command (or EXPLAIN ANALYZE) to see the query plan. It will show whether the database uses an index scan, a bitmap scan, or a sequential scan. If you see a sequential scan on a large table, your index may not be helping.

Does an index help with sorting?

Yes. If a query uses ORDER BY on an indexed column, the database can read the index in sorted order and avoid a separate sort step. This is especially helpful for large result sets. However, if the query also filters on another column, the database may need to sort anyway.