Attach Partition Validation Tradeoff
Default ATTACH scans the new table to prove it satisfies the bounds; a pre-checked CHECK constraint lets PostgreSQL skip that validation scan.
Code
-- 大表 ATTACH 的验证成本:默认会扫整表核对边界
CREATE TABLE events_2026_12 (
occurred_at date NOT NULL,
detail text NOT NULL,
PRIMARY KEY (occurred_at, detail)
);
-- 预先声明数据落点:CHECK 约束证明边界已核实
ALTER TABLE events_2026_12
ADD CONSTRAINT events_2026_12_bounds
CHECK (occurred_at >= '2026-12-01' AND occurred_at < '2027-01-01');
CREATE TABLE events (occurred_at date, detail text)
PARTITION BY RANGE (occurred_at);
-- 约束先于 ATTACH 存在时,验证扫描被跳过,只需 ACCESS EXCLUSIVE 锁
ALTER TABLE events ATTACH PARTITION events_2026_12
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
DROP TABLE events, events_2026_12;How it works
The file runs CREATE / ALTER statements.
Breaking the statements into their working parts: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Statements that matter
CREATE TABLE events (occurred_at date, detail text)
PARTITION BY RANGE (occurred_at);
CREATE TABLE events_2026_12 (
occurred_at date NOT NULL,
detail text NOT NULL,
PRIMARY KEY (occurred_at, detail)
);
ALTER TABLE events ATTACH PARTITION events_2026_12
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
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.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
Report a problem with this exampleOpens a pre-filled issue on GitHub.