🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Partition Pruning: Range, Hash, List and BigQuery Filters

Advanced SQLPerformance⭐ Premium

Partition Pruning & Elimination

Advanced SQL

Partition Your Data

Partitioning splits a large table into smaller, physically separate pieces based on a key. When you query with a filter on the partition key, the database eliminates partitions that don't match — scanning only relevant data.

  • Range Partitioning — By date ranges (most common)
  • Hash Partitioning — Even distribution by hash value
  • List Partitioning — By categorical values (region, status)
  • Partition Pruning — WHERE clause eliminates irrelevant partitions

Partitioning is essential for tables with billions of rows — it turns a 10-minute full table scan into a 1-second partition scan.


Partition Types Visualized

Range PartitioningQ1 2023: Jan – MarQ2 2023: Apr – JunQ3 2023: Jul – SepQ4 2023: Oct – DecWHERE order_date = '2023-06-15'→ Only scans Q2 partitionHash PartitioningP0: hash(user_id) % 4 = 0P1: hash(user_id) % 4 = 1P2: hash(user_id) % 4 = 2P3: hash(user_id) % 4 = 3Even distribution across partitionsNo range queries — point lookups onlyList PartitioningUS: US_EAST, US_WESTEU: EU_WEST, EU_EASTAPAC: APAC_EAST, APAC_WESTDEFAULT: other regionsWHERE region = 'US_EAST'→ Only scans US partition

Range Partitioning

-- PostgreSQL declarative partitioning
CREATE TABLE orders (
  order_id BIGINT,
  customer_id INT,
  order_date DATE,
  total_amount DECIMAL(10,2)
) PARTITION BY RANGE (order_date);

-- Create quarterly partitions
CREATE TABLE orders_2023_q1 PARTITION OF orders
  FOR VALUES FROM ('2023-01-01') TO ('2023-04-01');
CREATE TABLE orders_2023_q2 PARTITION OF orders
  FOR VALUES FROM ('2023-04-01') TO ('2023-07-01');
CREATE TABLE orders_2023_q3 PARTITION OF orders
  FOR VALUES FROM ('2023-07-01') TO ('2023-10-01');
CREATE TABLE orders_2023_q4 PARTITION OF orders
  FOR VALUES FROM ('2023-10-01') TO ('2024-01-01');

â„šī¸

Key Insight: Partition pruning automatically eliminates partitions that don't match the query's WHERE clause. This dramatically reduces I/O by only scanning relevant partitions — from scanning 100GB to scanning 25GB for a quarterly query.


When Pruning Actually Happens

Pruning is a planning decision, not a runtime filter. When you run EXPLAIN on a range predicate over order_date, PostgreSQL evaluates each partition's constraint against that predicate and drops the non-matching partitions from the plan entirely. They appear in neither the plan tree nor the execution statistics, and their indexes are never opened, so the saving is complete rather than proportional.

Parameterised statements complicate the picture. When a prepared statement binds its value only at execution, PostgreSQL defers part of the pruning (available since version 11): the plan carries a one-time filter and removes partitions as the parameter arrives. Repeated calls with different dates can therefore produce different partition sets for the same prepared statement, which shows up in EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) as a reduced count of partitions removed.


Worked Numbers: What a Pruned Scan Saves

A 100 GB orders table split into 40 quarterly partitions holds roughly 2.5 GB per partition. A query for one quarter reads 2.5 GB instead of 100 GB, a 40× reduction in I/O, and each partition carries its own smaller B-tree — a few hundred megabytes instead of tens of gigabytes, which usually fits inside shared_buffers and turns random reads into cache hits. Maintenance gains more than the queries do: deleting expired rows becomes DROP TABLE orders_2019_q1, a metadata operation taking milliseconds, instead of a purge that generates hundreds of millions of dead tuples and keeps autovacuum busy for hours.

