Database Indexes: B-Tree, Hash, Covering, and Beyond

A practical guide to database indexes. Learn when to use B-tree, hash, composite, and partial indexes, understand index maintenance overhead, and avoid common performance traps.

published: reading time: 28 min read author: Geek Workbench updated: November 18, 2026
Quick Summary

Indexes can help selective queries, but a database may prefer a sequential scan for a small table or a query that returns many rows. In PostgreSQL, B-tree indexes support equality and range comparisons, while hash indexes support equality only; neither guarantees a faster plan. Use EXPLAIN to compare scan choices, then measure actual reads and writes on representative data before keeping an index.

Database Indexes: B-Tree, Hash, Covering, and Beyond

An index can save work when a query returns a small share of a large table. A sequential scan may be cheaper for a small table or a query that returns many rows, especially when its pages are already cached. There is no general millisecond guarantee: the result depends on the engine, data, query, and workload. This guide introduces common index types and ways to check whether one helps.

How B-Tree Indexes Work

flowchart TD
    Root["Root: [15]"]
    L1A["Leaf A: [5, 10]"] --> Root
    L1B["Leaf B: [15, 20]"] --> Root
    L1C["Leaf C: [25, 30, 35]"] --> Root
    L1A --> L1AL["5 → row_ptr"]
    L1A --> L1AR["10 → row_ptr"]
    L1B --> L1BL["15 → row_ptr"]
    L1B --> L1BR["20 → row_ptr"]
    L1C --> L1CL["25 → row_ptr"]
    L1C --> L1CM["30 → row_ptr"]
    L1C --> L1CR["35 → row_ptr"]

B-trees cluster data at leaf nodes, with internal nodes routing lookups. A lookup for WHERE id = 20 traverses root → Leaf B → returns the row pointer. Range queries like WHERE id > 15 AND id <= 25 follow the same path to 15, then scan forward through Leaf B and Leaf C.

Why Indexes Exist

A sequential scan checks the table’s pages to find matching rows. For a small table, that can be cheaper than consulting an index; for a selective query on a large table, an index may avoid reading many unrelated pages. A database can also choose a sequential scan when a query needs a large share of the rows. An index is a separate structure that the engine maintains to support particular query patterns.

The tradeoff is space and maintenance. Indexes consume disk space. When rows are inserted, updated, or deleted, the database must update every index on that table.

B-Tree Indexes

B-tree is the default index type in PostgreSQL and a common general-purpose choice in other relational databases. The exact default types and available index features vary by engine.

B-trees maintain sorted order, so PostgreSQL can consider them for equality and range comparisons, as well as ordered output. For example, WHERE created_at > '2024-01-01' can use a B-tree when the planner estimates that path is worthwhile. It may choose a sequential scan instead if the table is small or the predicate matches many rows.

Equality queries can use B-trees too. For WHERE email = 'user@example.com', the planner may use the index if that is estimated to cost less than scanning the table.

CREATE INDEX idx_users_email ON users(email);

B-trees handle most query patterns. If you are not sure what index type to use, start with B-tree.

Hash Indexes

The syntax below is PostgreSQL-specific. PostgreSQL hash indexes store a 32-bit hash code and support simple equality comparisons. They are not inherently faster than B-trees; compare plans and workload measurements before choosing one.

CREATE INDEX idx_sessions_token ON sessions USING HASH (token);

Because PostgreSQL hash indexes do not maintain sorted order, they cannot support range conditions such as WHERE created_at > '2024-01-01' or provide sorted output. A prefix pattern such as name LIKE 'John%' is not an equality comparison, so a hash index does not support that lookup either.

The fact that a cache or session store uses a hash table internally does not mean a PostgreSQL hash index is automatically the right choice. For an exact-match query, test both the hash index and the usual B-tree option with the database and workload you use.

Composite Indexes

A composite index spans multiple columns. The index is sorted by the first column, then the second within each first-column value.

CREATE INDEX idx_orders_customer_date ON orders(customer_id, order_date DESC);

