Indexes
Indexes make a query read only the rows that can match instead of the whole table. RasterizedDB has two kinds: the B-tree, hash and GIN indexes you declare with CREATE INDEX, and a built-in filter index that covers every eligible column of every table without being declared. Use this page to decide what to declare, how to tune the filter index, and where indexes live in memory and on disk.
Every index answer is re-checked against the row, so an index never changes what a query returns, only how much it reads.
Indexes you get without asking
- Primary keys and unique constraints. Every
PRIMARY KEY, everyUNIQUEcolumn and every compositeUNIQUE (a, b)constraint gets a B-tree index over exactly its columns. Uniqueness checks and lookups by those keys use it, so an insert into a keyed table costs the same at a million rows as at a thousand. - The filter index. A compact bit-level index over the columns of every table with at least 4,096 rows. It prunes rows for equality,
IN, range,BETWEEN,LIKE 'prefix%'andIS [NOT] NULLpredicates. See The filter index.
Declare an index yourself when a query filters or joins on a column that is not a key and the filter index does not narrow it enough, for example a point lookup by a near-unique column, a range over a large table, or a path inside a JSON document.
CREATE INDEX
CREATE INDEX orders_customer ON orders (customer_id); -- method chosen for you
CREATE INDEX orders_placed ON orders USING btree (placed_at);
CREATE INDEX sessions_token ON sessions USING hash (token);
CREATE INDEX orders_cust_day ON orders (customer_id, placed_at); -- composite
CREATE INDEX IF NOT EXISTS ON orders (status); -- name derived: orders_status_idxFull form:
CREATE INDEX [CONCURRENTLY] [IF NOT EXISTS] [name] ON [ONLY] table
[USING btree | hash | gin] (column [ASC | DESC] [NULLS FIRST | LAST], ...)
[INCLUDE (...)] [WITH (...)] [TABLESPACE ...]- The name is optional. Without one the index is named
table_column1_column2_idx, as PostgreSQL names it. Index names are database-wide and at most 128 bytes. - An index covers at most 16 columns.
ASC/DESC,NULLS FIRST/LAST,COLLATE, a B-tree or hash operator class,INCLUDE,WITH,TABLESPACE,ONLYandCONCURRENTLYare accepted so that existing migrations andpg_dumpoutput run, and have no further effect: the index orders by the engine's own comparison.CREATE INDEXtakes anACCESS EXCLUSIVElock on the table while it records the index (CONCURRENTLYdoes not change this). The index is then built from the table's rows in the background; queries scan until it is ready, and writes keep it current from the start.- Inside a transaction block,
CREATE INDEXrolls back with the block. See Transactions. - On a partitioned table, every partition keeps the index. See Partitioning.
Choosing the method
With no USING, the method is chosen from the column types:
| Columns | Method |
|---|---|
every column is uuid, jsonb, macaddr or macaddr8 | hash |
| anything else that can be ordered | B-tree |
USING btree or USING hash overrides the choice. A type the method cannot index is refused with the reason; nothing is ever indexed approximately.
| Method | Answers | Column types |
|---|---|---|
| B-tree | =, IN, <, <=, >, >=, BETWEEN, LIKE 'prefix%'; on a composite index, any of these on the leading column | integers, real, double precision, numeric, boolean, timestamp, timestamptz, date, time, uuid, inet, macaddr, macaddr8, text types |
| Hash | = and IN, with every column of the index fixed | the B-tree types, plus jsonb |
| GIN | JSON containment and key existence, or full-text match | one jsonb column, or to_tsvector(...) over text columns |
Refused, with the reason:
intervalandtimetz: two equal values can have different bytes ('1 day'equals'24 hours'), so a lookup by one would miss the other.- geometric types and range types: they have no order an index could keep.
json(text JSON) columns: PostgreSQL has no operator class for them either. Usejsonb, or a path index (below).
A column with a case- or accent-insensitive collation is indexed by what the collation considers equal, so the index finds 'Alice' for 'ALICE'. See Text search and collations.
Unique indexes
CREATE UNIQUE INDEX users_email_key ON users (email);
CREATE UNIQUE INDEX pages_tenant_slug ON pages (tenant_id, slug) WHERE active;A unique index is enforced as a unique constraint, with its own B-tree. A WHERE clause makes it a partial unique key: uniqueness is checked only among rows that satisfy the predicate. IF NOT EXISTS is honoured, so a migration can be re-run.
The key remembers that it was created as an index, as in PostgreSQL: DROP INDEX drops it (add CASCADE to drop foreign keys that depend on it; without it the drop is refused with 2BP01), while ALTER TABLE … DROP CONSTRAINT does not know it. A key created with ALTER TABLE … ADD CONSTRAINT … UNIQUE is the opposite: drop it with ALTER TABLE … DROP CONSTRAINT; DROP INDEX of it is refused.
NULLS NOT DISTINCT is refused.
Always give a unique index a name, as in the examples above.
Indexes on JSON documents
CREATE INDEX docs_gin ON docs USING gin (doc); -- jsonb_ops: @>, ?, ?|, ?&
CREATE INDEX docs_paths ON docs USING gin (doc jsonb_path_ops); -- @> only, more selective
CREATE INDEX docs_status ON docs ((doc->>'status')); -- one path: =, ranges, LIKE 'prefix%'- A GIN index covers exactly one
jsonbcolumn. The operator class isjsonb_ops(the default) orjsonb_path_ops; any other is refused. - A path index is a B-tree over the text that
->>returns for one path. It must be named, written with->>, and have nothing after the parenthesised expression. An index over->is refused.
Nothing indexes a path inside a document automatically, and the filter index does not see inside documents, so doc->>'k' = 'v' reads every row unless you declare a path index for that path. Details, operators and examples are on JSON and JSONB.
Full-text indexes
CREATE INDEX articles_fts ON articles USING gin (to_tsvector('english', title || ' ' || body));A GIN index over to_tsvector('<configuration>', …) of one or more text columns answers @@ queries that use a to_tsvector of the same configuration over those columns. See Text search and collations.
Expression and partial indexes
An expression index such as CREATE INDEX ON users (lower(email)), or a non-unique partial index such as CREATE INDEX ON orders (placed_at) WHERE shipped, is accepted and not built. The statement succeeds so that migrations written for PostgreSQL run, queries return the same rows without it, and the server log records that it was set aside. The only expression forms that are built are a jsonb path ((doc->>'k')) and to_tsvector(…) under USING gin.
For case-insensitive lookups, give the column a case-insensitive collation instead of indexing lower(column).
DROP INDEX
DROP INDEX orders_customer;
DROP INDEX IF EXISTS public.orders_placed;
DROP INDEX users_email_key CASCADE;CONCURRENTLY and a schema qualifier are accepted. Dropping a name that this server never built (an expression or partial index, for example) succeeds, so migrations that create and later drop such indexes keep running. An index that backs a constraint created with ALTER TABLE … ADD CONSTRAINT cannot be dropped this way; drop the constraint.
There is no REINDEX statement. Indexes are rebuilt from the table's rows when it opens (see Where indexes live) and when VACUUM FULL compacts it.
Listing indexes
pg_indexes lists every index, declared or implicit, with the definition PostgreSQL would print; pg_index lists them too.
SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'orders';Is my index used?
The planner decides while the scan runs, from the WHERE clause and the state of each index, so EXPLAIN does not name an index. Its plan for a filtered scan says so:
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;Scan on orders
Filter: (customer_id = 42)
Index use: decided as the scan runs, from the filter and the indexes' stateEXPLAIN ANALYZE runs the statement and adds the rows returned and the execution time.
To see how much a statement actually read, compare rows with rows_scanned in SHOW QUERIES (recent statements) or SHOW QUERY STATS (totals per statement shape):
SHOW QUERIES 5;rows_scanned counts the rows the scan had to look at after every index excluded what it could. Three rows returned out of three scanned means an index found them; three out of ten million means nothing narrowed the read and an index on that predicate would help. See Monitoring.
How the planner uses indexes:
- An index whose every column is fixed by
=orINis preferred, the one with the most columns first. - Otherwise, a B-tree whose leading column is constrained by a range.
- Other indexes whose columns are fixed then narrow that answer further.
- Under
AND, any branch an index answers narrows the read; underOR, an index is used only when every branch can be answered.
An index answer of more than an eighth of the table is set aside in favour of the filter index or a plain scan, which is cheaper at that size.
The filter index
Every table of at least 4,096 rows carries a bit-level filter index over its columns: a few bits of fingerprint per row and value, plus minimum and maximum bounds for each block of rows. Before fetching rows, a scan uses it to rule out every row that cannot match an equality, IN, range, BETWEEN, LIKE 'prefix%' (on text) or IS [NOT] NULL predicate. It may let through a few rows that do not match, which the scan then discards; it never drops a row that does. Results with the filter index off are identical, only slower.
It needs no declaration and is kept up to date by every write. It is saved to disk at clean points, such as a clean shutdown, so a table normally opens without rebuilding it; after a crash it is rebuilt from the rows in the background. Predicates it cannot help with, such as ILIKE, <> or a function call on the column, simply scan.
A column whose predicates would match a large share of the table (more than 2 % of rows per value, by default) is not fingerprinted, because pruning would save little.
Tuning it
SET FILTER max_f = 16; -- all tables
SET FILTER max_f = 12 FOR TABLE events; -- one table
SET FILTER min_f = 10 FOR COLUMN users.email; -- one column
SET FILTER zone_bounds = off FOR COLUMN users.id; -- random UUIDs: range bounds prune nothing
SET FILTER indexed = off FOR TABLE audit_log; -- leave a table out entirely
SET FILTER bloom = on FOR COLUMN orders.status;
SHOW FILTER; -- effective global values
SHOW FILTER FOR TABLE events; -- as resolved for one table
SHOW FILTER FOR COLUMN users.email; -- as resolved for one column
SHOW FILTER KEYS; -- every key, its scope and meaning
RESET FILTER FOR COLUMN users.email; -- remove one layer of overrides
RESET FILTER FOR TABLE events;
RESET FILTER; -- everything back to defaultsSettings layer from global to table to column, the most specific winning. An override names only the keys it changes and inherits the rest.
| Key | Scope | Default | What it does |
|---|---|---|---|
enabled | global | on | Master switch for the filter index. |
backfill_on_open | global | on | Index rows that predate the filter when a table opens. |
min_pruning_ratio | global | 0.9 | Skip the filter on a scan when it would rule out less than this fraction of rows (0..1). A filter that lets a scan start late, which matters for LIMIT, is used regardless. |
checkpoint_interval_secs | global | 10 | How often the background task considers a checkpoint. |
indexed | global, table, column | on | Index this table or column at all. |
zone_bounds | global, table, column | on | Keep per-block minimum and maximum for range pruning. Turn off for values with no locality, such as random UUIDs or hashes. |
bloom | global, table, column | off | Keep a summary per span of 16,384 rows. Reduces how much index data a lookup reads, not how many rows it fetches; pays off for heavy point lookups on columns with few distinct values per span. |
min_f | global, table, column | 4 | Floor on fingerprint bits per row (4..16). |
default_f | global, table, column | 8 | Fingerprint bits used before the column's number of distinct values is known. |
max_f | global, table, column | 16 | Ceiling on fingerprint bits per row (4..16). Higher costs storage and lowers the false-positive rate. |
min_selectivity | global, table, column | 0.02 | Largest fraction of rows one value may match and still be fingerprinted (greater than 0, at most 1). |
min_table_rows | global, table, column | 4096 | Tables with fewer rows are scanned without the filter. |
How changes apply:
SET FILTERandRESET FILTERneed a superuser.SHOW FILTERdoes not.- A change applies to filters built afterwards: tables opened later, and new blocks of rows as they fill. Rows already indexed keep the width they were built with.
SET FILTERsettings are not saved and are not replicated: they last until the server restarts and apply only to the node you run them on.- To keep a global value across restarts, either start the server with the matching
--filter-*flag (--filter,--filter-backfill,--filter-min-pruning-ratio,--filter-checkpoint-secs,--filter-min-f,--filter-default-f,--filter-max-f,--filter-min-selectivity,--filter-min-table-rows,--filter-zone-bounds,--filter-bloom), or set it withSET CONFIG filter.<key> = value(superuser), which applies it at global scope now and saves it for the next start. A flag given at start-up wins over a saved value. See Configuration.
SHOW TABLE STATS t reports filters_ready (the filter has caught up with the rows) and filter_enabled_for_table.
Where indexes live
In memory, rebuilt at open (default)
By default every B-tree, hash, path and GIN index lives in memory, roughly 60 to 90 bytes per row per index for short keys. Only the declaration is stored. When a table opens, its indexes are rebuilt from its rows by a background task; queries scan until the rebuild is done. Because an index is derived from data the write-ahead log already made durable, it cannot disagree with the table after a crash.
Loading a snapshot instead of rebuilding
With --index-storage snapshot, B-tree, hash and path indexes are written to disk at clean points and loaded at the next open instead of rebuilt. A clean point is a clean shutdown, an idle checkpoint, or an explicit call:
SELECT rdb_index_checkpoint('orders'); rdb_index_checkpoint
----------------------
1 of 1 cleanA snapshot is trusted only if nothing wrote to the table after it was taken; any other open rebuilds from rows, exactly as by default. GIN indexes are always rebuilt at open. rdb_index_checkpoint needs a superuser and covers every partition of a partitioned table; run it outside the transaction that wrote the table.
SELECT rdb_index_check('orders') (superuser) compares a table's indexes with its rows, reports what it checked in one row (relation, file_sets, rows_checked, index_entries, missing_entries, filter_values, filter_misses, result), and rebuilds in place anything it finds missing.
Indexes larger than memory
--index-residency decides where B-tree, hash and path index entries are kept:
| Residency | Entries | Block cache (--index-cache-mb) | Memory part (--index-delta-mb) |
|---|---|---|---|
memory (default) | all in RAM | none | not used |
hybrid | sorted files beside the table, plus recent changes in RAM | 1024 MiB | 256 MiB |
disk | sorted files beside the table, plus recent changes in RAM | 64 MiB | 16 MiB |
An explicit --index-cache-mb or --index-delta-mb overrides the residency's default. The block cache is shared by every table. The setting applies to tables opened after it is set; it is shown by SHOW CONFIG as index.residency, index.cache_mb and index.delta_mb. A paged index is rebuilt at open unless --index-storage snapshot can load it. These are startup settings; see Configuration.
Limits
- Expression indexes (other than a
jsonbpath andto_tsvectorunder GIN) and non-unique partial indexes are accepted and not built. - A path index must be named and must have nothing after its expression; otherwise it is accepted and not built.
NULLS NOT DISTINCTon a unique index is refused.- There is no
REINDEX; indexes rebuild at open and onVACUUM FULL. EXPLAINdoes not say which index a scan will use. Userows_scannedinSHOW QUERIES/SHOW QUERY STATS.- Index statistics views such as
pg_stat_user_indexesare not provided. CONCURRENTLYis accepted but the build still locks the table while the index is recorded.ASC/DESC,NULLS FIRST/LASTand operator classes do not change the index's order.- Filter index settings are per node and not replicated;
SET FILTERchanges are lost at restart (use the flags orSET CONFIG filter.*to keep global ones). bytea, array,interval,timetz, geometric and range columns cannot be indexed.