实现说明
实际执行的是 CREATE—— 是涉及的对象。
真正干活的子句:必填列上的 NOT NULL 限定;把重复值挡在外面的 UNIQUE 约束。
核心语句
CREATE TABLE events (
event_id bigint NOT NULL,
tenant_id integer NOT NULL,
happened_at timestamptz NOT NULL
) PARTITION BY RANGE (happened_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE UNIQUE INDEX ON events (event_id, happened_at);
代码示例
-- A monthly range-partitioned table: primary keys and unique constraints must include the partition key
CREATE TABLE events (
event_id bigint NOT NULL,
tenant_id integer NOT NULL,
happened_at timestamptz NOT NULL
) PARTITION BY RANGE (happened_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
-- A unique index without the partition key is rejected outright:
-- CREATE UNIQUE INDEX ON events (event_id);
-- Error: unique constraints and indexes must include all partition key columns
-- Including happened_at in the index key makes it valid
CREATE UNIQUE INDEX ON events (event_id, happened_at);