Sub topic 14
Which index types support index-only scans
This chapter assumes you know how an index-only scan uses the visibility map and what Heap Fetches means in EXPLAIN (ANALYZE) output. It also assumes you have used INCLUDE. Those topics appear in earlier chapters. Here the question is narrower: which index types can feed an index-only scan, and how do you check that for an index you already have?
Why the index type matters
An index-only scan returns column values that are read straight from index entries. That works only if the index stores the original column value, or can rebuild it exactly. Many index types do not. A hash index keeps a hash code, a BRIN index keeps a summary of block ranges, and a GIN index keeps a mapping from elements to row locations. None of these can hand back the column value, so the planner never picks an index-only scan for them.
PostgreSQL records this ability in the index access method. The access method is the code behind an index type. It exposes a capability called amcanreturn. If an access method has no such function, no index of that type can be scanned index-only. If it does have one, the function is asked per column, because the answer can depend on the operator class.
Support by access method
| Access method | Stores the original value? | Index-only scan | INCLUDE columns |
|---|---|---|---|
| B-tree | Yes | Yes, for all operator classes | PostgreSQL 11 and later |
| GiST | Depends on the operator class | Only for operator classes that can return the value | PostgreSQL 12 and later |
| SP-GiST | Depends on the operator class | Only for operator classes that can return the value | PostgreSQL 14 and later |
| Hash | No, only a hash code | No | No |
| GIN | No, only element-to-row mappings | No | No |
| BRIN | No, only block-range summaries | No | No |
The rest of this chapter goes through the table.
B-tree
B-tree is the default index type and the usual choice for covering indexes. Every key column is stored in full, so every key column can be returned. Columns added with INCLUDE are stored in the index entries as payload, and they can be returned too. All the earlier examples in this tutorial rely on this.
GiST and SP-GiST
GiST and SP-GiST are frameworks for building tree indexes over data that does not sort in a simple order, such as points, boxes, ranges and network addresses. Each operator class decides what is stored in the index.
- Some operator classes store the value exactly, or can reconstruct it. Examples include
point_opsand range operator classes. Index-only scans work for them. - Some operator classes are lossy. For example, an index on a
polygoncolumn stores the polygon's bounding box, not the polygon. The index cannot rebuild the original value, so it cannot answer a query that selects the column.
The same index can mix both cases. In a multicolumn GiST index, one column may be returnable and another not. A query can use an index-only scan only if every column it needs from the index is returnable.
Operator class support has grown across releases, so do not rely on a list from memory. Check the specific index on your version, as shown below.
Hash, GIN and BRIN
These three never support index-only scans.
- A hash index stores only the hash of each key. Different values can share a hash, so the index cannot return the value.
- A GIN index is built to find rows that contain given elements, such as array items or words in a document. It does not store the whole column value for each row.
- A BRIN index stores a minimum and maximum (or similar summary) per range of table blocks. It points at ranges of the heap, not at individual rows.
For these types, a query that selects the indexed column still has to read the heap. You can use INCLUDE for none of them, so you cannot build a covering index of these types.
Checking support in your own database
You can ask PostgreSQL directly. Two catalog functions cover this.
First, list which index access methods accept INCLUDE on your server:
SELECT a.amname,
pg_indexam_has_property(a.oid, 'can_include') AS can_include
FROM pg_am a
WHERE a.amtype = 'i'
ORDER BY a.amname;Second, check whether each column of an existing index is returnable. This uses the covering index from earlier in the tutorial:
SELECT a.attnum,
a.attname,
pg_index_column_has_property(
'orders_customer_total_idx'::regclass,
a.attnum::int,
'returnable') AS returnable
FROM pg_attribute a
WHERE a.attrelid = 'orders_customer_total_idx'::regclass
AND a.attnum > 0
ORDER BY a.attnum;Both columns, customer_id and the included total, should report true. Run the same query against an index of another type to see how it differs.
The property name is returnable, and the function takes the column's position within the index, starting at 1. The result is the authority for that exact index on that exact server version. It is more reliable than documentation or a blog post.
A GiST example
The following example builds a GiST index on a point column and lets the planner use an index-only scan. It also uses INCLUDE with GiST, which needs PostgreSQL 12 or later.
CREATE TABLE places (
id integer NOT NULL,
loc point NOT NULL
);
INSERT INTO places (id, loc)
SELECT g, point(random() * 1000, random() * 1000)
FROM generate_series(1, 200000) AS g;
CREATE INDEX places_loc_idx ON places USING gist (loc) INCLUDE (id);
VACUUM (ANALYZE) places;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, loc
FROM places
WHERE loc <@ box '((0,0),(10,10))';The box covers a tiny part of the 1000 by 1000 area, so only a few dozen rows match. With the table freshly vacuumed, the plan should show Index Only Scan using places_loc_idx and Heap Fetches: 0. The point_ops operator class can return the point, and id is carried as payload.
Everything from earlier chapters still applies. A GiST index-only scan consults the same visibility map. If a table has many pages that are not all-visible, you will see non-zero Heap Fetches here too.
If you replace point with polygon and select the polygon, the plan will not use an index-only scan. The operator class stores bounding boxes, and the column is not returnable.
Deciding which index type to use
The access method is chosen by the operators your queries need, not by a wish for index-only scans. A GIN index exists because you need to search inside arrays or JSONB. Choosing B-tree instead would not answer those queries.
A practical order of thought:
- Pick the access method that supports the operators in your
WHEREclause. - If it is B-tree, design the covering index with key and
INCLUDEcolumns as in earlier chapters. - If it is GiST or SP-GiST, check
returnablefor the columns you select. - If it is hash, GIN or BRIN, accept that the heap will be visited. Reduce its cost in other ways, such as selective predicates,
LIMIT, or a separate B-tree index for the covering case.
Common mistakes
- Assuming GiST always works. Support is per operator class and per column. Check
returnablebefore you design around it. - Expecting
INCLUDEon GIN, hash or BRIN. The syntax is rejected for these types. Only B-tree, GiST and SP-GiST accept it, and only on the versions listed in the table. - Forgetting the version.
INCLUDEfor B-tree needs PostgreSQL 11, for GiST 12, and for SP-GiST 14. On an older server, a statement that works elsewhere may fail. - Blaming the index type when the problem is the visibility map. A returnable index can still show many
Heap Fetchesafter heavy updates. CheckVACUUMfirst, as covered earlier.
Exercise
A table has a GIN index on a text[] column called tags and a B-tree index on (customer_id). A query runs SELECT tags FROM t WHERE tags @> ARRAY['sale']. A colleague proposes adding INCLUDE (tags) to the GIN index so the query becomes index-only. Will that work? What would you check, and what would you do instead if the heap visits are too costly?
Show answer
It will not work. GIN does not support INCLUDE, and GIN indexes are not returnable, so no index-only scan is possible. You can confirm both on your server with pgindexamhasproperty('gin' access method oid, 'caninclude') and pgindexcolumnhasproperty(index, 1, 'returnable'). Both report false. The @> operator needs GIN, so the B-tree on customer_id cannot replace it. To reduce heap cost, make the predicate more selective, add a LIMIT, or avoid selecting the full array. If the query needs only a few other columns, select just those and accept a Bitmap Heap Scan.
Exercise
You create a multicolumn GiST index on (loc, regionid) where loc is a polygon and regionid is an integer. A query selects only regionid and filters on loc && somepolygon. Is an index-only scan possible? How would you find out for sure?
Show answer
Not necessarily, and the reliable way is to ask the server. The query needs regionid from the index, and the filter uses loc as a search condition. Whether the scan can be index-only depends on whether the columns the query needs are returnable. Run pgindexcolumnhasproperty(indexoid, 2, 'returnable') for region_id. A GiST index over polygons stores bounding boxes for loc, so loc itself is not returnable. Since the query does not select loc, that does not by itself block the scan, but you must confirm with EXPLAIN and the property check on your version, because support depends on the operator class and the PostgreSQL release. Also confirm that the visibility map is current, or Heap Fetches will stay high.