Partition_management
Chapter 40: Partition Management
Section titled “Chapter 40: Partition Management”Ongoing Partition Maintenance
Section titled “Ongoing Partition Maintenance”40.1 Automated Partition Creation
Section titled “40.1 Automated Partition Creation”-- Function to create monthly partitionsCREATE OR REPLACE FUNCTION create_monthly_partition( p_year INTEGER, p_month INTEGER) RETURNS VOID AS $$DECLARE v_partition_name TEXT; v_start_date DATE; v_end_date DATE;BEGIN v_start_date := make_date(p_year, p_month, 1); v_end_date := v_start_date + INTERVAL '1 month'; v_partition_name := 'orders_' || p_year || '_' || LPAD(p_month::TEXT, 2, '0');
EXECUTE format( 'CREATE TABLE %I PARTITION OF orders FOR VALUES FROM (%L) TO (%L)', v_partition_name, v_start_date, v_end_date );
RAISE NOTICE 'Created partition: %', v_partition_name;END;$$ LANGUAGE plpgsql;
-- Create partitions for next 12 monthsSELECT create_monthly_partition(2024, 1);SELECT create_monthly_partition(2024, 2);-- Continue...
-- Or use a loop in a functionCREATE OR REPLACE FUNCTION create_year_partitions(p_year INTEGER)RETURNS VOID AS $$DECLARE v_month INTEGER;BEGIN FOR v_month IN 1..12 LOOP PERFORM create_monthly_partition(p_year, v_month); END LOOP;END;$$ LANGUAGE plpgsql;
SELECT create_year_partitions(2025);40.2 Partition Pruning
Section titled “40.2 Partition Pruning”PostgreSQL automatically prunes partitions to speed up queries.
-- Enable constraint_exclusionSET constraint_exclusion = partition;
-- Check query plan for partition pruningEXPLAIN SELECT * FROM orders WHERE order_date = '2024-06-15';
-- The query should only scan the relevant partition-- "Partition pruning" in EXPLAIN output
-- Force constraint exclusionALTER TABLE orders SET (constraint_exclusion = partition);40.3 Partition Indexes
Section titled “40.3 Partition Indexes”-- Create indexes on partitionsCREATE INDEX ON orders_2024_q1 (order_date);CREATE INDEX ON orders_2024_q1 (user_id);
-- Or create on main table (propagates to partitions)CREATE INDEX ON orders (order_date);CREATE INDEX ON orders (user_id);
-- Partial indexes on partitionsCREATE INDEX ON orders_2024_q1 (order_date) WHERE status = 'completed';Summary
Section titled “Summary”| Task | Command |
|---|---|
| Create partition | CREATE TABLE … PARTITION OF |
| Attach partition | ALTER TABLE … ATTACH PARTITION |
| Detach partition | ALTER TABLE … DETACH PARTITION |
| Enable pruning | SET constraint_exclusion = partition |