Skip to content
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–4320 for 2025 and 4320–10000 for 2026. Session 4320 crosses the year boundary, so neither partition can be excluded for that ID.
  • A CHECK constraint 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 1 also appears in the 2026 partition, widening its constraint to 1–10000 would cover IDs absent from that partition. Instead, the article uses session_id BETWEEN 1 AND 1 OR session_id BETWEEN 4320 AND 10000. EXPLAIN shows that queries for 1000 and 6000 each visit one partition, while a query for 1 still visits both.
  • To derive the ranges, sort by ID and use lag() to flag gaps greater than 1. A running sum of those flags assigns groups, and MIN() and MAX() give each group's bounds. The author's multirange attempt did not yield pruning; simple range predicates joined by OR did.
Source: Haki Benita Blog· hakibenita.com

PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.

Read Official Source

Related PostgreSQL Reference