Attach Detach Partition Swap
Swap an archive table in as a partition with ALTER TABLE ATTACH PARTITION and detach it back out, moving whole datasets without copying rows.
Code
-- 按月分区的事件表 + 一张结构相同的独立归档表
CREATE TABLE events (
occurred_at date NOT NULL,
detail text NOT NULL,
PRIMARY KEY (occurred_at, detail)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE events_archive (
occurred_at date NOT NULL,
detail text NOT NULL,
PRIMARY KEY (occurred_at, detail)
);
INSERT INTO events_archive VALUES ('2026-12-05', 'archived flash sale');
-- ATTACH:整表挂进父表成为分区,行数据零拷贝
-- 范围必须是父表尚无分区的区间;与 events_2026_11 重叠会被拒绝(would overlap)
ALTER TABLE events ATTACH PARTITION events_archive
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
-- 查询父表能直接看到挂进来的行
SELECT count(*) FROM events WHERE occurred_at = '2026-12-05';
-- DETACH:整块摘出,回到独立表;摘掉后该范围重新空缺,可再 ATTACH 别的表进来
ALTER TABLE events DETACH PARTITION events_archive;
DROP TABLE events_archive, events_2026_11, events;What the code does
Several statements share this file — SELECT / INSERT / CREATE / ALTER, with events_archive and events among the objects involved.
In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
The events_archive table is the working surface here.
Key statements
CREATE TABLE events (
occurred_at date NOT NULL,
detail text NOT NULL,
PRIMARY KEY (occurred_at, detail)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
SELECT count(*) FROM events WHERE occurred_at = '2026-12-05';
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 relations does the SQL touch?
- `events_archive`, `events`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.