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.

SqlData Integrity

Code

snippet
-- 按月分区的事件表 + 一张结构相同的独立归档表
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

FAQ

What relations does the SQL touch?
`events_archive`, `events`.