Sub topic 9
Speeding Up Array Searches with GIN Indexes
Prerequisites and the search problem
Assume you know basic SELECT, WHERE, and CREATE INDEX statements. You should also understand PostgreSQL arrays and the operators @>, <@, and &&.
An array search checks the elements stored in one array column:
tags @> ARRAY['postgres']meanstagscontainspostgres.tags <@ ARRAY['postgres', 'sql']means every value intagsis included in the given array.tags && ARRAY['postgres', 'sql']means the two arrays share at least one value.
A normal B-tree index is usually not the right index for these element-based searches. PostgreSQL provides a GIN index for this purpose.
GIN means Generalized Inverted Index. Instead of storing one index entry for each complete array, GIN stores searchable entries for the array's individual elements. A query can then find rows containing a requested value without scanning every array.
Creating and using the index
Suppose the table has an array column:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
CREATE INDEX posts_tags_gin
ON posts USING gin (tags);The USING gin clause selects the GIN index method. The default operator class for an array column knows how to index array values.
After creating the index, write the query normally:
SELECT id, title
FROM posts
WHERE tags @> ARRAY['postgres'];You can inspect the planner's choice with EXPLAIN:
EXPLAIN
SELECT title
FROM posts
WHERE tags && ARRAY['postgres', 'sql'];On a large table, the plan may contain a Bitmap Index Scan followed by a Bitmap Heap Scan. The index scan finds candidate row locations, and the heap scan reads those table rows. PostgreSQL can still check the condition after reading the rows because an index plan can produce candidates that need rechecking.
| Operator | Meaning | Typical GIN use |
|---|---|---|
| `@>` | Left array contains every right-side value | Find rows containing required tags |
| `<@` | Left array is contained by the right-side array | Find rows using only allowed values |
| `&&` | Arrays have at least one value in common | Find rows matching any requested tag |
| `=` | Arrays have equal contents and shape | Exact array comparisons |
Why PostgreSQL might ignore the index
Creating an index does not force PostgreSQL to use it. The planner estimates the cost of each plan. For a small table, reading the whole table can be cheaper than opening and scanning an index.
Statistics also affect the estimate. After loading or changing a large amount of data, update statistics:
ANALYZE posts;Use EXPLAIN (ANALYZE, BUFFERS) when you need to compare the estimate with actual behavior:
EXPLAIN (ANALYZE, BUFFERS)
SELECT title
FROM posts
WHERE tags @> ARRAY['postgres'];EXPLAIN ANALYZE runs the query, so do not use it casually on an expensive statement in a production system. For a write query, use a transaction and roll it back if you need to test safely.
A query must also match the indexed expression. An index on tags does not automatically optimize a search on an unrelated expression such as lower(tags::text). If you need expression-based searches, create an expression index deliberately and make the query use the same expression.
Choosing GIN carefully
GIN works well when:
- Rows contain several values.
- Queries frequently search for containment or overlap.
- The table is large enough that sequential scans are costly.
- The array values are relatively stable or read-heavy.
GIN is less attractive when arrays change constantly, searches are rare, or the table is small. Measure with realistic data rather than assuming an index helps.
The index does not remove array design concerns. A GIN index can find a row with a matching tag, but it does not enforce that tags are unique, valid, or consistently formatted. If Postgres and postgres should mean the same thing, normalize values before storing them or use a design that enforces that rule.
Exercise
A table has a text[] column named tags, and queries often use tags && ARRAY['sql', 'postgres']. Which index should you create, and why might EXPLAIN still show a sequential scan?
Show answer
Create CREATE INDEX table_tags_gin ON table_name USING gin (tags);. PostgreSQL may still choose a sequential scan when the table is small, the filter matches many rows, or its statistics make the sequential plan look cheaper.