Choosing PostgreSQL index types: B-tree, GIN, GiST and BRIN

Pick a PostgreSQL index type from the query shape, table size and write pattern, then test it, measure it and remove the indexes nothing uses. This page covers each type's fit, trade-offs and the checks to run before and after a change.

On this page

Which PostgreSQL index type fits your query pattern?

Match the index type to the operator and data type in the query, and use B-tree unless you have a specific reason not to. Filters that compare a column with equality or a range, sort results, or enforce uniqueness are the common case, and a B-tree index handles them for most scalar columns. The other index types exist for shapes B-tree does not serve well: GIN for jsonb containment and full-text search, GiST and SP-GiST for ranges, geometry and nearest-neighbor style lookups, and BRIN for very large tables whose rows are physically ordered by a column such as an insert timestamp. Start from the WHERE clauses and ORDER BY of your slowest statements, not from a list of index types.

The right choice depends on three things: the operators your queries use, the size and physical order of the table, and how heavily the table is written. Every index adds work to inserts, updates and deletes, and each index type has a different maintenance cost and size profile, so a query that is slow on a growing table is not automatically solved by adding an index. Before you choose, confirm which operators each index type supports for your data type in the documentation for the PostgreSQL version you run, because operator classes differ between index methods and between releases. The PostgreSQL high availability and replication docs cover the server side of this, but the index reference in the version-specific manual is the authority for what each method can do.

PostgreSQL index types and the queries each one serves

This table compares the five index types PostgreSQL offers for common data types and operators, with the strengths and costs of each. Read it by starting from your query pattern, then check the index documentation for your PostgreSQL version, because supported operators differ by index type and release.

Index typeTypical data types and operatorsGood atMain costWhen it fits
B-tree (default)Scalar types such as integer, text, date and timestamp with equality and range operators, and orderingEquality, range filters, sorting and unique constraintsFull index on every indexed row, with write overhead on each insert and updateDefault choice for primary keys, foreign keys and most filtered or sorted columns
GINjsonb, arrays, tsvector for full-text search, and trigram-based text matching through extensionsContainment and membership queries over many keys inside one valueSlower writes and larger size, with more maintenance work on frequently updated rowsjsonb containment, array overlap and full-text search over mostly stable documents
GiSTRange and geometric types, and some full-text and extension-defined types such as those for geospatial dataOverlap, containment and nearest-neighbor style queries on ranges and shapesCan be larger and slower to build than B-tree, and results depend on operator class designRange exclusion constraints, overlap queries on time periods and geometric lookups
SP-GiSTPartitionable structures such as text prefixes, points and some range shapesPrefix and space-partitioned searches where data clusters unevenlyFewer operators and more specialized behavior than GiST or B-treePrefix searches on text or point data where the data distribution suits a space-partitioned tree
BRINLarge tables where values correlate with physical row order, such as timestamps or sequence IDsVery small index size on huge append-only tables with range filtersOnly useful when physical order matches the column, and returns candidate blocks that must be recheckedTime-series or log tables that grow in order and are queried by ranges over that column
Partial and covering indexesAny indexable type, with a WHERE clause or extra INCLUDE columns on B-treeIndexing only the rows a query needs, or allowing index-only scansEach variant must match the query predicate exactly, and extra columns increase index sizeQueries that always filter on a status or flag, or always read a fixed set of columns

Access patterns that call for a specialized index

B-tree handles most equality and range predicates on scalar columns, so the question is when a query's operator or data shape falls outside what it can answer efficiently. The five patterns below each change which index type fits, and each needs a check on data size and physical ordering before you commit to one.

jsonb containment and key lookups

Queries such as @> containment or ? key existence on a jsonb column cannot use a B-tree on the whole document in a useful way, because B-tree orders values rather than matching the keys inside them. A GIN index on the jsonb column indexes the keys and values, which suits containment filters. Confirm which operators your application actually uses, how many distinct keys exist, and whether a B-tree on one extracted expression already covers the hot path.

Replication docs

Full-text search over documents

Matching a tsvector against a tsquery with @@ asks whether a document contains words, not whether it sorts between two values, so a B-tree offers no help for it. A GIN index on the tsvector expression is the usual choice because it stores each lexeme and its matching rows. Confirm how often documents change, since frequent updates make GIN writes costlier, and how large the text column is relative to available memory.

Range overlap and containment

