Table Partitioning by Range
Partition large tables by date range for faster queries and easier data lifecycle management.
-- 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.
Keyset Pagination vs Offset
Efficient keyset (cursor) pagination pattern compared to traditional OFFSET for large datasets in PostgreSQL.
Materialized View with Auto-Refresh
Create and maintain materialized views for expensive aggregate queries with concurrent refresh support.
LATERAL Join for Top-N Per Group
Use LATERAL joins to efficiently fetch the top N related rows per group without window function subqueries.
Row-Level Security Policies
Enforce data access rules at the database level with PostgreSQL Row-Level Security policies.