IntermediateAdvanced PostgreSQL

Table Partitioning: range partition by date

The query

SQL
-- Partitioned parent table
CREATE TABLE orders_partitioned (
  order_id    INT NOT NULL,
  order_date  DATE NOT NULL,
  total       NUMERIC,
  cust_id     INT
) PARTITION BY RANGE (order_date);

-- Create partitions
CREATE TABLE orders_2023 PARTITION OF orders_partitioned
  FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');

CREATE TABLE orders_2024 PARTITION OF orders_partitioned
  FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');

-- Query works on all partitions transparently
SELECT SUM(total) FROM orders_partitioned
WHERE order_date >= '2024-06-01';
Tested against PostgreSQL 16

Note

Partitioning improves query performance by pruning irrelevant partitions. Query hits only 2024 partition.