Predicates such as && on ranges or periods ask whether two intervals overlap, which a B-tree on the start column cannot answer without scanning many rows. A GiST index on a range type handles overlap and containment directly. Confirm which operators the queries use, whether the range column is sometimes null, and whether exclusion constraints on the same column are needed to prevent double bookings.

Geometric and nearest-neighbor queries

Spatial containment, bounding box tests and distance ordering with the <-> operator need an index that partitions space, which B-tree does not do. GiST supports these operators for geometry types and SP-GiST suits some partitioned data such as points and prefixes. Confirm the operators in your queries, the coordinate system and any extension that supplies the types, and how many rows a typical nearest-neighbor search must return.

Very large append-only tables

When a table grows by appending rows in roughly time or ID order and queries filter on that column, a B-tree can be large and slow to maintain relative to the value it adds. A BRIN index stores summaries per block range and works only while the physical row order tracks the column value. Confirm the table size, the physical correlation of the column with row position in pg_stats, and whether updates or deletes or a later bulk load would break that ordering.

How to choose an index type from the query

Start at the query's operator and the column's data type, then follow the branch that matches. Equality and ordering on ordinary columns lead to B-tree. Containment and full-text searches on jsonb or text lead to GIN. Range overlap and geometry lead to GiST or SP-GiST. Very large, naturally ordered append-only tables lead to BRIN. Every choice ends in the same check: run EXPLAIN on the real query, and drop the index if the planner never uses it.

Decision path from query operator to index choice and plan check.

When partial and covering indexes pay off in PostgreSQL

A partial index pays off when queries reliably filter on the same narrow slice of a table, such as rows where status = 'unprocessed' or archived_at IS NULL. You create it with a WHERE clause, and PostgreSQL stores entries only for rows that match the predicate. For a queue-like table where most rows are finished and only a small share are active, the index stays small, is cheaper to keep current on every write, and fits in memory more easily than a full index on the same column. The main constraint is matching: the planner uses the partial index only when it can prove the query's conditions imply the index predicate. A query that filters on status = 'processing' will not use an index written for status = 'unprocessed', and parameterized predicates can be hard to prove at plan time. Check this with EXPLAIN on your own data, and confirm the application sends the predicate literally in the form the index expects.

A covering index adds non-key columns with the INCLUDE clause, so a query that needs only indexed columns can be answered from the index without visiting the table heap. This is an index-only scan, and it works only when the visibility map marks the relevant heap pages as all-visible. Those bits are set by VACUUM, so a write-heavy table that vacuum does not keep up with will show frequent heap fetches even though the index contains every column. Included columns are not searchable, and they add index size and write cost on every insert and on updates that touch them, so include only the columns a hot query returns. Before adopting one, compare EXPLAIN (ANALYZE, BUFFERS) output for the query, look at the heap fetch count, and confirm that autovacuum keeps up with the table's change rate.

Treat both index types as hypotheses until the plan confirms them. Run the query before and after creating the index, on a copy of production-sized data if you can, and check that the plan actually chooses the index. Record the index size and the write-path cost for the table, since these are the recurring costs a partial or covering index adds. If the workload changes, for example when the status value that defines the active slice changes, the index can silently stop being used, so include it in your review of unused indexes. Confirm the exact behavior of each setting and version on the PostgreSQL documentation for your release before relying on it.

How to test a new PostgreSQL index before production

