This guide was prepared with AI assistance using the linked documentation. Code examples are illustrative; verify them against your environment and current API documentation before use.
A catalog search works in development, then slows down as the table grows. A common response is to add a cache or an index immediately. Both can help, but neither tells you why the query is slow or whether the change protects the result your users need.
This guide starts with a representative query and a repeatable measurement. It then walks through PostgreSQL execution plans, composite and partial indexes, prefix and substring searches, pg_trgm, joins, pagination, query statistics, and a safe rollout. The SQL examples use synthetic catalog data. They illustrate a workflow; they are not measurements from your database or promises of a particular speedup.
Who this is for: developers and operators with SQL experience who want to diagnose an application query before choosing an optimization. The examples follow current PostgreSQL documentation; confirm features and defaults against the version you run. Practice in a disposable database, not on production data.
Start with the actual slow request
First identify one request the application makes and the result it needs. A product list may filter by category and active status, search a name, order by price, and return the first twenty rows. A report might aggregate a whole month. They can touch the same table but need different plans and indexes.
Capture the SQL shape, parameter types, typical and unusually expensive values, row counts, and the order of the result. Record whether the application makes one query or many. Include the complete sort and limit: removing either to simplify an example can change which plan PostgreSQL chooses. Replace private values with safe examples before sharing a query or a plan.
Establish the decision you need to make. If the page is slow only for one common search term, inspect that term. If the page makes 101 database calls to render 100 products, removing repeated calls may matter more than tuning one lookup. If the database query is fast but the page waits on another service, investigate that service before making a database migration.
Useful measurements include request duration, database duration, number of queries per request, rows returned, and a plan from representative data. Record the environment, PostgreSQL version, dataset scale, query parameters, concurrency, and timestamp. A single duration from a laptop is a clue, not a production benchmark.
Set up a safe example
The following table is intentionally small and synthetic. Use a scratch database and an account with permissions to create its own objects. The sample is useful for checking syntax and query shape; with only a few rows the planner will often choose a sequential scan because reading the whole table is cheaper than using an index.
CREATE TABLE catalog_demo (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
category_id integer NOT NULL,
name text NOT NULL,
status text NOT NULL CHECK (status IN ('active', 'draft')),
price numeric(12, 2) NOT NULL CHECK (price >= 0),
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO catalog_demo (category_id, name, status, price) VALUES
(10, 'Lime desk lamp', 'active', 49.00),
(10, 'LED desk light', 'active', 32.00),
(10, 'Draft floor lamp', 'draft', 79.00),
(20, 'Studio chair', 'active', 125.00);
ANALYZE catalog_demo;
SELECT id, name, price
FROM catalog_demo
WHERE category_id = 10 AND status = 'active'
ORDER BY price, id
LIMIT 20;The id tiebreaker makes ordering deterministic when multiple products have the same price. The example does not create millions of random rows or pretend that four rows reproduce a production distribution. For a meaningful benchmark, build a larger, synthetic dataset with the same kinds of skew and cardinality as the real workload, then document how it was produced.
Run ANALYZE after loading representative data so the planner has statistics. Statistics are estimates, not a guarantee that the planner knows every correlation. When the estimated number of rows differs greatly from the actual number, investigate the distribution and statistics as well as the index. See the PostgreSQL planner statistics guide.
Read a plan without treating it as a verdict
Start with a non-executing plan when you are not certain a statement is safe to run:
EXPLAIN
SELECT id, name, price
FROM catalog_demo
WHERE category_id = 10 AND status = 'active'
ORDER BY price, id
LIMIT 20;EXPLAIN displays the planner's chosen strategy and estimates. A plan is a tree: lower nodes read or produce data; upper nodes combine, filter, sort, or limit it. The estimated cost is a planner unit, not milliseconds. Compare actual elapsed time separately, and do not compare cost figures from unrelated plans as though they were a service-level objective.
For an appropriate read-only test in a safe environment, add actual execution and buffer information:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, name, price
FROM catalog_demo
WHERE category_id = 10 AND status = 'active'
ORDER BY price, id
LIMIT 20;ANALYZE executes the statement. It can put load on a system and, for statements that modify data, perform their effects. Even a SELECT can invoke a function with side effects. Use a staging environment and a representative safe query, or follow your organization's production-observation procedure. PostgreSQL's EXPLAIN reference explains the options and cautions.
Look at actual rows and loops, not only the top execution time. A node producing one row per loop over a large number of loops can still perform substantial work. Compare estimated rows with actual rows, inspect where filters discard rows, and identify expensive sorts or repeated scans. BUFFERS describes buffer activity; distinguish shared hits from reads and interpret both in context. A warm cache and a cold cache can produce very different timings.
Decide whether a sequential scan is actually a problem
A sequential scan is not automatically bad. Reading most of a small table in order may be cheaper than walking an index and fetching many scattered heap pages. If a filter returns a large fraction of a table, the same can be true for a larger table. The planner is choosing among estimated alternatives; your job is to determine whether the chosen plan performs acceptably for the real request.
Inspect the condition and the proportion of rows needed. A scan that reads a large table and discards nearly all rows for a highly selective query deserves attention. A scan over four demo rows does not justify an index by itself. Also check stale statistics and parameter differences before concluding that PostgreSQL ignored a useful index.
When testing a candidate, measure the original and changed query under comparable conditions. Repeat runs, record concurrency and cache state as far as practical, and look at a distribution rather than picking the best run. If the new index improves one query but substantially increases write latency or storage, include that tradeoff in the decision.
Design a composite index around the access pattern
For the catalog query above, a candidate index might begin with the equality filter and continue with the ordering columns:
CREATE INDEX catalog_demo_category_status_price_id_idx
ON catalog_demo (category_id, status, price, id);The idea is to make a matching range of rows available in the requested order, so the engine may avoid sorting a large intermediate result. Whether it does so depends on the predicate, selectivity, available statistics, table size, and planner estimates. Check the plan; do not assume the index will be used or will be faster.
Column order matters. A multicolumn B-tree can serve different predicates, but the usefulness of a leading equality constraint differs from a query that filters only a later column. An index built for category_id, status, and price order is not automatically the best index for a global name search. The multicolumn-index documentation describes how PostgreSQL applies constraints to index columns.
Adding name as an included column may allow an index-only scan for some workloads, but it makes the index larger and an index-only scan still depends on visibility information. Test with actual update patterns. Avoid including every selected field without measuring the added write and storage cost. See index-only scans.
Consider a partial index for a stable subset
If nearly every catalog request looks only at active products, a partial index can exclude drafts:
CREATE INDEX catalog_demo_active_category_price_id_idx
ON catalog_demo (category_id, price, id)
WHERE status = 'active';The planner can use a partial index when it can establish that the query predicate implies the index predicate. An application query written with a parameter for status, especially under a generic prepared plan, may not always give the planner enough information to make that deduction. Test the actual parameterized query and plan used by your application; do not assume a literal demo query proves the production query will use the index.
Partial indexes are most useful when the indexed subset and access pattern justify their complexity. If nearly all rows are active, the index may not save much space. If status changes frequently, updates still have maintenance costs. A second index should solve a measured need rather than duplicate an existing index with a different name. The official partial-index guide explains predicate matching and its limits.
LIKE patterns are different search problems
The shape of a pattern changes which indexing approach might help:
| Request | Example | Design question |
|---|---|---|
| Exact value | name = 'Lamp' | Does equality use the intended collation and case rules? |
| Prefix | name LIKE 'Lamp%' | Can the planner use a B-tree under the chosen collation and operator class? |
| Substring | name LIKE '%lamp%' | Would a trigram index help on representative terms? |
| Case-insensitive | name ILIKE '%lamp%' | What locale and case behavior do users expect? |
LIKE uses % for any sequence and _ for a single character. Decide whether a user's % and _ should be treated as wildcards or literal characters; parameterization prevents SQL injection, but it does not automatically escape pattern metacharacters. Follow PostgreSQL's pattern-matching documentation and make the product behavior explicit.
For a constant left-anchored prefix, a B-tree can be useful. Outside the C locale, a suitable pattern operator class may be needed; collation and the query's expression must match the index design. Test your exact database version and collation. A leading wildcard such as %lamp% is a different problem and generally cannot use an ordinary B-tree as a simple prefix range.
Test a prefix index with the real expression
For a text column and a compatible deterministic collation, one candidate is a B-tree pattern operator class:
CREATE INDEX catalog_demo_name_prefix_idx
ON catalog_demo (name text_pattern_ops);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, name
FROM catalog_demo
WHERE name LIKE 'Desk%';The query is case-sensitive. For a case-normalized prefix search, teams sometimes index lower(name) and apply the same expression in the predicate. Before doing so, agree on the desired language and collation semantics, and confirm how input is normalized. Case folding can be more complicated than converting ASCII letters. An expression index only helps when the query and index expressions align and the planner judges the access path worthwhile.
Never change the database's collation or a customer-facing search rule just to make a particular index appear in a plan. First define the correct result set; then evaluate options that preserve it. Use representative prefixes, including very common values that may match a large proportion of rows and rare values that match only a few.
Use pg_trgm for measured substring workloads
PostgreSQL's pg_trgm extension provides operator classes that can support LIKE, ILIKE, regular-expression and similarity searches. A typical candidate for substring search is a GIN trigram index:
-- Run only in a database where installing this extension is permitted.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX catalog_demo_name_trgm_idx
ON catalog_demo USING gin (name gin_trgm_ops);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, name
FROM catalog_demo
WHERE name ILIKE '%lamp%';This is a candidate, not a universal replacement for B-tree indexes or a promise that a short pattern will be fast. PostgreSQL extracts trigrams from the search pattern; patterns with no extractable trigrams can degenerate to a full-index scan. Very short or broad terms can still touch a large part of the index or table. Test common and rare terms, patterns with punctuation, and terms that match many rows. The pg_trgm reference describes GIN and GiST support and limitations.
GIN and GiST have different tradeoffs. The documentation notes that some nearest-neighbor distance orderings can be implemented efficiently by GiST, whereas GIN is not suitable for that same ordering. Do not choose by a generic benchmark alone. Measure your read pattern, write rate, index size, latency distribution, and maintenance behavior on a production-like dataset.
If the user wants linguistic word search, stemming, ranking, or multiple languages, investigate PostgreSQL full-text search as a separate design. A trigram substring index and a full-text search index answer different questions. Replacing one with the other can change which results users see.
Keep patterns safe and predictable
Use parameters for user input. Do not concatenate a raw string into SQL. For a literal substring search, escape the escape character itself, %, and _, then add the outer wildcards. The exact syntax depends on your language, database driver, and SQL string settings, so unit-test the helper with your actual driver.
// Example for a driver that binds $1 as text. Test with your driver and locale.
function literalLikePattern(value: string): string {
return `%${value.replace(/[\\%_]/g, "\\$&")}%`;
}
const pattern = literalLikePattern(userSearch);
// Pass `pattern` as a bound parameter, never interpolate it into SQL:
// SELECT id, name FROM catalog_demo WHERE name ILIKE $1 ESCAPE E'\\';An input such as 50% should search for the percent sign if that is the product's intended behavior. An input with a backslash needs its own test, and an empty or extremely short input needs an explicit policy. Decide whether to reject it, show a bounded recent list, or require another filter. Returning an entire large table for every keystroke can overload the service even when the SQL is parameterized.
Apply request-size limits and appropriate rate controls to public search endpoints. Restrict which columns and records a caller may search before the query is executed. An efficient index cannot repair missing tenant authorization or a query that exposes another customer's records.
Check the query your ORM really sends
ORM code can conceal several queries behind an apparently simple call. Capture SQL using your framework's supported diagnostic tools, taking care to redact private values. Compare the generated predicate, selected columns, joins, sort, and limit with the query you intended to optimize. An index for lower(name) will not automatically help if the ORM sends a different expression.
Look for the N+1 pattern: one query obtains a list, then another query runs for each row. Count queries per request and inspect their timing. Depending on the relationship and workload, a join, batched lookup, aggregate, or a carefully selected relation load may reduce round trips. The best choice depends on data volume and how the ORM generates SQL; test the resulting query rather than assuming a particular API always joins or always batches.
Select only the columns the page needs. Large text or binary fields can increase network transfer and memory pressure even when the plan finds rows quickly. But avoid premature micro-optimization: first establish which stage consumes the request's time, including serialization and downstream calls.
Diagnose joins and row estimates
A join can be slow because the input is much larger than expected, because a join key lacks a useful index, or because the data distribution differs from the planner's estimate. Inspect the plan from the bottom up. Which relation is read first? How many rows survive each filter? How many times does a nested-loop inner operation execute? Is a sort or hash operation spilling to disk?
The planner chooses among nested-loop, hash, and merge joins using estimates. None is universally superior. A nested loop can be excellent when the outer input is small and the inner lookup is indexed; it can be expensive if the outer input is much larger than estimated. A hash join may be useful for a larger equality join but needs memory and can batch when it does not fit. Read the nodes and actual rows in context rather than banning one join type.
If estimates are persistently wrong, check statistics freshness and whether columns are correlated. PostgreSQL supports extended statistics for selected relationships between columns, but choosing them requires understanding the workload. Measure whether a statistics change improves the plan before keeping it, and remember that statistics do not replace indexes or fix an incorrect query.
Make pagination stable and affordable
OFFSET is convenient, but a deep page can require the database to find and discard many earlier rows. For a large ordered catalog, consider keyset pagination using the last (price, id) pair from the previous page:
SELECT id, name, price
FROM catalog_demo
WHERE category_id = $1
AND status = 'active'
AND (price, id) > ($2, $3)
ORDER BY price, id
LIMIT 20;The cursor values must match the sort order and data types. If users can change the sort, use a cursor format for each supported ordering. Null values, descending order, and mutable prices need deliberate handling; this example uses a non-null ascending price and an ID tiebreaker. A cursor is not proof that a user is authorized to view a category or tenant.
Keyset pagination improves the work needed to continue from a known position in suitable indexes, but it changes product behavior. Jumping directly to page 100 or showing an exact page count may require a different design. Rows can also change between requests. Decide what consistency the product needs and explain it to the team before replacing an existing pagination contract.
Measure with pg_stat_statements when available
pg_stat_statements can help identify frequently executed and expensive statement shapes across a workload. It requires setup and configuration appropriate to the server, and access to its data should be controlled. Check your managed provider's instructions and the PostgreSQL reference before enabling it.
Use the statistics to ask which query families consume total time, which have high mean or maximum duration, and how often they execute. A moderately slow query called thousands of times can matter more than a rare slow administrative report. Conversely, an average can hide a severe tail for a particular customer or parameter value. Combine aggregate statistics with application traces and carefully collected representative plans.
Record the observation window and whether counters were reset. Do not compare a fresh interval with a month of accumulated data as though they were equivalent. Protect query text and application traces: they can reveal table names, business logic, or private values depending on logging configuration. Use synthetic examples in public reports.
Understand prepared statements and parameter sensitivity
A query plan that works for a rare category may be poor for a category containing most of the table. PostgreSQL can use custom or generic plans for prepared statements under documented rules. A generic plan avoids repeated planning but cannot specialize to every parameter value. Inspect the plans used by your actual application and test a range of representative parameters.
Do not disable prepared statements globally as a first reaction. The cause may be stale statistics, a query shape, an inappropriate index, or a genuinely different workload. Compare alternatives on a staging dataset with the same driver behavior, and account for planning overhead as well as execution time. PostgreSQL's PREPARE documentation explains generic and custom plans.
The same caution applies to optional filters expressed as broad OR conditions. A single query intended to support every combination can be harder to optimize than a small number of deliberate query shapes. Change the application only after verifying that the new shapes preserve authorization, result ordering, and parameter binding.
Roll out an index as an operational change
An index consumes disk and must be maintained as rows are inserted, updated, or deleted. Before adding one, check available space, write volume, replication behavior, the migration process, and any existing indexes that cover the same access pattern. Estimate the impact in a representative environment and coordinate with the database owner.
For a live table, PostgreSQL supports CREATE INDEX CONCURRENTLY to reduce blocking of writes, with important caveats: it cannot run inside a transaction block, takes additional work, and a failed build can leave an invalid index requiring investigation. Managed platforms and migration tools may add constraints. Read the CREATE INDEX documentation and your provider's guidance before applying a migration.
Plan how to verify the index, how to monitor query and write latency, and how to roll back if the result is worse. Do not drop an existing index simply because a new one exists; other queries or constraints may rely on it. Review usage over a meaningful workload window and consider infrequent but important jobs before removing anything.
Separate query time from time spent waiting
A query can be slow because it waits for a lock, a connection, disk activity, or another resource. An index change will not necessarily address the wait. Capture the timing boundaries in your application: when a request begins, when it receives a pooled connection, when the database call finishes, and when the response reaches the user. Use monotonic timers for durations within a process and a shared trace identifier to connect related observations.
Pool wait and query execution are different measurements. A request that waits for a connection may reach PostgreSQL after most of its time budget has already elapsed. Increasing the pool without checking database capacity can make contention worse. Review connection limits, transaction duration, idle connections, and the deployment topology with the person who operates the database.
Lock investigations need care. A maintenance operation or long transaction may delay otherwise simple work. Use the monitoring views and provider tooling appropriate to your version, restrict access to operational data, and establish an incident procedure before cancelling a query or terminating a session. A cancellation can have application consequences; it is not a diagnostic command to run casually.
Network distance and result size also matter. A plan can report a short database execution while a request transfers a large result across a slow connection and serializes it into a page. Measure rows and bytes when useful, and ensure the application consumes and releases connections promptly. Check the complete request before deciding that a database plan explains the user's experience.
Compare sorts, counts, and result fidelity
A product page may run a list query and a separate exact count. The list might be fast after an index change while the count still scans a broad set of matching rows. Measure both queries independently. If an exact count is expensive, discuss alternatives such as showing a next-page control or an explicitly approximate count. Such a change affects the interface and should not silently replace an exact business requirement.
Sort order can determine whether an index avoids additional work. A matching index may be useful for a filtered, ordered, limited query, but joins, expressions, direction, null handling, and collation can change what the planner can use. Keep the full ORDER BY in test queries, including a deterministic tiebreaker. Inspect whether the plan sorts many rows before applying the limit.
Before reporting a performance win, compare results as well as timing. Run the old and candidate query against a fixed synthetic dataset and compare identifiers, ordering, pagination boundaries, and behavior for empty searches. If a proposed rewrite returns fewer authorized records or changes case sensitivity, it is a product change even if it is faster. Correctness is a release criterion, not a footnote in the benchmark.
Keep a before-and-after record
A useful change record explains the question and the result without overclaiming. Record the query shape, parameter distribution, schema and index definitions, dataset size, PostgreSQL version, hardware or service tier, concurrency, and time window. Save sanitized plans and note whether runs used a warm or cold cache where that distinction was measured.
Compare p50 and tail latency where enough observations exist, as well as total database time, query count, error rate, rows returned, and relevant write performance. A plan improvement for a synthetic query is not evidence of a production improvement. After release, compare equivalent windows while considering traffic mix and other deployments. If the result is ambiguous, say so and keep measuring.
Use a rollback criterion agreed before deployment. For example, the team may choose to revert if write latency increases beyond an agreed threshold or the index consumes more space than planned. The actual threshold belongs to the system's owner; this tutorial does not invent one for your application.
Troubleshooting checklist
If a query is slow, work through the following questions in order:
- Is the request slow in the database, in another service, or during rendering and network transfer?
- Is the captured SQL the same query, parameter type, sort, and limit used by the application?
- Is there an N+1 pattern or unnecessary transfer of large columns?
- Are estimated and actual row counts far apart, and are statistics current?
- Does the query need equality, prefix, substring, or full-text semantics?
- Does a candidate index match the filter and ordering, and does it preserve correct results?
- Does the plan change for common and rare values or for a prepared statement?
- What is the index's cost in writes, storage, deployment time, and ongoing maintenance?
- Did the measured change improve representative latency and correctness under realistic concurrency?
- Can the team safely roll back and explain the decision to the next maintainer?
If you cannot answer the first question, start with instrumentation. If you cannot reproduce the result, record the uncertainty and gather a better test case rather than adding indexes at random.
Frequently asked questions
Does every slow query need an index?
No. The bottleneck may be repeated requests, a large result set, an inefficient join, a sort, lock contention, a downstream dependency, or stale estimates. An index is one candidate. Use the actual query and plan to decide whether it addresses the expensive work.
Why does PostgreSQL ignore an index?
The planner may estimate that a sequential scan is cheaper, the predicate may not match the index expression or partial predicate, the search term may be too broad, or statistics and parameter values may influence the estimate. Inspect the plan and test representative conditions. An unused index is not automatically a bug.
Can a normal B-tree make %term% fast?
An ordinary B-tree is suited to equality and certain ordered or left-anchored searches; a leading wildcard changes the access problem. pg_trgm can support substring searches, subject to pattern and workload limitations. Compare alternatives on your own data rather than assuming that one index is always beneficial.
Is EXPLAIN ANALYZE safe on production?
It runs the statement and adds measurement overhead. A write statement can change data, and a read can still be expensive or call functions with side effects. Follow a safe observation procedure and prefer staging when possible. Plain EXPLAIN does not execute the statement, but it reports estimates rather than actual timing.
Should I add a cache first?
Add a cache when it solves a measured problem and the team understands freshness, invalidation, authorization, and failure behavior. A cache can hide an inefficient query until a miss or invalidation spike. Measure the underlying path and define the acceptable staleness before adopting it.
Does a faster plan guarantee a faster page?
No. The page may wait on network calls, application processing, serialization, or a different query. Compare end-to-end user experience and database measurements, and keep correctness and error rates in the same experiment.
Sources and further reading
- PostgreSQL: Using EXPLAIN — plan nodes, estimates, actual execution, and buffers.
- PostgreSQL: Index types — B-tree and other index access methods.
- PostgreSQL: Multicolumn indexes — how column order and constraints affect an index.
- PostgreSQL: Partial indexes — predicates and planner matching.
- PostgreSQL: pg_trgm — trigram similarity and indexed pattern matching.
- PostgreSQL: Pattern matching —
LIKE,ILIKE, escape behavior, and collation considerations. - PostgreSQL: CREATE INDEX — index construction and concurrent-build caveats.
- PostgreSQL: pg_stat_statements — statement-level workload statistics.
Review the documentation for your PostgreSQL version and managed service before applying a change. The examples above have not been benchmarked against your database.
