Haki Benita Blog·
How to Prune PostgreSQL Partitions When Filtering on Non-Partition Key Columns
How to Achieve Pruning When Querying by Non-Partitioned Columns in PostgreSQL
Key Takeaway
Haki Benita demonstrates how PostgreSQL can prune partitions when filtering on non-partition key columns if the data follows certain patterns. In a table partitioned by timestamp, local indexes let a query filtering on session_id avoid sequential scans, but it still visits every partition.
Why It Matters
When session IDs correlate strongly with event time and historical partitions no longer change, CHECK constraints can skip irrelevant partitions without changing the time-based partition key.
Technical Breakdown · Distilled from the original source
Excluding partitions with CHECK constraints
- The example uses an append-only event table, sequential session IDs, and sessions that usually last minutes or hours. Per-partition minimum and maximum IDs give ranges of
1–4320for 2025 and4320–10000for 2026. Session4320crosses the year boundary, so neither partition can be excluded for that ID. - A
CHECKconstraint on each child partition declares which IDs it can contain. With constraint exclusion (constraint_exclusion), the planner can skip a partition when its constraint contradicts the query predicate. Local indexes help find rows within the remaining partitions but cannot exclude partitions on their own.
Giving outliers their own ranges
- When session
1also appears in the 2026 partition, widening its constraint to1–10000would cover IDs absent from that partition. Instead, the article usessession_id BETWEEN 1 AND 1 OR session_id BETWEEN 4320 AND 10000.EXPLAINshows that queries for1000and6000each visit one partition, while a query for1still visits both. - To derive the ranges, sort by ID and use
lag()to flag gaps greater than1. A running sum of those flags assigns groups, andMIN()andMAX()give each group's bounds. The author's multirange attempt did not yield pruning; simple range predicates joined byORdid.
Source: Haki Benita Blog· hakibenita.com
PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.