A customer searches for an order. The application asks a database for one record, and the response takes seconds. Someone suggests adding an index. That may help. But an index is not a switch labeled “make database fast,” and a proposed fix deserves a question before it gets a production change: which query is slow, and what is the database doing to answer it?
A database index is a separate data structure that helps the database find rows matching certain conditions without necessarily examining every row in a table. The benefit depends on the query and the data; the structure also uses storage and can add work when data changes. PostgreSQL’s index documentation describes both faster retrieval and the overhead. Other database systems have their own index types, optimizers and operating rules.
Start with the request, not the hardware
Suppose a fictional retailer’s orders table contains two million rows. A support tool often requests orders for one customer, sorted by creation time. The team expects roughly 40 matching orders for a typical customer. Without a suitable access path, a database might need to inspect far more of the table to find them. An index on a relevant field can give it another way to locate candidates.
This is an illustration of a choice, not a prediction of what any particular database will do. A query can be slow for reasons outside the lookup: a network wait, a lock, an expensive join, a large result sent to the browser, insufficient memory or a competing workload. Capture the exact query, parameters where appropriate, timing and circumstances. Protect customer data when retaining examples.
“The order page is slow” is a symptom. “This query spends most of its measured execution time scanning this table under representative load” is a more useful starting point. The evidence may point to an index, a query change, a different data model or a problem elsewhere.
The lookup and the table are separate pieces
Imagine an alphabetical directory. It provides a route to a record, but the details may live elsewhere. In a database, an index contains keys and information that can help locate corresponding rows; the exact structure and lookup process vary by database and index type. PostgreSQL supports several index types, each suited to different classes of operations. Its index type guide describes B-tree, hash, GiST, SP-GiST, GIN and BRIN, rather than suggesting one structure is best for every search.
A B-tree index is a common choice for equality and range conditions in PostgreSQL. That does not mean it automatically helps every condition involving that column. The query’s operators, data distribution, index definition and planner’s estimates all influence the path chosen. A search over almost every row can favor a sequential scan even when an index exists.
Do not confuse the number of entries in an index with the amount of work actually saved. If a query returns most of a table, fetching many separate rows through an index can be less attractive than reading the table in order. Conversely, a selective condition may let the engine avoid examining a great many irrelevant rows. Both possibilities need measurement on the actual workload.
Column order is a design choice
Suppose the frequent request is “find orders for this customer between two dates.” A multicolumn index might include customer ID and order date. In PostgreSQL, the multicolumn index documentation explains that a B-tree index is most effective at limiting the scanned portion with equality constraints on leading columns followed by an inequality on the first column without an equality constraint. Later-column conditions and newer skip-scan behavior can also matter; exact planner behavior is version- and workload-dependent.
That distinction is why “these are both indexed” is not enough information. An index beginning with customer ID followed by date is organized differently from one beginning with date followed by customer ID. One may fit a customer-specific time range better, while the other may be useful for a report covering a short date range across many customers. Neither is automatically superior for every query.
Write down the actual filters, joins and sort requirements before choosing an order. Consider whether a condition is always present, how many rows it selects and whether the query asks for a small result or a large export. Then inspect the plan and measure. Avoid designing the index from a hypothetical query that the application does not actually run.
The costs arrive on writes, too
When rows are inserted, deleted or changed, relevant indexes may also need maintenance. More indexes can consume storage, add write work and increase operational complexity. PostgreSQL’s introduction notes that indexes impose overhead and should be created sensibly. The size and effect depend on the index, update pattern, hardware, concurrency and database implementation.
Imagine a test in which an order lookup falls from an average of 800 milliseconds to 200 milliseconds after an index is added. The difference is 600 milliseconds, or a 75% reduction in that measured average: 600 divided by 800. In the same fictional test, a representative write operation rises from 20 milliseconds to 25 milliseconds, a 25% increase. Both can be true at once.
Those numbers do not establish that the change is good or bad. How often is each operation performed? Are the tests comparable? What happens at busy times, and what are the high-percentile delays? Does the index consume meaningful storage or cause maintenance pressure? An average alone can hide a few very slow requests, and a quiet test can miss contention that appears when the system is busy.
Read a plan without turning it into a verdict
PostgreSQL’s EXPLAIN documentation shows how to inspect the plan selected for a query. A plan describes operations and estimates, including estimated rows and costs. With suitable precautions, an actual execution plan can also reveal observed behavior. Estimated cost is a planner comparison measure; it is not a bill in dollars or a guaranteed number of milliseconds.
Compare estimated rows with actual rows where the tools and environment permit. Large differences can indicate stale statistics, a difficult estimate or other conditions worth investigating. Look at the whole path: an efficient index lookup followed by an unexpectedly large join may still produce a slow result. A query can use an index and remain slow, just as a sequential scan can be a sensible choice.
Be careful with measurement commands. PostgreSQL explains that EXPLAIN ANALYZE actually executes the statement. That matters for commands that change data and for production workloads. Use a safe environment, appropriate permissions and the database team’s procedures; avoid running an unreviewed expensive query simply to obtain a screenshot of a plan.
A realistic test needs realistic data
Test with representative table size, data distribution, query parameters and concurrency. A query for a customer with three orders can behave differently from a query for a large customer with hundreds of thousands. A tiny test table may fit entirely in memory and produce a plan unlike the production table. Warm caches and cold caches can also change results.
Compare the same query and output before and after the change. Record the database version, index definition, measurement window and whether other work was running. Look at latency distribution, resource use, write impact and index size. Repeat enough to understand variation without treating a small experiment as proof of every future condition.
Also test the queries that might lose. An index built for a report could slow a busy import or add cost to an order-update workflow. The people requesting a faster screen and the people responsible for transaction processing may be looking at different parts of the same tradeoff.
Production changes need a plan
Creating an index can require significant time and resources. In PostgreSQL, the documentation describes CREATE INDEX and concurrent builds, including restrictions and failure cases. A concurrent build has different locking behavior, but it is not free of cost or risk. The correct procedure depends on the version, table, workload and team’s operational requirements.
Agree on a maintenance window or low-impact method, expected resource budget, progress monitoring and a rollback or cleanup plan. Know who will decide whether the result meets the objective. An interrupted or failed operation may leave an artifact that requires investigation; do not assume a failed command means nothing changed.
After deployment, compare observed application behavior with the original baseline. A faster query in a plan is useful evidence, but the user’s page also depends on application logic, other queries and the network. Monitor the broader service and document any changed assumptions.
Questions before adding another index
- Which exact query and parameters are causing a meaningful delay?
- What do the current plan and representative measurements show?
- Which filters, joins and ordering does the proposed index support?
- How selective are those conditions for both typical and unusually large customers?
- What storage, write, maintenance and deployment costs might the index add?
- How will the team measure the result and safely reverse or revise the change?
The best index is not the one with the most impressive name. It is the one that earns its maintenance cost by improving a real workload—and continues to do so after the data and application change.
Explore Infinite Upside
For Vijay Sheth’s personal accounts, read Infinite Upside: Building Wealth With Room to Live, published by Sheth Capital, Inc.
Explore a related guide
Books about software architecture and tradeoffs