Partition routing and constraints
Overview
Routing chooses the destination partition for an INSERT based on the key. PostgreSQL declarative partitioning routes automatically and can move rows after partition-key updates; constraints reject rows outside valid bounds. The teaching view uses an INSTEAD OF INSERT trigger to select a child table. It supports inserts only, not automatic UPDATE or DELETE routing. Child constraints and local indexes do not establish global uniqueness.
First example
BEGIN;INSERT INTO pt_all VALUES(8,11,'west',80);SELECT id,day FROM pt_late WHERE id=8;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 8, 11 ]]How it works
The first example inserts at the range boundary through the view and inspects the late table before rollback. The second deliberately inserts an id already present in the other child; both rows exist because the primary keys are local. PostgreSQL 17 requires a partitioned-table unique or primary key to include every partition-key column, with additional restrictions on expressions. A separate registry or a different key design may be necessary for global identity.
Practical example
BEGIN;INSERT INTO pt_all VALUES(1,12,'east',90);SELECT id,day FROM pt_all WHERE id=1 ORDER BY day;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 1, 1 ], [ 1, 12 ]]Practice and mistakes
Practice: predict what happens for day 21, NULL day, and a duplicate local id. Hint 1: inspect the routing guard. Hint 2: distinguish a duplicate in the same table from a duplicate across tables. Never bypass boundary checks; test multi-row statement atomicity.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE bm_pt(day integer NOT NULL,id integer NOT NULL,PRIMARY KEY(day,id)) PARTITION BY RANGE(day);CREATE TEMP TABLE bm_pt_early PARTITION OF bm_pt FOR VALUES FROM (1) TO (11);CREATE TEMP TABLE bm_pt_late PARTITION OF bm_pt FOR VALUES FROM (11) TO (21);INSERT INTO bm_pt VALUES (1,1),(5,2),(10,3),(10,4),(11,5),(20,6);UPDATE bm_pt SET day=12 WHERE day=1 AND id=1;SELECT day,id,tableoid::regclass FROM bm_pt WHERE id=1;ROLLBACK;Expected result, not executed: "Row (12,1) resides in the late partition."