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.
Code
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- The references are `tickets`, `generate_series`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.