Btree Deduplicate Items Storage
Create two identical B-tree indexes differing only in deduplicate_items and compare pg_relation_size, showing how PG13 packs duplicate TIDs into posting lists.
Code
-- PG13+ 的 B-tree 去重:同一键值的多个 TID 打包进一个 posting list,
-- 重复值越密,索引体积收益越大
CREATE TABLE tags (
id bigint GENERATED ALWAYS AS IDENTITY,
tag text NOT NULL
);
INSERT INTO tags (tag)
SELECT 'hot-' || (g % 10)
FROM generate_series(1, 100000) g;
-- 默认 deduplicate_items=on;显式关掉做对照
CREATE INDEX tags_tag_dedup ON tags (tag) WITH (deduplicate_items = on);
CREATE INDEX tags_tag_full ON tags (tag) WITH (deduplicate_items = off);
SELECT relname,
pg_size_pretty(pg_relation_size(oid)) AS index_size
FROM pg_class
WHERE relname IN ('tags_tag_dedup', 'tags_tag_full')
ORDER BY 1;How the snippet works
What runs here is SELECT / INSERT / CREATE — tags, generate_series and pg_class are the objects involved.
Mechanically, the statements are built from: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Point it at the tags table.
Statements that matter
SELECT relname,
pg_size_pretty(pg_relation_size(oid)) AS index_size
FROM pg_class
WHERE relname IN ('tags_tag_dedup', 'tags_tag_full')
ORDER BY 1;
INSERT INTO tags (tag)
SELECT 'hot-' || (g % 10)
FROM generate_series(1, 100000) g;
CREATE INDEX tags_tag_full ON tags (tag) WITH (deduplicate_items = off);
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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- Which tables does this file reference?
- `tags`, `generate_series`, `pg_class` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.