This index is a natural candidate for queries filtering by customer_id, with or without an order_date condition. Queries that filter only by order_date usually cannot use the leading part as effectively, though index support depends on the database version and plan. In PostgreSQL 18, a B-tree skip scan can help in some cases when the omitted leading column has few distinct values; it is not a guarantee.

Column order matters, but there is no universal rule to put the most selective column first or to put every equality column before a range. Start with the query patterns you need, then compare candidate indexes with the planner. For a deeper guide to composite, covering, and partial index choices, see Index Design Clinic.

Covering Indexes

A covering index includes all columns needed by a query, not just the indexed ones. The database can satisfy the query entirely from the index without reading the table.

CREATE INDEX idx_orders_covering ON orders(customer_id)
    INCLUDE (order_id, order_date, total_amount);

This index covers queries like:

SELECT order_id, order_date, total_amount
FROM orders
WHERE customer_id = 123;

The database reads only the index, not the table. For high-frequency queries that select few columns, covering indexes provide significant speedups.

Covering indexes add overhead. They consume more space and slow down writes because more data must be written to the index. Use them for frequently executed queries, not every query.

Partial Indexes

A partial index covers only rows matching a condition. This reduces size and maintenance overhead while speeding up specific queries.

CREATE INDEX idx_orders_pending ON orders(created_at)
WHERE status = 'pending';

This index only indexes pending orders. Queries filtering by status=‘pending’ and created_at benefit. Other queries do not.

Partial indexes suit tables with skewed distributions. If most rows have a common status and you frequently query the rare statuses, partial indexes focus on what matters.

When to Index

Index columns that appear in WHERE clauses. If you frequently filter by status, index status. If you join on customer_id, index customer_id.

Index columns used in ORDER BY. Databases can avoid sorting steps if an index provides the required order.

Index foreign keys. Joins perform much better when the database can look up rows by indexed values.

Index columns with high selectivity. An index on a boolean column that is 99% true provides little benefit because most rows match. An index on an account number that is unique is maximally selective.

Capacity Estimation: B-Tree Depth and Size

B-tree depth limits how many index pages a lookup may need to visit. Most B-trees stay shallow even with large tables, and those pages may already be in memory.

Depth calculation: a B-tree with a branching factor of roughly 100–300 entries per internal node reaches depth 3 with 1 million to 270 million leaf entries. In practice, a B-tree index on an ID column with 100 million rows typically has depth 3 or 4. A lookup may visit pages at each level, but this does not mean one physical disk read per level: cached pages need no disk I/O. A matching row can also require a heap-page visit in PostgreSQL unless an index-only scan can avoid it.

Index size estimation: the index entry storage is roughly key_size + 8 bytes per row for the ctid/toast pointer plus B-tree overhead. A 4-byte INTEGER key with a 6-byte PostgreSQL ctid totals about 18 bytes per entry. For 100 million rows, that is roughly 1.8 GB for the leaf level, plus internal node overhead of maybe 5–10% more. A composite index on two 4-byte integers is 26 bytes per entry, or 2.6 GB for 100 million rows.

For covering indexes with INCLUDE columns, add the included column sizes. A covering index on customer_id (4 bytes) with INCLUDE of order_id (4 bytes), order_date (8 bytes), and total_amount (8 bytes) is effectively 32 bytes per row, not 12.

If your table is 10 GB and the indexed columns represent 20% of row size, the index will be roughly 2 GB. If you are unsure, most databases provide commands to estimate index size before creating it.

Index Type Trade-offs

Index Type Best for Avoid when Notes
B-tree (PostgreSQL default) Equality, range queries, sorted output Operators without a compatible operator class PostgreSQL’s general-purpose default
Hash (PostgreSQL) Equality comparisons on the indexed value Range queries and sorted output Supports equality only; benchmark against B-tree
Composite (B-tree) Queries filtering on leading column, or both columns Queries on a later column alone Check engine/version behavior and the actual plan
Covering (B-tree with INCLUDE) High-frequency queries with small SELECT lists Writes, queries selecting many columns Adds storage and slows writes
Partial Skewed distributions, rare status values Common values (most rows match) Dramatically reduces index size
GiST (PostgreSQL) Geometric, full-text, range types Simple equality Not a general-purpose index
GIN (PostgreSQL) JSONB, arrays, full-text search Simple scalar columns Slow to build, fast to query

