Overview
Partitioning splits one logical table into smaller physical pieces by a partition key. Its main wins are partition pruning (skip pieces that cannot match), cheap data lifecycle (drop or detach a whole old partition instead of a huge DELETE), and easier maintenance. It is not an automatic speed-up for every query.
Core concepts
- Range (dates, ids), list (region, tenant), hash (even spread) partitioning.
- Pruning happens when the query filters on the partition key with values the planner can use.
- Unique constraints must include the partition key in PostgreSQL, because each partition has its own indexes. Oracle supports local and global indexes; SQL Server needs the partitioning column in a unique aligned index.
- Engine features: PostgreSQL declarative partitioning (
PARTITION BY), SQL Server partition functions and schemes plusSWITCHfor instant load/unload, Oracle partitioning (a separately licensed option on Enterprise Edition) with interval and reference partitioning.
Worked example
PostgreSQL 17, two monthly partitions with 100,000 rows:
CREATE TABLE ev (
id bigint GENERATED ALWAYS AS IDENTITY,
created date NOT NULL,
payload text,
PRIMARY KEY (id, created) -- must contain the partition key
) PARTITION BY RANGE (created);
CREATE TABLE ev_2025_01 PARTITION OF ev FOR VALUES FROM ('2025-01-01') TO ('2025-02-01');
CREATE TABLE ev_2025_02 PARTITION OF ev FOR VALUES FROM ('2025-02-01') TO ('2025-03-01');Filtering on the key scans only one partition:
EXPLAIN SELECT count(*) FROM ev WHERE created >= '2025-02-10' AND created < '2025-02-20';
Aggregate
-> Seq Scan on ev_2025_02 evwhile WHERE payload = 'x' (no key) scans both. Retiring old data is ALTER TABLE ev DETACH PARTITION ev_2025_01; followed by dropping or archiving it.
Pitfalls and production notes
- Choose the key from how data is queried and aged, not only how it is inserted.
- Thousands of partitions raise planning time and memory; keep the count in the tens or hundreds unless you have measured otherwise.
- Create future partitions ahead of time (cron job,
pg_partman, interval partitioning) so inserts never fail. - Do not partition small tables; an index usually suffices (indexing-theory).
- ClickHouse partitions serve data management more than query speed; its sorting key does the heavy lifting.
Practice questions
- Why must the primary key include the partition key in PostgreSQL?
- Which queries get slower after partitioning by month?
- How would you migrate a 2 TB table to partitioned with minimal downtime?
References
- PostgreSQL manual, Table Partitioning: https://www.postgresql.org/docs/current/ddl-partitioning.html
- Microsoft Learn, Partitioned tables and indexes
- Oracle VLDB and Partitioning Guide
Related
indexing-theory · query-planning · safe-schema-migrations · sqlserver-partitioning · oracle-partitioning · ch-partitions