Redirecting INSERT statements to the partitions

Now that the structure is present, the next step is to make rows inserted into the parent table, go into the appropriate partition. The recommended way to do this is with a TRIGGER function:

CREATE OR REPLACE FUNCTION orders_insert_trigger() RETURNS TRIGGER AS $$ BEGIN IF ( NEW.orderdate >= DATE '2004-12-01' AND NEW.orderdate < DATE '2005-01-01' ) THEN INSERT INTO orders_2004_12 VALUES (NEW.*); ELSIF ( NEW.orderdate >= DATE '2004-11-01' AND NEW.orderdate < DATE '2004-12-01' ) THEN INSERT INTO orders_2004_11 VALUES (NEW.*); ... ELSIF ( NEW.orderdate >= DATE '2004-01-01' AND NEW.orderdate < DATE '2004-02-01' ) THEN INSERT INTO orders_2004_01 VALUES (NEW.*); ELSE RAISE EXCEPTION 'Error in orders_insert_trigger(): ...

Get PostgreSQL 10 High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.