This sequence checks that a candidate index speeds up the real slow query, costs an acceptable amount of write time, and is actually used once it reaches production traffic. Each step ends with a check that decides whether the index stays.

  1. Capture the slow query and its current plan

    Start by recording the exact query text, its parameter patterns and how often it runs, usually from pg_stat_statements or application logs. On a copy of the database with representative data volumes, run EXPLAIN (ANALYZE, BUFFERS) and save the plan, the actual runtime and the shared buffer counts. This is the baseline. The step is done when you have a saved plan that matches the production query, with the table sizes and row counts recorded beside it, so the later comparison is like for like.

  2. Confirm the index type matches the access pattern

    Before building anything, check that the predicate, operator and column type fit the index type you chose: B-tree for equality and range on scalar columns, GIN for jsonb containment and full-text, GiST or SP-GiST for ranges and geometry, BRIN for large append-only tables correlated with physical order. Write the operator class and any partial predicate into the test plan. The step is done when every query pattern the index must serve is listed, and a query that uses a different operator is either rewritten or marked as out of scope.

  3. Create the index concurrently on the copy

    Build the candidate index with CREATE INDEX CONCURRENTLY on the test copy first, then repeat the same statement on production when the table is in use, since a plain CREATE INDEX takes a lock that blocks writes for the build. Note the build time and the resulting index size. Concurrent builds can fail and leave an invalid index, so check pg_index for indisvalid = false. The step is done when the index exists and is marked valid. An invalid index must be dropped and rebuilt before anything else.

  4. Run ANALYZE and re-capture the plan

    Run ANALYZE on the table so the planner has current statistics that include the new index, then run the same EXPLAIN (ANALYZE, BUFFERS) statement you saved in the first step. Compare the plan shape, the estimated and actual row counts, the buffer reads and the runtime. If the planner still ignores the index, check whether the estimates are wrong before changing anything else. The step is done when the new plan uses the index and the buffer count and runtime move in the expected direction across several runs with warm and cold caches.

  5. Test that the index helps other queries and does not hurt them

    Run the wider set of queries that touch the same table, not only the target query, and compare their plans against the baseline. An index can attract the planner into a worse plan for a query that was never the target. Also check that the index serves the queries you designed it for under the same operators and parameter values. The step is done when no critical query regresses in plan or runtime, or each regression has been explained and accepted by the owner of that query.

  6. Measure write overhead on the affected table

    Replay a representative write workload against the copy with and without the candidate index, using the same test harness for both runs. Record insert, update and delete throughput and latency on the affected table, and note how much extra WAL the index generates. Heavier write paths, especially GIN indexes on frequently updated jsonb or text columns, can cost far more than the read gain. The step is done when the write cost is measured against an agreed limit that the database owner set before the test, and the index is kept only if the read benefit justifies it.

  7. Deploy and confirm the index is used in production

    Create the index on production with CONCURRENTLY, outside peak hours where your change process requires it, and verify it is valid. After a period of normal traffic, query pg_stat_user_indexes and check idx_scan for the new index. An index with zero scans after representative traffic is a candidate for removal, and the unused index review should follow. The step is done when idx_scan grows for the target queries and the slow query shows the planned improvement in production monitoring.

Keep, change or drop an existing index

An index with zero scans since statistics were last reset is a candidate for removal, not proof that it is unused. Query pg_stat_user_indexes and read idx_scan alongside stats_reset in pg_stat_database to learn how long the counter has been running. A reset a few days ago tells you little about monthly reports, quarter-end jobs or failover runbooks that only run occasionally.

  • Check the counter window: Confirm when statistics were last reset and whether the database has been restarted or upgraded in that period.
  • Read the right view: Use pg_stat_user_indexes for idx_scan and idx_tup_read, and check pg_index for indisunique before deciding anything.
  • Account for replicas: On a hot standby, scans run on the standby are counted there, so check each node that serves reads.
  • Review rare jobs: List batch, reporting and maintenance jobs that run outside normal hours and confirm their query patterns.
  • Drop only after a full cycle: Confirm the statistics cover a full business cycle, such as a month-end close, before dropping with DROP INDEX CONCURRENTLY.

Before removing anything, confirm with the application owners that the window of observation includes their busiest periods.

Security and data handling for indexed columns

An index is a second copy of the data it covers, and it inherits the access, retention and change rules of the table. The cards below cover what to review before an index reaches production, from data copies and policy interactions to privileges, catalog visibility, extensions and change records.

Indexed values are copies of data

A B-tree, GIN or GiST index stores the indexed values inside its own pages, so a column holding personal data also appears in index pages, WAL, base backups and any replica. Deleting or masking the source value does not remove the copy until the index is rebuilt or vacuumed. Ask which indexed columns hold personal, health or payment data, and confirm that backup retention and restore access cover the indexes as well as the tables.

Row-level security and index use

Row-level security policies filter rows at query time, but an index can still be used by a planner decision that the policy does not control. Functions in policy expressions that are not marked LEAKPROOF can also limit which indexes the planner may use. Test each policy-protected table with EXPLAIN as the restricted role, so you confirm both the plan and that no rows outside the policy are visible.

Locks and owner privileges

A plain CREATE INDEX blocks writes to the table for the whole build, while CREATE INDEX CONCURRENTLY allows writes but takes longer and cannot run inside a transaction block. Only the table owner or a role with sufficient privileges can create or drop an index. Confirm which role runs index changes in production, when the build window falls, and how a failed concurrent build is cleaned up.

Replication docs

Catalog visibility of index definitions

Index names, columns and expressions are recorded in system catalogs such as pg_indexes and pg_index, and roles with ordinary read access can often see them. Expression indexes can reveal business logic or the shape of sensitive data. Review which roles can query catalog views in production, and avoid putting sensitive values or identifiers into index names and expressions.

