Introduction
Attaching and detaching partitions helps organize large tables into smaller parts for easier management and faster queries.
Jump into concepts and practice - no test required
ALTER TABLE parent_table ATTACH PARTITION child_table FOR VALUES partition_values; ALTER TABLE parent_table DETACH PARTITION child_table;
ALTER TABLE sales ATTACH PARTITION sales_2023_q1 FOR VALUES FROM ('2023-01-01') TO ('2023-04-01');
ALTER TABLE sales DETACH PARTITION sales_2022_q4;
CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, order_date DATE NOT NULL, amount NUMERIC ) PARTITION BY RANGE (order_date); CREATE TABLE orders_2023 PARTITION OF orders FOR VALUES FROM ('2023-01-01') TO ('2024-01-01'); CREATE TABLE old_orders ( order_id SERIAL PRIMARY KEY, order_date DATE NOT NULL, amount NUMERIC ); INSERT INTO old_orders (order_date, amount) VALUES ('2022-06-15', 100), ('2022-12-31', 200); ALTER TABLE orders ATTACH PARTITION old_orders FOR VALUES FROM ('2022-01-01') TO ('2023-01-01'); SELECT tableoid::regclass AS partition_name, count(*) AS rows_count FROM orders GROUP BY tableoid;
part_2023 to a partitioned table sales in PostgreSQL?ALTER TABLE sales ATTACH PARTITION part_2023; without specifying the value range, because the partition table already has the range defined.SELECT count(*) FROM sales; after detaching the partition part_2022?
ALTER TABLE sales DETACH PARTITION part_2022; SELECT count(*) FROM sales;
ALTER TABLE sales DETACH PARTITION part_2023; but get an error saying the partition does not exist. What is the most likely cause?part_2023 is not currently attached to sales, so it cannot be detached.DETACH PARTITION removes the link but keeps data; DROP PARTITION deletes data. Using drop won't fix a non-attached partition error.orders partitioned by range on order_date. You want to archive data from 2020 by detaching the partition orders_2020 and then attaching it to a new partitioned table archived_orders. Which sequence of commands correctly achieves this without data loss?ALTER TABLE orders DETACH PARTITION orders_2020; to remove the partition without deleting data.ALTER TABLE archived_orders ATTACH PARTITION orders_2020 FOR VALUES FROM ('2020-01-01') TO ('2021-01-01'); to add it as a partition.