AdvancedDate & Time Functions

Partition by date range with automatic partition creation

The query

SQL
-- Parent table
CREATE TABLE metrics (
  id         BIGSERIAL,
  recorded_at TIMESTAMP NOT NULL,
  metric_name TEXT,
  value       NUMERIC
) PARTITION BY RANGE (recorded_at);

-- Create partition for each month
CREATE TABLE metrics_2024_01 PARTITION OF metrics
  FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');

CREATE TABLE metrics_2024_02 PARTITION OF metrics
  FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');

-- Create default partition for out-of-range data
CREATE TABLE metrics_default PARTITION OF metrics DEFAULT;

-- Check which partition a row goes to
SELECT tableoid::regclass AS partition, COUNT(*)
FROM metrics
GROUP BY tableoid::regclass;
Tested against PostgreSQL 16

Note

tableoid::regclass shows which partition each row lives in. Useful for partition monitoring.