sqladvanced

Table Partitioning by Range

Partition large tables by date range for faster queries and easier data lifecycle management.

sql
-- Create partitioned table
CREATE TABLE events (
  id         BIGSERIAL,
  event_type TEXT NOT NULL,
  payload    JSONB,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
) PARTITION BY RANGE (created_at);

-- Create monthly partitions
CREATE TABLE events_2025_01 PARTITION OF events
  FOR VALUES FROM ('2025-01-01') TO ('2025-02-01');

CREATE TABLE events_2025_02 PARTITION OF events
  FOR VALUES FROM ('2025-02-01') TO ('2025-03-01');

-- Create index on each partition (auto-propagated)
CREATE INDEX idx_events_type ON events (event_type);

-- Query only hits relevant partitions
SELECT * FROM events
WHERE created_at >= '2025-01-15'
  AND created_at < '2025-01-20';

Use Cases

  • Time-series data
  • Log tables
  • Event sourcing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.