btree_gin Index Serves Scalar And Array

Create one GIN index over an array column plus a scalar text column with the btree_gin operator classes, so containment and equality share a single index.

SqlData Fetching

Code

snippet
CREATE EXTENSION IF NOT EXISTS btree_gin;

CREATE TABLE tickets (
    id     int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status text NOT NULL,
    tags   text[] NOT NULL
);

INSERT INTO tickets (status, tags)
SELECT CASE WHEN g % 7 = 0 THEN 'closed' ELSE 'open' END,
       CASE WHEN g % 3 = 0 THEN ARRAY['postgres','window'] ELSE ARRAY['cte'] END
FROM generate_series(1, 10000) g;

ANALYZE tickets;

-- 原生 GIN 只有数组能进索引;btree_gin 让标量 status 也成为同一索引的一部分
CREATE INDEX tickets_gin ON tickets USING gin (tags, status);

-- 数组包含 + 标量相等两个条件都能被这一个 GIN 索引服务
EXPLAIN (COSTS OFF)
SELECT id, status FROM tickets
WHERE tags @> ARRAY['postgres'] AND status = 'open';

What the code does

The file runs SELECT / INSERT / CREATE / EXPLAIN statements, touching tickets and generate_series.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run the statement against the tickets table.

Statements that matter

INSERT INTO tickets (status, tags)
SELECT CASE WHEN g % 7 = 0 THEN 'closed' ELSE 'open' END,
       CASE WHEN g % 3 = 0 THEN ARRAY['postgres','window'] ELSE ARRAY['cte'] END
FROM generate_series(1, 10000) g;
EXPLAIN (COSTS OFF)
SELECT id, status FROM tickets
WHERE tags @> ARRAY['postgres'] AND status = 'open';
CREATE TABLE tickets (
    id     int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status text NOT NULL,
    tags   text[] NOT NULL
);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `tickets`, `generate_series`.