Common Production Failures

Wrong index selected by the query planner: Sometimes the planner picks a suboptimal index — a partial index with a different WHERE clause, or a composite index on the wrong column order. Query plans that looked fine on small tables behave differently at scale. Monitor slow queries and use EXPLAIN ANALYZE to verify the index actually gets used.

Index bloat from frequent updates: Heap-only tuples (HOT updates) that cannot reuse dead tuples cause index bloat over time. In PostgreSQL, monitor pg_stat_user_indexes for increasing idx_scan counts without corresponding query speedup. Heavy UPDATE workloads on columns with moderate cardinality can bloat indexes faster than expected.

Covering index column order mistakes: Adding columns to the INCLUDE clause of a covering index without considering query patterns wastes space and slows writes. INCLUDE columns should be the most frequently selected non-indexed columns, not an afterthought.

Forgetting that partial indexes are invisible to statistics: PostgreSQL’s statistics collector does not track partial indexes well. The planner may underestimate selectivity for partial indexes on rare values, leading to table scans when the index would be faster. Verify planner choices with EXPLAIN ANALYZE, not assumptions.

When NOT to Index

Do not index columns you never filter on. Indexes consume space and slow writes without helping reads.

Do not index low-selectivity columns unless you specifically need them. An index on a gender column or a status column with three values rarely helps.

Do not over-index write-heavy tables. Each index must be updated on every insert, update, and delete. Tables with heavy write loads need fewer indexes.

Index Maintenance Overhead

Indexes are not free. Every write operation must update every index on the table. A table with ten indexes costs ten times more to write to than a table with one index.

This matters for write-heavy workloads. Bulk inserts are much slower with many indexes. Some ETL processes drop indexes before loading and recreate them after.

Monitor index usage. Databases track whether indexes are used. Unused indexes waste space and add overhead. Drop them.

Real-World Case Study: PostgreSQL Index-Only Scans

PostgreSQL’s index-only scan feature lets a query return results entirely from the index, without touching the heap. For queries that select only indexed columns, this can cut response time dramatically.

Stack Overflow used this extensively. Their database serves millions of reads per day. A query like SELECT id, title, created_at FROM posts WHERE user_id = 123 can be served entirely from an index on (user_id) INCLUDE (id, title, created_at) — the database reads the index, finds matching rows, and returns without ever touching the main posts table. For their read-heavy workload, this cut latency in half on their most common query patterns.

The catch: visibility map. PostgreSQL only uses index-only scans on pages where it knows all rows are visible to the current transaction. Pages with recently modified rows have bits cleared in the visibility map, forcing heap access anyway. Running VACUUM frequently keeps the visibility map current. On tables with high write volumes, index-only scans might not trigger at all without aggressive autovacuum tuning.

The lesson: covering indexes with INCLUDE columns are not free — they consume more storage and slow writes. But for read-heavy tables where the same few columns are selected repeatedly, the read performance gain is worth it. Profile the actual query patterns before adding covering indexes speculatively.

Identifying Missing Indexes

Query plans show the access path the planner chose. The commands and output differ by database, so the following PostgreSQL example uses EXPLAIN and EXPLAIN ANALYZE.

EXPLAIN SELECT order_id, created_at
FROM orders
WHERE customer_id = 123;

Here are simplified plan shapes for the same query before and after adding an index. They are illustrations, not measured output; PostgreSQL may keep the sequential scan if it estimates that to be cheaper.

-- Before: no useful index, or a sequential scan costs less
Seq Scan on orders
  Filter: (customer_id = 123)

-- After: an index on a selective customer_id can be cheaper
Index Scan using orders_customer_id_idx on orders
  Index Cond: (customer_id = 123)

Compare estimated rows and costs with EXPLAIN. To see actual rows, buffer activity, and elapsed time, run EXPLAIN (ANALYZE, BUFFERS) on a representative SELECT; ANALYZE executes the statement. The planner’s cost units are estimates, not milliseconds. An index can still lose when the table is small, many rows match, or relevant pages are cached. After checking read plans, measure write throughput and index storage as well: each added index adds maintenance work, and its cost varies with the data and workload.

CREATE INDEX orders_customer_id_idx ON orders (customer_id);

EXPLAIN (ANALYZE, BUFFERS)
SELECT order_id, created_at
FROM orders
WHERE customer_id = 123;

Slow query logs flag frequently executed slow queries. Add indexes based on what your application actually queries, not what you think it queries.

Interview Questions

1. A query that used an index is suddenly doing a table scan. What happened?

The most common causes: statistics went stale after a large data load, causing the planner to underestimate row counts. An index was dropped or disabled. The query changed — different operator or column — and the existing index no longer matches. A different execution path is being chosen because session parameters changed (like enable_seqscan). Run EXPLAIN and compare to a known-good plan from when it was fast.

2. How do you decide between a composite index and multiple single-column indexes?

Composite indexes are better when queries consistently filter on both columns together, or when the index can serve as a covering index for common queries. Multiple single-column indexes are better when queries filter on different combinations of columns independently. The PostgreSQL query planner can combine single-column indexes with index scans, but a composite index may be faster for some query shapes. Profile the actual queries.

3. When would you choose a partial index over a regular index?

Partial indexes make sense when a significant portion of the table is never queried. If 95% of your orders have status='completed' and you only query status='pending' orders, a partial index on pending orders is dramatically smaller and faster than a full index on status. They also help when you need an index on an expression that only applies to a subset of rows. The tradeoff is that queries outside the partial index condition cannot use it.

4. An application query is slow. You find it is doing a sequential scan on a 50-million-row table despite having an index on the filter column. Why would the planner choose a seqscan over an index scan?

PostgreSQL may choose a sequential scan when the query needs many rows, when the table is small, or when relevant pages are already cached. There is no fixed percentage at which that choice becomes correct; row width, data distribution, storage, cache state, and planner settings all matter. Check statistics and compare plans first. If you temporarily set enable_seqscan = off to inspect an alternative plan, treat it as a diagnostic, not a production fix.

5. You are designing indexes for a new schema. What is your process?

Start with the queries the application actually runs, not theoretical access patterns. Identify the most frequent and most latency-sensitive queries. For each, find the filter columns and select columns. Add indexes to support the filters, and covering indexes if the same columns are selected repeatedly. Add foreign key indexes for joins. Then measure under realistic write load to see whether the indexes slow inserts enough to matter. On write-heavy tables, keep indexes lean — every unnecessary index delays writes.

6. What is the difference between a B-tree index and a hash index?

In PostgreSQL, B-tree indexes support equality and range comparisons and can provide sorted output. PostgreSQL hash indexes support simple equality comparisons only. Neither type is always faster; compare plans and workload measurements. The USING HASH syntax and these capabilities are PostgreSQL-specific, so check the documentation for another database.

7. What is a covering index and when would you use one?

A covering index includes all columns needed by a query, not just the indexed ones. The database can satisfy the query entirely from the index without reading the table (index-only scan). Use covering indexes when you frequently select a small set of columns and the WHERE clause filters on a different set. The tradeoff is more storage and slower writes because more data must be written to the index. Use INCLUDE columns (non-key columns stored in the index leaf) rather than adding them as key columns when the included columns are not used in filtering.

8. What is index bloat and how does it affect performance?

Index bloat occurs when deleted or updated rows leave gaps in the index that are not reclaimed efficiently. In PostgreSQL, frequent HOT updates (heap-only tuple updates that reuse the same page) can cause index bloat over time because the index entries must still point to the updated rows. Bloat increases index size, reduces cache efficiency, and slows scans because more pages must be read. Monitor with pg_stat_user_indexes and reclaim with REINDEX or VACUUM. Heavy UPDATE workloads on columns with moderate cardinality bloat indexes faster than expected.