Vetting extension index types

Index access methods and operator classes from extensions, such as those for vector or full-text search, run code inside the database server and may have their own release and security history. Confirm the extension's source, license, supported PostgreSQL major versions and update path before installing it. Also check that the extension is installed by a trusted role and that its objects are reviewed like any other schema change.

Index changes in change control

Adding, dropping or rebuilding an index changes write cost, lock behavior and query plans, so it should go through the same review as a schema change. Record the definition, the reason, the expected query it serves, the rollback statement and the approver. Re-check the record after major upgrades, because planner behavior and index support can change between versions.

Upgrade docs

What buyers ask about PostgreSQL index work

What drives the cost of a PostgreSQL index review?

The main driver is how many tables, queries and workload patterns need to be examined, and how much evidence the team can provide. A review of a small schema with a handful of known slow queries is narrower than one covering dozens of tables, mixed OLTP and reporting traffic, and jsonb or full-text search columns. Cost components are the reviewer's time for analysis, time spent reading plans and query logs, testing candidate indexes on a copy, and writing the change list with rollback steps. Ask any partner for a quote that lists the tables in scope, the query sources used, whether testing happens on a test copy, and the number of rounds of retesting included. Most engagements are fixed-scope, so the written scope should set these boundaries before work starts.

Can our own team review PostgreSQL indexes without a partner?

Yes, many teams can, provided they have someone who can read EXPLAIN ANALYZE output, interpret pg_stat_statements data and understand how the B-tree, GIN, GiST and BRIN access methods behave. The work that is hardest to do in-house is usually testing changes safely: building indexes without blocking writes, measuring the effect across realistic query mixes, and checking that a new index does not slow inserts or updates on busy tables. A useful test is whether the team can name the queries each index serves and the write cost it adds. If that analysis is already routine internally, a partner adds less value than a second pair of eyes on a specific risk, such as a large jsonb workload or a migration from another database.

What does a partner need from us to start an index review?

A partner needs enough evidence to see how the database is actually used, not only how it is defined. The usual inputs are the schema with existing indexes and constraints, representative data volumes and growth patterns, query logs or pg_stat_statements output from a period that reflects normal and peak load, and the top slow or frequent queries with their plans. A test copy of the database is needed to measure candidate indexes without touching production. The team should also name change windows, the owner who approves index changes, and the PostgreSQL major version in use, since version differences affect planner behavior. Missing any of these usually widens the scope or delays the start, so confirm the list in writing before the review begins.

How long does a PostgreSQL index review take?

Duration depends mainly on table count, the number of distinct query patterns and how many candidate changes need testing. A review centered on a few hot tables with clear query logs takes far less time than one that must map access patterns across a large schema with mixed workloads. Other factors that extend the work include missing query logs, a test copy that does not reflect production data distribution, and the need to retest after each change. Ask for a timeline that separates analysis, testing, the change plan and the post-change check, because each stage can be scheduled independently. Any specific duration should come from the written scope for your environment rather than from a general estimate.

Do index changes require downtime?

Most index changes do not need a full outage, but they can block writes or consume significant resources if handled carelessly. Creating an index with a plain CREATE INDEX takes a lock that blocks writes to the table until the build finishes, while CREATE INDEX CONCURRENTLY avoids that block at the cost of a longer build and extra steps if it fails. Dropping an index also needs care, and it is safer to drop with DROP INDEX CONCURRENTLY on busy tables. Large tables and BRIN or GIN builds can add I/O load, so schedule them in change windows and confirm the disk and memory headroom first. Whether a specific change needs a window depends on table size, write rate and your replication setup, so test the exact statement on a copy.

How do we decide between an index review and a full performance audit?

Choose an index review when the problem is narrow: a known set of slow queries, a new feature that needs indexes, or a schema that has grown without anyone checking which indexes are used. Choose a full performance audit when the slowness has several possible causes, such as configuration, memory, connection handling, bloat and query design, and you need a prioritized fix list covering all of them. An index review is a subset of an audit, so a useful test is whether the fixes you expect are mostly index-related. If the first pass of analysis shows that the real problem lies in configuration or connection pooling, the scope can be widened in writing rather than assumed. Ask the partner to state which areas are covered and which are excluded before you sign.

Will removing unused indexes break anything?

