PostgreSQL Indexes Explained: Why Some Queries Are Faster Than Others
A database query can be perfectly correct and still perform badly. Consider an application that stores millions of orders and regularly retrieves an order using its customer ID, filters orders by status, or displays a customer's most recent purchases. Without a suitable access path, PostgreSQL may need to examine a large portion of the table to find the rows that satisfy a query. As the table grows, the work can grow with it. An index gives PostgreSQL another way to locate data. Instead of searching every row in the table, the database can use an auxiliary data structure to identify promising row locations. For selective queries, that can substantially reduce the number of rows and data pages that must be examined. However, indexes are not automatic performance improvements. They consume storage, require maintenance when data changes, and introduce additional work during inserts, updates, and deletes. An index can also be slower than a sequential scan when a query needs a large…
// TABLE OF CONTENTS+
Why Database Indexes Matter
A database query can be perfectly correct and still perform badly. Consider an application that stores millions of orders and regularly retrieves an order using its customer ID, filters orders by status, or displays a customer's most recent purchases. Without a suitable access path, PostgreSQL may need to examine a large portion of the table to find the rows that satisfy a query. As the table grows, the work can grow with it. An index gives PostgreSQL another way to locate data. Instead of searching every row in the table, the database can use an auxiliary data structure to identify promising row locations. For selective queries, that can substantially reduce the number of rows and data pages that must be examined. However, indexes are not automatic performance improvements. They consume storage, require maintenance when data changes, and introduce additional work during inserts, updates, and deletes. An index can also be slower than a sequential scan when a query needs a large proportion of a table. The engineering problem is therefore not to create as many indexes as possible. It is to identify the queries that matter, measure their behavior, choose indexes that fit those queries, and verify the result with execution plans and representative workloads. This article investigates that process using PostgreSQL and a synthetic orders dataset. You will compare execution plans before and after indexing, interpret EXPLAIN ANALYZE, explore B-tree and composite indexes, and measure the trade-offs that accompany faster reads.
What Is a Database Index?
A database index is an auxiliary data structure that helps the database locate records matching a condition. In PostgreSQL, indexes are stored separately from the table's main row storage, commonly called the heap. An index entry contains indexed key values and information PostgreSQL can use to find the corresponding table row, with the exact representation depending on the index type. Imagine a table containing five million orders. To retrieve an order with a particular order ID, PostgreSQL could inspect the table's rows until it finds the matching record. An index on that ID can instead direct the search through an ordered structure to a much smaller set of candidate entries. This is similar to looking up a subject in the index of a textbook instead of reading every page. The analogy is not exact: a database index is a data structure managed by the database engine, and accessing the referenced row may still require additional work. Nevertheless, it illustrates the central idea: organize information to reduce the effort required to find it. PostgreSQL supports multiple index types, including B-tree, Hash, GiST, SP-GiST, GIN, and BRIN. B-tree is the usual starting point for conventional equality comparisons, range conditions, and ordered retrieval. Other index types serve different operators and data distributions. PostgreSQL
How a B-tree Index Organizes Values
A B-tree index maintains keys in an ordered, balanced structure. Searching follows a path through the tree rather than inspecting every indexed value. Internal pages guide the search toward the relevant part of the tree, while leaf pages contain ordered index entries that identify matching rows. Because the tree remains balanced as entries are added and removed, its height grows slowly relative to the number of entries. This makes B-tree indexes useful for equality predicates such as WHERE customer_id = 4200, range predicates such as WHERE total >= 100, and many ordering operations. A B-tree index does not mean PostgreSQL can retrieve every query result without touching the table. A normal index scan may find matching tuple locations in the index and then fetch the corresponding rows from the heap. Those additional accesses can be expensive when many rows match or when the referenced pages are scattered across storage. The planner weighs these costs when selecting a plan. An index scan, bitmap scan, or sequential scan may be appropriate depending on selectivity, row width, table size, caching, and the query's requirements. An index existing in the database does not guarantee that PostgreSQL will use it.
Build a Reproducible PostgreSQL Dataset
A useful performance experiment begins with data large enough to make competing execution strategies meaningful. A table containing ten rows is a poor benchmark for index selection because a sequential scan may be cheaper than navigating an index and fetching the same data. PostgreSQL's own documentation warns against drawing conclusions from tiny test datasets. PostgreSQL For this experiment, create an orders table with an order identifier, customer identifier, order status, order timestamp, total amount, and short reference value. Generate hundreds of thousands of records with a deterministic distribution. This is enough to demonstrate how selective predicates and composite indexes affect query plans on many ordinary development machines, although results will vary by hardware and configuration. The data will be synthetic. It is intended to demonstrate a repeatable method, not to reproduce the exact workload of an online store. The customer identifiers will be distributed across many values, order statuses will have a limited number of distinct values, and order timestamps will span a period of time. This combination lets us test both selective and less-selective conditions. Run the experiment on a local or disposable development database. Avoid running benchmark scripts against a production database because bulk inserts, index creation, cache warming, and repeated queries can affect real workloads.
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL,
status TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
total_amount NUMERIC(10, 2) NOT NULL,
reference_code TEXT NOT NULL
);The primary key creates a unique access path for orderid, so this experiment does not attempt to compare primary-key lookup performance against a table without a primary-key index. Instead, it focuses on customerid, status, and createdat, which are initially not indexed independently. The TIMESTAMPTZ column represents timestamps with time-zone-aware semantics. The generated values below use a fixed UTC starting point and deterministic intervals. The referencecode column adds some row width without creating an unnecessarily large dataset. The NUMERIC type provides exact decimal representation for monetary values, though it is not the only suitable representation for every financial workload. Here, it keeps the schema understandable and avoids introducing floating-point rounding as an unrelated issue.
INSERT INTO orders (
customer_id,
status,
created_at,
total_amount,
reference_code
)
SELECT
1 + ((g * 37) % 50000)::INTEGER,
CASE
WHEN g % 100 < 55 THEN 'completed'
WHEN g % 100 < 75 THEN 'pending'
WHEN g % 100 < 90 THEN 'shipped'
ELSE 'cancelled'
END,
TIMESTAMPTZ '2025-01-01 00:00:00+00'
+ (g % 31536000) * INTERVAL '1 second',
(10 + ((g * 13) % 99900) / 100.0)::NUMERIC(10, 2),
'ORD-' || LPAD(g::TEXT, 10, '0')
FROM generate_series(1, 500000) AS series(g);
ANALYZE orders;This script inserts 500,000 rows. It distributes customer identifiers across 50,000 values and assigns statuses according to a fixed pattern. The status distribution is intentionally uneven: completed accounts for 55 percent of the generated rows, while cancelled accounts for 10 percent. The generated timestamps span approximately one year. The customer and timestamp patterns are deterministic, which makes repeated dataset creation easier to compare. The distribution is still synthetic and has limitations: real customers may place orders at very different rates, and real workloads often contain correlations between customer identity, order status, and order date. The final ANALYZE command collects table statistics for the planner. Those statistics help PostgreSQL estimate the number of rows a query will return and compare possible execution plans. After substantial data changes, refreshing statistics can be important for interpreting planner decisions. PostgreSQL
SELECT COUNT(*) AS total_orders
FROM orders;
SELECT
status,
COUNT(*) AS order_count,
ROUND(
100.0 * COUNT(*) /
SUM(COUNT(*)) OVER (),
2
) AS percentage
FROM orders
GROUP BY status
ORDER BY order_count DESC;
SELECT
COUNT(DISTINCT customer_id) AS distinct_customers,
MIN(created_at) AS first_order,
MAX(created_at) AS last_order
FROM orders;Verify that the table contains 500,000 rows and that the status distribution is consistent with the insertion script. The distinct customer count should be 50,000 for this dataset. These checks are not merely administrative: a benchmark is only useful if the underlying data matches the assumptions used to interpret it. The first test query will retrieve the orders for a particular customer. Because customer identifiers are distributed across many customers, a typical customer has roughly ten orders in this dataset. That is a relatively selective query, making it a useful candidate for a B-tree index. Do not treat the expected row count as a measured execution result. The count describes the generated data distribution; actual query timings and plan choices must be obtained from the PostgreSQL instance running the experiment.
Establish a Baseline Before Indexing
Before creating any secondary indexes, measure a representative query. Start with a lookup for one customer and return the customer's recent orders. This combines a selective equality predicate with an ordering requirement. The LIMIT clause is useful because it reflects a common application pattern: retrieve the most recent few records rather than every matching row. It also creates an opportunity for a composite index to support both filtering and ordering later in the experiment. The important rule is to keep the query identical when comparing the baseline and indexed versions. If the selected columns, filter conditions, sort order, or limit change between runs, the measurements no longer isolate the effect of the index.
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT
order_id,
customer_id,
status,
created_at,
total_amount
FROM orders
WHERE customer_id = 4200
ORDER BY created_at DESC
LIMIT 20;Run the query several times and save the plans. Record the scan type, estimated rows, actual rows, buffer activity, and execution time. Do not assume that the planner must select a sequential scan simply because there is no index on customerid: the primary-key index exists, and the planner is free to consider any useful access path. However, for this predicate, a sequential scan is a likely baseline plan because no suitable index begins with the customer identifier. The plan selected depends on the PostgreSQL version, statistics, machine resources, cache state, and other settings. Your output is the evidence for your environment; it should not be replaced with a made-up example claiming a particular number of milliseconds. The ORDER BY createdat DESC LIMIT 20 requirement matters too. Without an appropriate index, PostgreSQL may need to examine matching rows and perform a sort or top-N operation to find the most recent results. A plan can contain multiple operations, so the cost of a query is not explained by its table scan alone.
How to Read EXPLAIN ANALYZE
EXPLAIN asks PostgreSQL to display the execution plan selected by the query planner. Adding ANALYZE executes the query and includes actual execution statistics. Adding BUFFERS provides information about database pages accessed during execution. Together, these options are among the most useful tools for investigating query performance. PostgreSQL +1 The output is a tree. Lower nodes perform scans or produce rows; higher nodes combine, sort, aggregate, or otherwise process those rows. To understand the query, read the plan from the leaves upward. A sequential scan at the bottom may feed a filter or sort node, while an index scan may feed a limit or join operation. The planner's cost values are estimates expressed in PostgreSQL's internal cost units, not milliseconds. The first value indicates estimated startup cost, and the second represents estimated total cost. These estimates help the planner compare alternatives. They should not be interpreted as direct predictions of wall-clock time. By contrast, actual time reports measured execution timing for plan nodes when timing is enabled. rows describes rows emitted by a node, and loops describes how often it ran. For nodes executed repeatedly, the reported row and time figures require careful interpretation because the output may show averages per loop. The plan also reports planning time and total execution time. Execution time is not a complete measure of application response time: ordinary EXPLAIN ANALYZE does not include the time required to transfer the result set over the network to the client, and instrumentation itself can introduce overhead.
| Field | Meaning | How to use it |
|---|---|---|
| Seq Scan | Reads the table's heap sequentially | Determine whether scanning the table is reasonable for the query. |
| Index Scan | Uses an index to find candidate tuples and may fetch heap rows | Check whether the index matches the filter and whether heap access remains expensive. |
| Bitmap Heap Scan | Fetches heap rows using a bitmap of tuple locations | Useful when matching multiple rows where direct random heap access may be inefficient. |
| Index Only Scan | Can obtain required values from the index when visibility conditions allow | Check the columns needed and the reported heap fetches. |
| cost | Planner-estimated cost units | Compare plan alternatives; do not interpret as milliseconds. |
| actual time | Measured execution time for a node | Compare repeated runs with attention to loops and instrumentation. |
| rows | Estimated or actual rows emitted by a node | Investigate major differences between estimated and actual cardinality. |
| Buffers | Shared, local, and temporary block activity | Examine page access patterns and cache behavior. |
| Planning Time | Time spent planning the statement | Useful for understanding planning overhead separately. |
| Execution Time | Time spent executing the statement under the reported instrumentation | Compare with equivalent executions, while accounting for measurement limits. |
One of the most revealing signals is a mismatch between estimated and actual rows. If PostgreSQL expects a condition to return ten rows but the operation actually returns tens of thousands, the planner's cost comparison may be based on a poor estimate. Out-of-date statistics, skewed distributions, and relationships between columns can all complicate cardinality estimates. The buffer statistics add another perspective. A shared buffer hit means a requested database page was already in PostgreSQL's shared buffer cache. A shared read means the page had to be brought into that cache. The word “read” in the plan does not necessarily prove that the storage device performed a physical disk read, because operating-system caching can also satisfy file reads. When comparing plans, look beyond the final execution time. A faster-looking result in one run might simply reflect a warmer cache. Compare scan types, rows processed, buffer activity, and repeated timing measurements together. The purpose is to understand why the plan changed, not just to collect a smaller number.
Add a B-tree Index and Measure Again
The first index targets the equality predicate on customerid. A B-tree is a natural choice because the query asks for rows with a particular integer value. The index can help PostgreSQL find that customer's orders without examining every row in the table. Create the index and refresh the table statistics. Then rerun the exact baseline query. PostgreSQL may choose an index scan or a bitmap-based plan, depending on its estimates and the environment. An index scan is not guaranteed: the planner still compares the estimated cost of available plans. This first experiment isolates filtering. The query also requests the newest records, but the index on customerid alone does not naturally provide all rows in descending created_at order within a customer. PostgreSQL may still need to sort the matching rows. A later composite index will address that additional requirement.
CREATE INDEX idx_orders_customer
ON orders (customer_id);
ANALYZE orders;EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT
order_id,
customer_id,
status,
created_at,
total_amount
FROM orders
WHERE customer_id = 4200
ORDER BY created_at DESC
LIMIT 20;Compare the new output with the baseline. Did the scan type change? How many rows did the scan examine, and how many did it return? Did the sort operation remain? Did buffer activity or execution time change across repeated runs? If the index is used, the plan should identify it by name. The Index Cond line indicates conditions used to navigate the index, while a separate Filter line indicates conditions applied after candidate rows have been obtained. These are not interchangeable: a condition used as an index condition can restrict the index traversal itself, whereas a filter can discard rows after the access method has produced them. Do not conclude that the index is useless if a single run is not faster. Cache state, timing noise, and measurement overhead can affect short queries. Equally, do not claim success merely because the plan mentions an index. A plan that retrieves a large number of heap rows through an index can be more expensive than a sequential scan. The next step is to test a composite index that matches both the equality filter and the ordering requirement.
Understand Selectivity: Why Some Indexes Help More Than Others
Selectivity describes how narrowly a condition identifies rows. A highly selective predicate matches a small fraction of a table; a low-selectivity predicate matches a large fraction. The distinction matters because an index is most useful when it reduces the amount of data that must be examined enough to justify its own access costs. In the synthetic dataset, a query for a particular customer typically matches about ten rows out of 500,000. That is highly selective. A query for status = 'completed', on the other hand, matches 55 percent of the table. Retrieving that many rows through an index may require many heap accesses and may be more expensive than scanning the table sequentially. Selectivity is not the same thing as the number of distinct values alone. A column can contain many distinct values but still be skewed, with some values appearing far more frequently than others. A customer who places thousands of orders behaves differently from a customer who places only one. PostgreSQL uses statistics to estimate these distributions, but estimates are not guarantees. The practical consequence is that an index should be evaluated against the actual predicate and expected workload. Indexing a status column might help a query that searches for a rare status, but might not help one that retrieves most completed orders. Even the same index can be useful for one parameter value and unhelpful for another.
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = 4200;
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE status = 'completed';Run these statements before and after adding an index on status, if you want to explore how selectivity influences the planner. Keep in mind that the primary-key index and customer index already exist by this stage, so this is no longer a comparison between a completely unindexed table and a table with one index. It is a comparison of different access paths within a progressively indexed dataset. The status query returns many rows and uses SELECT *, which asks PostgreSQL to retrieve every column. A conventional index on status would identify candidate tuple locations, but the database would still need to obtain the full records. The cost of those heap accesses can outweigh the benefit of navigating the index. To see why this matters, compare both the percentage of rows returned and the number of blocks touched. A plan that reads more rows or pages is not necessarily incorrect; it may be the cheapest way to satisfy the query. The planner is optimizing estimated work, not trying to maximize the number of indexes used.
Composite Indexes: Match the Query's Filter and Sort
A composite index, also called a multicolumn index, stores entries using more than one key column. It can be useful when queries repeatedly combine conditions on several columns. For the orders query, the most natural next candidate is an index on customerid and createdat DESC. The order of the columns matters. A B-tree on (customerid, createdat DESC) groups entries by customer and orders each customer's entries by descending creation time. For a query with an equality condition on customerid, PostgreSQL can navigate to the customer's range of entries and potentially read the newest orders first. A composite index is not simply the sum of two independent indexes. It encodes a particular ordering of keys, and that ordering determines which queries it can serve efficiently. A B-tree index on (customerid, createdat) is most effective when the query constrains the leading column. A query that filters only on createdat may not benefit from that index as much as it would from an index beginning with created_at. PostgreSQL can sometimes use skip-scan optimizations for multicolumn B-tree indexes, but that depends on the data distribution and the planner's cost estimates. The safe design principle is to build indexes around actual query patterns and verify their use rather than assuming any combination of indexed columns will work equally well. PostgreSQL
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC);
ANALYZE orders;EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT
order_id,
customer_id,
status,
created_at,
total_amount
FROM orders
WHERE customer_id = 4200
ORDER BY created_at DESC
LIMIT 20;Compare this plan with the plan produced by the customer-only index. If PostgreSQL uses the composite index, it may retrieve entries for the selected customer in the required order, avoiding or reducing a separate sorting step. Because the query includes columns that are not all stored in the index, PostgreSQL may still access the heap to retrieve the requested values. This example demonstrates why query shape matters. The query filters by customer, sorts by creation time, and returns a limited number of rows. An index designed for those operations can support more of the query than an index that supports only the filter. Do not create the composite index merely because it is technically possible. If the application rarely asks for recent orders by customer, the additional storage and write work might not justify it. If the customer-only index already supports other important queries, removing it also requires care: the composite index can serve queries constrained on its leading customer_id column, but it is not a universal substitute for every independent index.
| Index definition | Example query | Expected usefulness |
|---|---|---|
| (customerid, createdat DESC) | Customer equality plus recent-order sorting | Strong candidate for the main experiment query. |
| (createdat DESC, customerid) | Recent orders across all customers | Better aligned with time-first access patterns, though other factors still matter. |
| (status, created_at DESC) | Orders for a particular status sorted by date | Potentially useful depending on status selectivity and query frequency. |
| (customer_id, status) | Customer equality combined with status filtering | Useful for queries that constrain the leading customer column and often filter by status. |
| (created_at DESC) | Recent orders across customers | Candidate when date-driven retrieval is the primary workload. |
The table is a design guide, not a promise that each index will improve performance. An index on (customerid, createdat DESC) is ordered first by customer, so it can support the customer-specific query. An index on (createdat DESC, customerid) is organized around time first and is better aligned with some global recent-order queries. When multiple columns appear in a predicate, think about which conditions are equality constraints, which are range constraints, and whether the query requests a particular ordering. Equality constraints on leading B-tree columns are especially useful for restricting the portion of the index that needs to be scanned. The first column is not always the column with the most distinct values; it should be chosen to fit the workload and the index's intended access paths. A common mistake is to create an index for each filter column independently and assume the planner will always combine them optimally. PostgreSQL can combine indexes in some circumstances, including through bitmap scans, but combining separate indexes is not always equivalent in cost or ordering to having a well-designed composite index. Measure both approaches when the workload justifies the comparison.
Indexing Has a Cost: Measure Write Overhead
Every additional index introduces work when the indexed table changes. An insert may need to add entries to multiple indexes. An update to an indexed column may require index maintenance, and deleting rows also affects index entries and subsequent cleanup. Indexes consume disk space and can influence memory pressure because frequently accessed index pages compete for shared cache resources. This means read optimization is a workload trade-off. A database serving many repeated lookup queries and relatively few writes may benefit substantially from selected indexes. A high-ingest workload with frequent inserts and updates may be more sensitive to excessive indexing. The cost is not always proportional to the number of indexes alone. Index size, key width, page splits, the columns being changed, and the workload's concurrency all influence maintenance overhead. A wide composite index can be more expensive to maintain than a narrow index. Indexing a column that changes frequently may be particularly costly if those updates prevent PostgreSQL from using some optimizations. To investigate the trade-off, compare insert throughput in a controlled environment before and after adding secondary indexes. Keep the dataset and insertion procedure consistent, repeat the experiment, and avoid treating a single batch timing as a universal performance result.
EXPLAIN (ANALYZE, BUFFERS, WAL)
INSERT INTO orders (
customer_id,
status,
created_at,
total_amount,
reference_code
)
SELECT
1 + ((g * 37) % 50000)::INTEGER,
'completed',
TIMESTAMPTZ '2026-01-01 00:00:00+00'
+ g * INTERVAL '1 second',
125.50,
'BENCH-' || LPAD(g::TEXT, 10, '0')
FROM generate_series(1, 10000) AS series(g);The example inserts 10,000 rows and requests execution statistics, buffer information, and WAL statistics. Run it once in a disposable database without the secondary indexes, reset the test conditions, then repeat with the selected indexes in place. Do not compare runs that differ in unrelated ways, such as different storage settings, a substantially different cache state, or a different transaction strategy. The WAL option provides information about write-ahead log generation when supported by the PostgreSQL version and execution context. WAL is important to durability and recovery, but generated WAL bytes alone do not capture every cost of maintaining an index. The complete comparison should include elapsed time, rows inserted, and any relevant resource metrics. Because the SQL modifies the table, running it repeatedly accumulates extra rows. For a clean experiment, recreate the test table or restore the same baseline between trials. Alternatively, prepare separate copies of the dataset for each condition. Avoid running the insert benchmark inside a long transaction that changes the intended durability behavior without explicitly documenting that choice.
Avoid Misleading Performance Benchmarks
A benchmark can produce numbers without producing reliable knowledge. Query execution time is affected by data volume, memory, storage, concurrent activity, operating-system caching, PostgreSQL's shared buffer cache, and planner statistics. A query executed immediately after a previous run may benefit from cached pages and therefore appear faster than the same query on a cold system. Use repeated runs and report the distribution rather than highlighting the best result. Median execution time is often more informative than a single minimum because it reduces the influence of unusually fast runs. For larger or more variable workloads, examine the range or percentiles as well. Do not delete slow observations simply because they weaken the result. Keep the SQL identical between conditions. Use the same selected columns, predicates, ordering, and limit. Ensure the dataset has the same size and distribution, and run ANALYZE after meaningful changes. If a query's plan differs after a statistics refresh, inspect the estimates and explain why the plan may have changed. Finally, distinguish a microbenchmark from application performance. EXPLAIN ANALYZE measures database execution with instrumentation, but does not by itself measure network transfer, application processing, connection-pool waits, or the user-perceived latency of an entire request. A query that looks fast in isolation may still be part of a slow endpoint for reasons outside the query plan.
ANALYZE orders;
EXPLAIN (
ANALYZE,
BUFFERS,
VERBOSE,
SETTINGS
)
SELECT
order_id,
status,
created_at,
total_amount
FROM orders
WHERE customer_id = 4200
ORDER BY created_at DESC
LIMIT 20;Save the full plan from each configuration. A small results table can record the index configuration, scan type, actual rows, buffer activity, execution time, and whether the sort operation remains. Keep the original plans so you can revisit a conclusion if later tests reveal that cache state or statistics influenced the first comparison. The SETTINGS option reports relevant planner settings that differ from built-in defaults. This can help explain why two PostgreSQL environments choose different plans. Do not disable sequential scans simply to force the desired result and then present that plan as proof that the index is beneficial. Forcing an access path can be useful as a diagnostic experiment, but the normal planner's choice is itself important evidence. A useful benchmark does not need to produce a dramatic speedup. It needs to show what happened, under what conditions, and why. If the index does not help the measured workload, that is a valid result. The next step is to investigate whether the query is too broad, the table is too small, the index is poorly ordered, or the planner is making a reasonable choice.
A Practical Framework for Choosing Indexes
Index design should begin with workload evidence, not with a list of columns that seem important. Start by identifying the queries that run frequently or consume a disproportionate amount of time. Inspect their filters, joins, ordering requirements, selected columns, and typical result sizes. Next, determine whether the current plan is spending unnecessary effort locating rows, sorting them, or fetching large amounts of data. An index may address one of these costs but not the others. For example, a customer-only index may reduce the rows examined but leave a sort step in place. A composite index that includes the timestamp in the appropriate order may address both operations for a specific query pattern. Then consider selectivity and data distribution. A condition matching a tiny fraction of the table is often a better candidate for index access than a condition matching most of the rows. But selectivity is only one factor. A query that can be satisfied from an index alone, or that needs a particular ordering, may benefit even when the result set is not extremely small. The actual plan and workload determine the outcome. Finally, measure the costs introduced by the new index. Consider storage, insert and update overhead, maintenance, and overlap with existing indexes. An index that speeds up one rarely used report but slows every write may be a poor trade. An index that makes a critical query consistently cheaper across a high-volume workload may be worth the cost.
- Identify a real query whose performance matters.
- Record its current execution plan with EXPLAIN (ANALYZE, BUFFERS).
- Verify that table statistics are current.
- Estimate how selective the query's predicates are and how many rows it returns.
- Choose an index type and column order that fit the operators, filters, and sorting requirements.
- Create the candidate index in a test environment.
- Rerun the identical query and compare the plan, buffer activity, and repeated timing results.
- Measure relevant write overhead and storage growth.
- Check whether the index duplicates an existing access path or is rarely used.
- Retain the index only when the evidence supports its cost across the workload.
This framework prevents a common optimization mistake: treating an index as a universal fix for slow queries. If a query is slow because it joins enormous intermediate results, performs expensive computation, returns an unnecessarily large result set, or waits on locks, adding a B-tree index may not address the primary cause. Likewise, a table scan is not automatically a defect. For a query that returns a large percentage of a table, reading the table sequentially can be the correct strategy. The goal is not to eliminate sequential scans; it is to reduce total work for the workload that matters. When evaluating indexes over time, examine usage statistics and real application behavior as well as individual plans. A candidate index that appears unused during a short test may support a rare but important maintenance job. Before removing an index, consider query schedules, constraints, dependencies, and the operational consequences of losing that access path.
Conclusion: Optimize for the Workload, Not the Index Count
PostgreSQL indexes make it possible to locate rows without scanning every record, but their benefit depends on the query, data distribution, and execution plan. B-tree indexes are a strong default for equality and range conditions. Composite indexes can combine filtering and ordering when their column sequence matches the workload. Selectivity helps explain why a narrow lookup may benefit from an index while a broad query may be better served by a sequential scan. The most important habit is to measure before and after making a change. Build a dataset large enough to reveal meaningful differences, keep the query consistent, refresh statistics, inspect EXPLAIN ANALYZE, and compare buffer activity alongside execution time. Treat measured values as evidence from a particular environment, not universal performance promises. Indexes also have costs. They consume storage and add maintenance work to writes. A sensible design balances read performance against those costs and avoids redundant indexes that do not justify their overhead. A good database engineer does not ask only, “Can I index this column?” The more useful questions are: “Which query am I improving?”, “What does its current plan reveal?”, “How selective is its predicate?”, and “Does the improvement justify the additional cost?” Answer those questions with reproducible measurements, and index design becomes a disciplined engineering process rather than guesswork.
OPEN
Thoughts on the article.