9. How do you calculate the size of an index before creating it?

Index entry size is roughly key_size + 8 bytes for the ctid/toast pointer plus B-tree overhead. A 4-byte INTEGER key with a 6-byte PostgreSQL ctid totals about 18 bytes per entry. For 100 million rows, that is roughly 1.8 GB for the leaf level, plus internal node overhead of 5-10% more. A composite index on two 4-byte integers is 26 bytes per entry, or 2.6 GB for 100 million rows. For covering indexes, add the included column sizes. If your table is 10 GB and the indexed columns represent 20% of row size, the index will be roughly 2 GB.

10. What is the write overhead of indexes on INSERT operations?

Every index must be updated on every INSERT. A table with 10 indexes costs 10 times more to insert into than a table with one index. Bulk inserts are much slower with many indexes — some ETL processes drop indexes before loading and recreate them after. The write overhead is most noticeable on high-frequency write paths. Estimate: if you insert 10,000 rows per second and have 5 indexes, you are doing 50,000 index inserts per second. Profile actual write throughput to determine whether indexes are a bottleneck.

11. What is the difference between a unique index and a primary key index?

Both enforce uniqueness, but primary key indexes cannot contain NULLs while unique indexes allow NULLs (multiple NULLs depending on database). Primary key indexes create a clustered index by default in most databases except PostgreSQL. Unique indexes create non-clustered indexes by default. A table can have many unique indexes but only one primary key. Use primary keys for row identifiers. Use unique indexes for columns that should be unique but are not the row identifier (like email addresses).

12. How does column order in a composite index affect query performance?

In a composite index (a, b), the index is ordered by a and then b within each value of a. It is a natural fit for queries on a or on both columns. A query on b alone often cannot narrow the leading part of the index, although PostgreSQL 18 can consider a skip scan when the omitted leading column has few distinct values. Choose column order from the query patterns you need, then compare plans on representative data instead of following a fixed selectivity rule.

13. What is an index-only scan and when does PostgreSQL use it?

An index-only scan returns results entirely from the index without touching the heap. PostgreSQL uses it when the query selects only indexed columns and the planner estimates the visibility map shows all relevant pages are visible to the current transaction. The visibility map must be current — on tables with high write volumes, index-only scans may not trigger without frequent VACUUM. Covering indexes with INCLUDE columns are the most reliable way to enable index-only scans for specific queries.

14. What is the relationship between statistics and index selection?

PostgreSQL's query planner uses statistics to estimate row counts and selectivity for different access paths. When statistics are stale (after bulk loads, large deletes, or significant data changes), the planner makes poor index selection decisions. Always run ANALYZE after bulk operations. The statistics collector tracks the distribution of column values. If a partial index captures a rare value but statistics do not reflect this, the planner may underestimate the index's selectivity and choose a sequential scan instead.

15. What is the fillfactor parameter and how does it affect index performance?

The fillfactor determines how full each index page is when created. Default is 90% for B-tree indexes, leaving 10% free for future inserts. A lower fillfactor reduces page splits during inserts, which is beneficial for indexes with high insert rates. However, lower fillfactor means more pages, larger indexes, and fewer rows per page, which can slow read-only scans. Set fillfactor based on the workload: high write volume benefits from lower fillfactor, read-heavy workloads benefit from higher fillfactor.

16. What happens when you index a column that has low selectivity?

Low selectivity means most rows have the same value — like a boolean column that is 99% true. An index on such a column returns nearly the full table regardless of the filter value. The index lookup saves little or no work, but the database still must traverse the index and fetch rows. In the worst case, the planner chooses the index, reads all matching rows from the index, then does a full table scan anyway because nearly every row matches. Low-selectivity indexes waste storage and slow inserts.

17. What is the difference between a partial index and a expression index?

A partial index is created with a WHERE clause, indexing only rows matching the condition. An expression index indexes the result of a function or expression on columns. Partial indexes filter rows by a condition on the base columns — WHERE status = 'pending'. Expression indexes transform the indexed value — ON lower(email). Both reduce index size by excluding rows that do not match the expression. Use partial indexes when you filter on a specific condition. Use expression indexes when you query on a function of a column.

18. How do you decide which columns to include in a covering index?

Include columns that are frequently selected but not used in the WHERE clause. The goal is to eliminate heap access entirely for specific queries. Start with the columns in your WHERE clause as key columns, then add columns from the SELECT list that are not already in the key columns as INCLUDE columns. Do not add every frequently selected column — each included column increases index size and slows writes. Only include columns where eliminating heap access provides measurable query improvement.

19. What is index bloat from page splits and how does it occur?

When a B-tree index page fills up and a new row needs to be inserted in the middle, the page splits into two pages, with roughly half the entries moving to the new page. This creates pages that are not fully utilized. Over time with random inserts (especially UUIDs), this pattern repeats, causing the index to grow larger than necessary and reducing cache efficiency. Sequential inserts (auto-increment keys) minimize splits because new values always go at the end of the index. UUIDs inserted with uuid_generate_v4() are random and cause significant page splits.

20. When should you drop an unused index?

Drop an index when it has never been used (check pg_stat_user_indexes for nonzero idx_scan), when it is used so rarely that its storage cost and write overhead exceed its occasional read benefit, or when a query change means the index is no longer needed for any query pattern. Before dropping any index, verify it is not used by any query including infrequent batch jobs. Monitor for at least one full business cycle before dropping, and always verify using pg_stat_statements rather than just pg_stat_user_indexes, since some usage patterns may not trigger idx_scan.

For more on query performance, see [query execution plans](/blog/technical/query-execution-plans/). To understand how indexes fit into broader schema design, explore [schema design](/blog/technical/schema-design/) and [relational databases](/blog/technical/relational-databases/).

Real-world Failure Scenarios

Scenario 1: The Covering Index That Doubled Storage Costs

What happened: A developer added a covering index to speed up a high-frequency query that selected 8 columns. The index grew to 40GB on a 60GB table, doubling the effective storage footprint and slowing down writes significantly. The query was 20% faster but storage costs were unacceptable.

The query ran 50,000 times per minute on a reporting dashboard. The developer used PostgreSQL’s INCLUDE syntax to store all 8 selected columns in the index, eliminating heap fetches entirely. Index-only scans on a read-heavy workload made sense here. What nobody measured upfront was the write amplification.

Root cause: The covering index included columns that changed frequently (status, updated_at), causing index maintenance overhead on every write. The INCLUDE clause added 6 columns to a table with already 12 indexes, multiplying write amplification. Each UPDATE to status or updated_at now touched 13 index structures instead of 1.

The table had 12 existing indexes for various query patterns. Adding a covering index on top meant every INSERT and UPDATE had to maintain 13 separate index entries. On a table receiving 5,000 writes per second, this translated to 65,000 index entries being updated per second instead of 5,000.

Impact: Storage costs increased by 40GB. Write throughput decreased by 30% on the indexed table. The query improvement did not justify the storage and write overhead.

Lesson learned: Covering indexes are not free. Each included column adds storage and slows writes. Only use covering indexes when the read performance gain is measured and justified, and when write throughput is not a bottleneck. Start with the minimum viable set of INCLUDE columns and add only what eliminates heap access for that specific query.

Scenario 2: The Partial Index That the Planner Ignored

What happened: A partial index on rare status values was created to speed up queries for those specific rows. Query plans showed the planner was ignoring the partial index and doing sequential scans instead. The rare status queries that should have been fast were still slow.

The team had a table with 50 million rows where 95% had status = 'completed' and only 5% had status = 'pending'. Users needed to query pending orders to process the backlog. The partial index created was CREATE INDEX idx_orders_pending ON orders(created_at) WHERE status = 'pending'. The idea was sound: a tiny index covering only the rows that mattered, updated automatically as rows transitioned between states.