It can, if an index is used by a query that runs rarely, such as a monthly report, a constraint check or an index that supports a unique or foreign key requirement. Usage statistics from a short window can make an index look unused when it is not. Before dropping anything, confirm the observation period covers business cycles, check for indexes that back constraints, and keep a tested rollback statement such as the original CREATE INDEX definition. Dropping indexes on a test copy and running the full query set is the most reliable check. Removing unused indexes also reduces write cost and storage, so the review should record both the benefit and the verification steps.

Limits to confirm for your PostgreSQL version and workload

Index choices depend on the operators your major version supports, the extensions you have installed, and how your tables change over time. The cards below list six points to confirm against the official PostgreSQL documentation and your own environment before you commit an index design to production.

Operator support per index type

Each index access method supports a different set of operators, and that set changes between major versions and with installed extensions. Confirm that your query predicates (equality, range, containment, overlap or distance) appear in the operator list for the access method you chose. A predicate with no matching operator falls back to a sequential scan, which the planner may choose without any error. Check the index operator tables in the current PostgreSQL documentation, then run EXPLAIN on your real queries against a copy of production data.

Index types docs

Extensions and operator classes

Some index types depend on operator classes that come from extensions, such as the trigram and vector operator classes used for fuzzy or similarity search. Verify with \dx in psql that the extension is installed in the database that holds the index, and check that the operator class named in CREATE INDEX exists there. Extension versions also matter, because an upgrade can change or remove operator classes. Record the extension version in your change records so that restores and standby builds pick up the same definitions.

Write volume and index bloat

Every insert, update and delete adds work to every index on the table, and updates that cannot use a HOT update also write new index entries. Index size grows between vacuum runs, and an index-only scan returns to the heap for any page whose visibility map bit is not set. Track how often autovacuum processes each table and whether the visibility map stays current for write-heavy tables. Measure index size over several weeks with pg_relation_size before deciding that an index is worth keeping on a busy table.

Replicas and standby index changes

Indexes are part of the physical data that streaming replication copies, so a hot standby has the same indexes as the primary and serves read-only queries that can use them. Index creation on the primary runs through WAL, and a standby receives the change, but a standby cannot create or drop indexes itself. Confirm that the standby's configuration and extensions match the primary, because a missing operator class can break queries that worked on the primary. Plan index builds on large tables with replication lag in mind.

High availability docs

Disk and memory budget

Large GIN, GiST and B-tree indexes can rival or exceed the table they cover, and index builds need temporary disk space and maintenance_work_mem while they run. Estimate the size of each index from a sample load, then add headroom for bloat, WAL generated by the build, and any backup copies. Ask whether your storage plan includes replica copies, and confirm that the frequently used indexes fit in the memory available for caching them. Your own storage and backup team should confirm these numbers, since DeployOpen cannot predict them without your data.

Limits of usage statistics

The pg_stat_user_indexes view counts index scans since the last statistics reset, so an index with zero scans may still be needed for a monthly report or a constraint check. Statistics reset on crash recovery in some cases, on explicit reset, and when you restore or promote a standby, so a short observation window can mislead. The view also does not show which queries used an index or whether an index is needed for a unique or foreign key constraint. Before dropping an index, check pg_index for constraint use and review query text from pg_stat_statements over a full business cycle.

How DeployOpen scopes index work on your PostgreSQL

DeployOpen approaches index selection as part of a wider review of your PostgreSQL workload, starting from the queries and tables that matter most to your teams. We scope the work in writing, build and test indexes against your real access patterns, and hand over the decisions, DDL and checks so your own engineers can maintain them after the engagement.

How we scope

  • We agree a written scope covering which tables, queries and workloads the index review includes.
  • We collect the slow query list, table sizes and current index definitions before proposing any change.
  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.

How we build

  • We match each access pattern to a B-tree, GIN, GiST, SP-GiST or BRIN index and record the reason.
  • We test candidate indexes on a copy of your data, checking plans with EXPLAIN ANALYZE and write overhead.
  • We identify unused and duplicate indexes and plan their removal in a controlled sequence.

How we hand over

  • You receive the index definitions, migration scripts and a rollback step for each change.
  • We document the access pattern behind every index so future teams can judge whether it still applies.
  • We walk your database engineers through the before and after measurements and the monitoring to keep.

How we support

  • Ongoing support, upgrades and continuous testing are available as a retainer after the handover.
  • A retainer can cover re-checking indexes after schema changes, PostgreSQL upgrades or new query patterns.
  • Ask us to confirm in the written scope which PostgreSQL versions and hosting environments are covered.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.