The countervailing cost is planning. PostgreSQL locks and checks one constraint per partition while building the plan, so a table with 10,000 partitions can spend longer planning than executing a short query. Production guidance settles around a few hundred partitions per table, extending to a few thousand only when every query is known to hit a narrow slice.


Hash Partitioning

-- Hash partitioning for even distribution
CREATE TABLE users (
  user_id BIGINT,
  username VARCHAR(100),
  email VARCHAR(255)
) PARTITION BY HASH (user_id);

CREATE TABLE users_p0 PARTITION OF users FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE users_p1 PARTITION OF users FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE users_p2 PARTITION OF users FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE users_p3 PARTITION OF users FOR VALUES WITH (MODULUS 4, REMAINDER 3);

List Partitioning

-- List partitioning for categorical data
CREATE TABLE sales (
  sale_id BIGINT,
  region VARCHAR(50),
  amount DECIMAL(10,2)
) PARTITION BY LIST (region);

CREATE TABLE sales_us PARTITION OF sales FOR VALUES IN ('US_EAST', 'US_WEST');
CREATE TABLE sales_eu PARTITION OF sales FOR VALUES IN ('EU_WEST', 'EU_EAST');
CREATE TABLE sales_apac PARTITION OF sales FOR VALUES IN ('APAC_EAST', 'APAC_WEST');

BigQuery Partitioning

-- BigQuery time-unit partitioning
CREATE TABLE `project.dataset.events` (
  event_id STRING, event_time TIMESTAMP,
  user_id STRING, event_type STRING
)
PARTITION BY DATE(event_time)
OPTIONS (require_partition_filter = true);

-- Query with partition filter (required!)
SELECT * FROM `project.dataset.events`
WHERE event_time >= '2024-01-01' AND event_time < '2024-02-01';

âš ī¸

Important: BigQuery's require_partition_filter = true forces queries to include a partition filter, preventing full-table scans and reducing costs. Without it, you scan the entire table and pay for all data.


Partition Pruning Patterns

The rewrite in this block is the most common pruning bug in real code. A predicate that wraps the partition column in a function is opaque to the constraint checker: EXTRACT(YEAR FROM order_date) = 2023 can be satisfied by rows living in any partition, so the planner keeps every partition and the query degrades into a full scan of forty partitions to answer a one-partition question. PostgreSQL does not evaluate the function symbolically, and neither does MySQL or Oracle.

BigQuery is the exception that proves the rule. WHERE DATE(event_time) = '2024-01-15' does prune there, because the partition column expression is part of the table definition and the engine recognizes the transformation; written against a PostgreSQL partition key, the identical shape never prunes. When a query crosses engines, re-test pruning with EXPLAIN, by reading the partitions eliminated in the plan, or by watching Bytes Billed — never assume the predicate transfers.

-- Good: Pruning works
SELECT * FROM orders WHERE order_date = '2023-06-15';

-- Good: Range pruning
SELECT * FROM orders
WHERE order_date BETWEEN '2023-04-01' AND '2023-06-30';

-- Bad: Pruning fails (function on partition column)
SELECT * FROM orders WHERE EXTRACT(YEAR FROM order_date) = 2023;

-- Good: Rewrite for pruning
SELECT * FROM orders
WHERE order_date >= '2023-01-01' AND order_date < '2024-01-01';

Too Many Partitions Is Also a Bug

Over-partitioning fails in ways that look like random slowness rather than a design choice. The symptoms are distinctive: planning time growing in proportion to partition count, thousands of rows in pg_locks after a DDL change, autovacuum that never finishes because it keeps rotating through small partitions, and catalog queries against pg_class that suddenly take seconds. Rules that hold up in production: partition on the column that dominates the predicate, size each partition so it holds at least a few hundred megabytes, pre-create the future range you will need, keep a DEFAULT partition as a safety net, and prefer dropping a partition to deleting its rows.