Root cause: PostgreSQL statistics do not track partial indexes well. The planner underestimated how selective the partial index was and chose a sequential scan because it appeared cheaper. Stale statistics after a large data load made the problem worse.

PostgreSQL’s planner relies on pg_statistic to estimate row counts, but partial indexes are not represented in those statistics. The planner saw a table with 50 million rows and assumed a sequential scan was faster than an index lookup that required random I/O. It was wrong, but without forcing the issue, it kept choosing the sequential scan. Running ANALYZE on the table refreshed the general statistics but still did not help the planner understand the partial index’s selectivity.

Impact: Slow queries for rare status values persisted despite the partial index existing. The team spent 2 days debugging before identifying the statistics issue.

Lesson learned: Partial indexes are invisible to PostgreSQL statistics. Always verify that partial indexes are actually being used with EXPLAIN ANALYZE, and run ANALYZE after creating them to ensure the planner has current information. If the planner ignores a partial index, use SET enable_seqscan = off to force index usage and compare performance before concluding the index is not worth keeping.

Scenario 3: The Dropped Index That Caused a Cascade of Slow Queries

What happened: A DBA dropped an unused index to reduce write overhead. Within hours, multiple queries that the application depended on became dramatically slower. The queries had never been flagged as slow because they ran infrequently, but when triggered they were now doing full table scans.

The index in question was on a metadata column used for ad-hoc reporting. It had been created 18 months earlier when a one-time analysis was run. Since then, idx_scan on that index was zero — it never appeared in any query execution path that the monitoring system captured. The DBA used pg_stat_user_indexes to identify it as a candidate for removal, citing the zero scan count. What nobody caught was that the index was critical for a month-end financial report that ran once per month at 2 AM, outside of peak monitoring windows.

Root cause: The queries were infrequent but expensive. They relied on an index that appeared unused based on low idx_scan counts but was actually essential for those specific query patterns. The idx_scan metric had not captured the queries because they ran during off-peak hours.

pg_stat_user_indexes.idx_scan only increments when the index is scanned during regular query execution. Scheduled jobs, batch processes, and ad-hoc reports run outside of peak monitoring windows often do not register in real-time dashboards. The index was not unused — it was used once per month by a query that selected all rows where metadata->>'quarter' = 'Q4' to aggregate quarterly financials.

Impact: Several business-critical reports timed out during the next morning’s batch run. The index was re-added immediately, but the incident took 3 hours to fully diagnose and resolve.

Lesson learned: Before dropping any index, verify it is not used by any query pattern, including infrequent or batch queries. Check pg_stat_statements for actual query patterns, not just pg_stat_user_indexes. pg_stat_statements captures all query execution counts regardless of timing, while pg_stat_user_indexes only shows whether the index physically participated in a plan. Monitor for at least one full business cycle (including batch jobs, month-end reports, and scheduled maintenance) before dropping any index.

Further Reading

Conclusion

Indexes are one way to reduce work for particular query patterns. In PostgreSQL, B-trees support equality and range comparisons, while hash indexes support equality only. A planner can still prefer a sequential scan, and an index-only scan may still need heap visits to check row visibility. Check plans on representative data, then compare read performance, write cost, and storage before keeping an index.

Category

Related Posts

Index Design Clinic: Composite Indexes, Covering Indexes, and Partial Indexes

Master composite index column ordering, covering indexes for query optimization, partial indexes for partitioned data, expression indexes, and selectivity.

#database #indexes #composite-indexes

Query Execution Plans: Reading EXPLAIN Output Like a Pro

Learn to decode PostgreSQL EXPLAIN output, understand sequential vs index scans, optimize join orders, and compare bitmap heap scans with index-only scans.

#database #query-optimization #explain

Denormalization

When to intentionally duplicate data for read performance. Tradeoffs with normalization, update anomalies, and application-level denormalization strategies.

#database #denormalization #performance