Introduction
Sub-partitioning helps organize large tables into smaller, more manageable pieces by dividing data twice, making queries faster and maintenance easier.
Jump into concepts and practice - no test required
CREATE TABLE table_name ( column_definitions ) PARTITION BY partition_method1 (column1); CREATE TABLE partition_name PARTITION OF table_name FOR VALUES partition_values PARTITION BY partition_method2 (column2); CREATE TABLE subpartition_name PARTITION OF partition_name FOR VALUES subpartition_values;
CREATE TABLE sales ( id SERIAL, region TEXT, sale_date DATE, amount NUMERIC ) PARTITION BY LIST (region);
CREATE TABLE sales_east PARTITION OF sales FOR VALUES IN ('East') PARTITION BY RANGE (sale_date);
CREATE TABLE sales_east_2023 PARTITION OF sales_east FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');
CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, customer_id INT, order_region TEXT, order_date DATE, total NUMERIC ) PARTITION BY LIST (order_region); CREATE TABLE orders_north PARTITION OF orders FOR VALUES IN ('North') PARTITION BY RANGE (order_date); CREATE TABLE orders_north_2023 PARTITION OF orders_north FOR VALUES FROM ('2023-01-01') TO ('2024-01-01'); INSERT INTO orders (customer_id, order_region, order_date, total) VALUES (1, 'North', '2023-05-10', 100.00), (2, 'North', '2023-11-20', 250.50); SELECT * FROM orders WHERE order_region = 'North' AND order_date >= '2023-01-01' AND order_date < '2024-01-01';
sub-partitioning in PostgreSQL?PARTITION BY for main partition and SUBPARTITION BY for sub-partition.PARTITION BY RANGE then SUBPARTITION BY LIST, matching PostgreSQL syntax.CREATE TABLE orders (id INT, country TEXT, year INT) PARTITION BY LIST (country) SUBPARTITION BY RANGE (year);
CREATE TABLE orders_us PARTITION OF orders FOR VALUES IN ('US') SUBPARTITION BY RANGE (year);
CREATE TABLE orders_us_2022 PARTITION OF orders_us FOR VALUES FROM (2022) TO (2023);
SELECT * FROM orders WHERE country = 'US' AND year = 2022; if there are rows with country 'US' and year 2022?CREATE TABLE logs (id INT, region TEXT, day DATE) PARTITION BY RANGE (region) SUBPARTITION BY LIST (day);
region is TEXT, so RANGE partitioning on it is invalid.region (LIST) and subpartitioned by sale_date (RANGE). Which approach correctly handles the subpartitioning to optimize query performance for recent sales?