Array Overlap Query GIN Index
Index a tag array with GIN so && overlap and @> containment filters resolve in the index instead of scanning every row.
Code
-- 标签列的"任一命中"查询:&& 判断两个数组是否有公共元素
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO articles (title, tags) VALUES
('trail guide', ARRAY['outdoor', 'hiking']),
('city guide', ARRAY['outdoor', 'urban']);
-- GIN 索引让 && 与 @> 等数组运算符走索引
CREATE INDEX articles_tags_gin ON articles USING gin (tags);
-- 含任一给定标签的文章
SELECT title
FROM articles
WHERE tags && ARRAY['hiking', 'urban'];
-- 包含全部给定标签的文章
SELECT title
FROM articles
WHERE tags @> ARRAY['outdoor', 'hiking'];Inside the snippet
Several statements share this file — SELECT / INSERT / CREATE, with articles among the objects involved.
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; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
Run it in the articles database context.
Core lines
SELECT title
FROM articles
WHERE tags @> ARRAY['outdoor', 'hiking'];
SELECT title
FROM articles
WHERE tags && ARRAY['hiking', 'urban'];
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
Interactive Tools for This Topic
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.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.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.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- What objects does the SQL involve?
- `articles`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.