Partitions per tablePlanning overheadMaintenanceWhen it fits
12 (monthly, one year)NegligibleTrivialSmall and medium tables
40 (quarterly, a decade)LowBatch drop of old rangesTypical analytics tables
500 (daily, multi-year)Measurable per queryAutomation requiredEvent logs with narrow filters
10,000 (per user or hash bucket)Planning dominates the queryUnmanageableAlmost never; use clustering instead

💡Sizing rule

Estimate partition count as retention window divided by time slice, never as rows divided by target rows. Time slices are predictable, row counts drift with traffic, and a fixed layout becomes a maintenance treadmill the moment traffic doubles.


Composite Partitioning (Subpartitioning)

-- First level: by date
CREATE TABLE orders_2023 PARTITION OF orders
  FOR VALUES FROM ('2023-01-01') TO ('2024-01-01')
  PARTITION BY LIST (region);

-- Second level: by region within year
CREATE TABLE orders_2023_us PARTITION OF orders_2023
  FOR VALUES IN ('US_EAST', 'US_WEST');

Partition Maintenance

-- Create new partition in advance
CREATE TABLE orders_2024_q1 PARTITION OF orders
  FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');

-- Detach old partition
ALTER TABLE orders DETACH PARTITION orders_2022_q1;

-- Drop old partition
DROP TABLE orders_2022_q1;

-- Default partition catches unmatched rows
CREATE TABLE orders_default PARTITION OF orders DEFAULT;

Engine Differences Worth Memorizing

Interviewers reach for this comparison because it separates people who have run the systems from people who have only read about them.

EnginePruning triggerFunction on the keyFilter forcedDistinguishing behaviour
PostgreSQL 10 and laterConstraint at plan time, plus runtime for bound parametersBlocks pruningNoenable_partition_pruning defaults to on
MySQL 8Range predicate on the partition columnBlocks pruningEffectively yesQueries should name the partition column
OracleAutomatic at plan timeA few forms understoodNoInterval partitions create the next range on insert
BigQueryPartition column predicateDATE() prunesOptional via require_partition_filterBilling follows partitions scanned, so pruning is a cost control
SQL ServerPredicate against the partition functionBlocks pruningNoReports partition elimination in the plan

The BigQuery row is the one that surprises people: a function over the partition timestamp is legal there and still prunes, and turning on require_partition_filter converts a forgotten predicate into a query error instead of an unexpected invoice.


Quiz: Test Your Knowledge


Follow-Up Questions

  1. When would you choose hash partitioning over range partitioning?
  2. How does partition pruning interact with index usage?
  3. What's the impact of partitioning on INSERT performance?
  4. How do you handle cross-partition queries efficiently?
  5. Explain the concept of partition elimination in distributed databases.

Key Takeaways

  • Range partitioning — Best for date/time columns (quarterly, monthly)
  • Hash partitioning — Even distribution for point lookups (no range queries)
  • List partitioning — Categorical columns (region, status)
  • Partition pruning — WHERE clause must reference partition column directly (no functions!)
  • Default partition — Catches unmatched rows to prevent INSERT errors
  • BigQuery — Use require_partition_filter = true to prevent full-table scans

Common Mistakes

Wrapping the partition key in a function, so the planner keeps every partition in the plan

Fix: Express a range on the key itself and re-run EXPLAIN to confirm partitions were actually removed

Creating thousands of tiny partitions and then blaming the engine for slow planning

Fix: Size by time slice with a few hundred partitions at most, and drop ranges instead of deleting rows

Assuming a DATE() predicate prunes everywhere because it does on BigQuery

Fix: Verify per engine: EXPLAIN for PostgreSQL, partition elimination for SQL Server, Bytes Billed for BigQuery

Letting inserts fall into the DEFAULT partition because the next range was never created

Fix: Schedule pre-creation ahead of each boundary and alert on rows that land in DEFAULT

🔒

Premium Content

Partition Pruning: Range, Hash, List and BigQuery Filters

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement