Browse topics

Indexes

Version
19
Review
Draft

Summary#

An index lets PostgreSQL locate rows without reading the whole table, at the price of storage and extra work on writes. The default type is B-tree.

Syntax#

sql
CREATE [UNIQUE] INDEX [CONCURRENTLY] index_name
ON table_name (first_column, second_column DESC)
INCLUDE (payload_column);

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind. EXPLAIN (COSTS OFF) shows the chosen plan without estimates that vary. Plans depend on data and settings, so another database may choose differently.

sql
BEGIN;
SET LOCAL DateStyle = 'ISO, YMD';
SET LOCAL default_statistics_target = 1000;

CREATE TEMPORARY TABLE events (
    event_id   integer NOT NULL,
    account_id integer NOT NULL,
    created_on date NOT NULL,
    kind       text NOT NULL
);

INSERT INTO events
SELECT n,
       n % 1000,
       date '2026-01-01' + (n % 365),
       CASE WHEN n % 2 = 0 THEN 'read' ELSE 'write' END
FROM generate_series(1, 100000) AS g(n);

CREATE UNIQUE INDEX events_id_idx ON events (event_id);
CREATE INDEX events_account_date_idx
    ON events (account_id, created_on) INCLUDE (kind);
ANALYZE events;

SELECT c.relname AS index_name,
       i.indisunique AS is_unique,
       i.indnkeyatts AS key_columns,
       i.indnatts AS stored_columns
FROM pg_index AS i
JOIN pg_class AS c ON c.oid = i.indexrelid
WHERE i.indrelid = 'events'::regclass
ORDER BY c.relname;

EXPLAIN (COSTS OFF)
SELECT * FROM events WHERE event_id = 500;

-- Equality on the first column and a range on the second use one index.
EXPLAIN (COSTS OFF)
SELECT * FROM events
WHERE account_id = 42 AND created_on >= date '2026-06-01'
ORDER BY created_on;

ROLLBACK;

Expected output#

Text
index_name|is_unique|key_columns|stored_columns
events_account_date_idx|f|2|3
events_id_idx|t|1|1
(2 rows)
QUERY PLAN
Index Scan using events_id_idx on events
  Index Cond: (event_id = 500)
(2 rows)
QUERY PLAN
Sort
  Sort Key: created_on
  ->  Bitmap Heap Scan on events
        Recheck Cond: ((account_id = 42) AND (created_on >= '2026-06-01'::date))
        ->  Bitmap Index Scan on events_account_date_idx
              Index Cond: ((account_id = 42) AND (created_on >= '2026-06-01'::date))
(6 rows)

Common mistakes#

A plain CREATE INDEX blocks writes to the table while it builds. Run CREATE INDEX CONCURRENTLY outside a transaction block to allow writes. If a failed build leaves an invalid index, drop or rebuild it. Even an index-only scan may visit the table to verify row visibility.

Version applicability#

INCLUDE requires PostgreSQL 11. Included columns are stored in the index but are not search keys and do not affect uniqueness. Basic indexes also work on earlier versions.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0