Partitioning

Updated · 15 min read
hardPostgreSQL 18sqlpartitioningperformancepartition-pruningpostgresqlinterview

Partitioning splits one large table into smaller tables, called partitions, while queries still use the single table name. Picture a filing cabinet with one drawer per year. To find December's payments you open only that year's drawer, and to throw out very old records you empty one drawer instead of searching every folder. In PostgreSQL, a partitioned table holds no rows itself; it routes every row to the partition whose rule it matches. In this lesson, we will split the Fee Tracker's payments by year, watch PostgreSQL skip partitions a query doesn't need (partition pruning), see the rules for keys, try list and hash partitioning, and learn when partitioning is not worth it.

In One Minute

  • A partitioned table is one name over several partitions; each row lives in exactly one partition.
  • Range partitions hold ranges of values (a year of dates), list partitions hold named values ('card'), and hash partitions spread rows evenly.
  • Partition pruning: a query that filters on the partition key reads only the matching partitions.
  • A primary key or unique constraint must include the partition key.
  • Old data can be removed by dropping or detaching a partition, far faster than a big DELETE.
  • Most tables don't need partitioning. It helps very large tables, mostly ones split by time.

Range Partitioning by Year

Range partitioning gives each partition a range of the partition key, written FROM (included) TO (not included). Payments are usually asked about by date, so paid_on is a natural key. We create the parent table with PARTITION BY RANGE, then one partition per year:

SQL▶ Try it
CREATE TABLE payments_by_year (LIKE payments) PARTITION BY RANGE (paid_on);
ALTER TABLE payments_by_year ADD PRIMARY KEY (payment_id, paid_on);
 
CREATE TABLE payments_2025 PARTITION OF payments_by_year
  FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE TABLE payments_2026 PARTITION OF payments_by_year
  FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
 
INSERT INTO payments_by_year SELECT * FROM payments;
 
SELECT tableoid::regclass AS stored_in, payment_id, paid_on, amount_usd
FROM payments_by_year
ORDER BY payment_id;
Output
CREATE TABLE
 
ALTER TABLE
 
CREATE TABLE
 
CREATE TABLE
 
INSERT 0 7
 
   stored_in   | payment_id |  paid_on   | amount_usd
---------------+------------+------------+------------
 payments_2025 |          1 | 2025-08-28 |     450.00
 payments_2025 |          2 | 2025-10-30 |     250.00
 payments_2025 |          3 | 2025-12-03 |     250.00
 payments_2025 |          4 | 2025-12-29 |     550.00
 payments_2026 |          5 | 2026-01-05 |     200.00
 payments_2025 |          6 | 2025-11-14 |     225.00
 payments_2025 |          7 | 2025-12-19 |     225.00
(7 rows)

Explanation: LIKE payments copies the column names, types and NOT NULL rules. Each partition is a real table with the same columns. The INSERT goes to the parent, and PostgreSQL routes each row by its paid_on: six payments land in payments_2025 and payment 5, paid on January 5, 2026, lands in payments_2026. The hidden column tableoid, cast to regclass, shows the name of the table each row is stored in. Because TO is not included, January 1, 2026 belongs to 2026, never to both years.

One table name, two partitions: each payment is routed by its paid_on date

A row with no matching partition is refused:

SQL▶ Try it
CREATE TABLE payments_by_year (LIKE payments) PARTITION BY RANGE (paid_on);
CREATE TABLE payments_2025 PARTITION OF payments_by_year
  FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE TABLE payments_2026 PARTITION OF payments_by_year
  FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
 
INSERT INTO payments_by_year
VALUES (8, 102, 4, 200.00, '2027-01-05', '2027-01-05', 'card');
Output
CREATE TABLE
 
CREATE TABLE
 
CREATE TABLE
 
ERROR:  no partition of relation "payments_by_year" found for row
DETAIL:  Partition key of the failing row contains (paid_on) = (2027-01-05).

Explanation: No partition covers 2027 yet. Teams either create next year's partition ahead of time (often with a scheduled job or the pg_partman extension), or add a default partition with CREATE TABLE payments_other PARTITION OF payments_by_year DEFAULT;, which catches every row no other partition takes. A default partition is a safety net, not a plan: when you later create the 2027 partition, PostgreSQL must check that no 2027 rows are already sitting in the default, and refuses if they are.

Partition Pruning

Partition pruning means the planner skips every partition that can't hold rows matching the WHERE clause. It is the main reason to partition. Compare a December report with a query that doesn't mention the date:

SQL▶ Try it
CREATE TABLE payments_by_year (LIKE payments) PARTITION BY RANGE (paid_on);
CREATE TABLE payments_2025 PARTITION OF payments_by_year
  FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE TABLE payments_2026 PARTITION OF payments_by_year
  FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
INSERT INTO payments_by_year SELECT * FROM payments;
 
EXPLAIN (COSTS OFF)
SELECT sum(amount_usd) FROM payments_by_year
WHERE paid_on >= '2025-12-01' AND paid_on < '2026-01-01';
 
EXPLAIN (COSTS OFF)
SELECT sum(amount_usd) FROM payments_by_year
WHERE amount_usd > 300;
Output
CREATE TABLE
 
CREATE TABLE
 
CREATE TABLE
 
INSERT 0 7
 
                                      QUERY PLAN
--------------------------------------------------------------------------------------
 Aggregate
   ->  Seq Scan on payments_2025 payments_by_year
         Filter: ((paid_on >= '2025-12-01'::date) AND (paid_on < '2026-01-01'::date))
(3 rows)
 
                        QUERY PLAN
----------------------------------------------------------
 Aggregate
   ->  Append
         ->  Seq Scan on payments_2025 payments_by_year_1
               Filter: (amount_usd > '300'::numeric)
         ->  Seq Scan on payments_2026 payments_by_year_2
               Filter: (amount_usd > '300'::numeric)
(6 rows)

Explanation: The December query filters on paid_on, the partition key, so its plan reads only payments_2025; the 2026 partition is not opened at all. The second query filters on amount_usd, which says nothing about dates, so the plan has to Append (combine) a scan of every partition. With ten years of partitions, the first kind of query reads one tenth of the data and the second reads all of it. Pruning only works when the query filters on the partition key, so choose the key your most common queries already filter on.

Real plans: filtering on the partition key skips a partition; filtering on another column reads them all

Keys, Indexes and Moving Rows

A primary key or unique constraint on a partitioned table must include every partition key column. PostgreSQL checks uniqueness inside each partition, so it can only promise a value is unique across the whole table if the partition key is part of it:

SQL▶ Try it
CREATE TABLE payments_by_year (
  payment_id INTEGER PRIMARY KEY,
  paid_on    DATE NOT NULL,
  amount_usd NUMERIC(8,2) NOT NULL
) PARTITION BY RANGE (paid_on);
Output
ERROR:  unique constraint on partitioned table must include all partitioning columns
DETAIL:  PRIMARY KEY constraint on table "payments_by_year" lacks column "paid_on" which is part of the partition key.

Explanation: That's why the first example used PRIMARY KEY (payment_id, paid_on). The catch is real: two rows could now share a payment_id if their dates differ. In practice the id comes from one identity column or sequence, which hands out each number once, so duplicates don't happen unless someone types the ids by hand.

An index created on the parent is created on every partition, and rows move when their key changes:

SQL▶ Try it
CREATE TABLE payments_by_year (LIKE payments) PARTITION BY RANGE (paid_on);
ALTER TABLE payments_by_year ADD PRIMARY KEY (payment_id, paid_on);
CREATE TABLE payments_2025 PARTITION OF payments_by_year
  FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE TABLE payments_2026 PARTITION OF payments_by_year
  FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
INSERT INTO payments_by_year SELECT * FROM payments;
 
CREATE INDEX ON payments_by_year (student_id);
 
SELECT indexrelid::regclass AS index_name
FROM pg_index
WHERE indrelid IN ('payments_2025'::regclass, 'payments_2026'::regclass)
ORDER BY 1;
 
UPDATE payments_by_year SET paid_on = '2026-01-02' WHERE payment_id = 4;
 
SELECT tableoid::regclass AS stored_in, payment_id, paid_on
FROM payments_by_year
WHERE payment_id IN (4, 5)
ORDER BY payment_id;
Output
CREATE TABLE
 
ALTER TABLE
 
CREATE TABLE
 
CREATE TABLE
 
INSERT 0 7
 
CREATE INDEX
 
          index_name
------------------------------
 payments_2025_pkey
 payments_2026_pkey
 payments_2025_student_id_idx
 payments_2026_student_id_idx
(4 rows)
 
UPDATE 1
 
   stored_in   | payment_id |  paid_on
---------------+------------+------------
 payments_2026 |          4 | 2026-01-02
 payments_2026 |          5 | 2026-01-05
(2 rows)

Explanation: One CREATE INDEX on the parent made a matching index in each partition, next to their primary key indexes, and a partition added later gets the same indexes automatically. Moving payment 4's date into 2026 moved the row from payments_2025 to payments_2026: PostgreSQL deletes it from one partition and inserts it into the other within the same statement.

Dropping Old Data in One Step

Removing a year of data from a partitioned table is a quick change to the table's structure instead of millions of row deletions.

SQL▶ Try it
CREATE TABLE payments_by_year (LIKE payments) PARTITION BY RANGE (paid_on);
CREATE TABLE payments_2025 PARTITION OF payments_by_year
  FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE TABLE payments_2026 PARTITION OF payments_by_year
  FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
INSERT INTO payments_by_year SELECT * FROM payments;
 
ALTER TABLE payments_by_year DETACH PARTITION payments_2025;
 
SELECT count(*) AS still_in_payments_by_year FROM payments_by_year;
SELECT count(*) AS kept_in_payments_2025     FROM payments_2025;
Output
CREATE TABLE
 
CREATE TABLE
 
CREATE TABLE
 
INSERT 0 7
 
ALTER TABLE
 
 still_in_payments_by_year
---------------------------
                         1
(1 row)
 
 kept_in_payments_2025
-----------------------
                     6
(1 row)

Explanation: DETACH PARTITION takes 2025 out of payments_by_year, so queries on the parent no longer see those six rows, but payments_2025 still exists as an ordinary table. You can archive it (Backup and Restore), and then DROP TABLE payments_2025; frees its space at once. A DELETE FROM payments WHERE paid_on < '2026-01-01' on an unpartitioned table must find and mark every row as dead, write all of that to the transaction log, and leave VACUUM to clean up later (MVCC). On a busy server, DETACH PARTITION ... CONCURRENTLY avoids blocking queries while it detaches.

List and Hash Partitioning

List partitioning puts named values in each partition; hash partitioning spreads rows evenly by a hash of the key.

SQL▶ Try it
CREATE TABLE payments_by_method (LIKE payments) PARTITION BY LIST (method);
CREATE TABLE payments_card  PARTITION OF payments_by_method FOR VALUES IN ('card');
CREATE TABLE payments_paper PARTITION OF payments_by_method FOR VALUES IN ('check', 'cash');
CREATE TABLE payments_other PARTITION OF payments_by_method DEFAULT;
 
INSERT INTO payments_by_method SELECT * FROM payments;
 
SELECT tableoid::regclass AS stored_in, count(*) AS payments
FROM payments_by_method
GROUP BY 1
ORDER BY 1;
Output
CREATE TABLE
 
CREATE TABLE
 
CREATE TABLE
 
CREATE TABLE
 
INSERT 0 7
 
   stored_in    | payments
----------------+----------
 payments_card  |        4
 payments_paper |        2
 payments_other |        1
(3 rows)

Explanation: Four card payments go to payments_card and two checks to payments_paper. Payment 5 has a NULL method; a list partition takes NULL only if it lists NULL in its IN (...), so here the row falls into the default partition. Without a default partition, that insert would have failed.

SQL▶ Try it
CREATE TABLE payments_by_student (LIKE payments) PARTITION BY HASH (student_id);
CREATE TABLE payments_h0 PARTITION OF payments_by_student FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE payments_h1 PARTITION OF payments_by_student FOR VALUES WITH (MODULUS 2, REMAINDER 1);
 
INSERT INTO payments_by_student SELECT * FROM payments;
 
SELECT tableoid::regclass AS stored_in, student_id, count(*) AS payments
FROM payments_by_student
GROUP BY 1, 2
ORDER BY 1, 2;
Output
CREATE TABLE
 
CREATE TABLE
 
CREATE TABLE
 
INSERT 0 7
 
  stored_in  | student_id | payments
-------------+------------+----------
 payments_h0 |        101 |        5
 payments_h1 |        103 |        2
(2 rows)

Explanation: PostgreSQL hashes each student_id and divides by the modulus (2); the remainder picks the partition. Every payment for one student always lands in the same partition. With only two students the split looks uneven, five payments against two; hashing evens out across thousands of keys, not a handful. Hash partitioning has no "old data" to drop and only prunes on equality (student_id = 101), so it is mainly used to keep each partition, and its indexes and maintenance, a manageable size.

MethodEach partition holdsTypical keyGood for
RangeA range, FROM included, TO notDates and timesTime-based data; dropping old periods
ListListed valuesRegion, status, tenantData naturally split into a few groups
HashA share by hashAn idSpreading a huge table evenly
Range, list and hash partitioning of the same seven payments

When Not to Partition

Partitioning adds work for every query that doesn't filter on the key, and for everyone who manages the table, so use it only when the table is really large.

Partition whenDon't partition when
The table is very large (often tens of millions of rows or more) and still growingThe table fits comfortably in memory; an index is enough
Most queries filter on one column, usually a dateQueries filter on many different columns
You regularly remove whole periods of old dataData is kept forever and rarely removed
Maintenance (VACUUM, index rebuilds) on one huge table takes too longYou'd end up with thousands of tiny partitions

An index usually solves a slow query on a table of a few million rows (Indexes). Partitioning is not a replacement for indexes; each partition still needs them. Too many partitions slow down planning, so most teams pick monthly or yearly ranges rather than daily ones, unless the data is huge.

Common Mistakes

Choosing a key that queries don't filter on. Every query then scans every partition. Pick the column most queries already have in their WHERE clause.

Forgetting next period's partition. Inserts start failing on New Year's Day. Create partitions ahead of time, or have a job do it, and watch the default partition.

Expecting a unique id without the partition key. A primary key must include the partition key columns.

Partitioning a small table. Seven payments, or even a million, rarely need it. Add the right index first.

Too many partitions. Thousands of partitions make planning slow and maintenance harder. Keep the number moderate.

Wrapping the key in a function. WHERE EXTRACT(YEAR FROM paid_on) = 2025 may not prune; WHERE paid_on >= '2025-01-01' AND paid_on < '2026-01-01' does.

Interview Corner

What is table partitioning?

Splitting one large table into smaller partitions by a key such as a date, while queries still use the single table name. Each row is stored in exactly one partition.

What is partition pruning?

The planner skips partitions that can't contain matching rows, based on the WHERE clause on the partition key, so a query reads only the partitions it needs.

Why must a primary key on a partitioned table include the partition key?

Uniqueness is enforced inside each partition. Only when the partition key is part of the constraint can PostgreSQL guarantee uniqueness across all partitions.

What is the difference between partitioning and sharding?

Partitioning splits a table into pieces inside one database server. Sharding splits data across several servers, which spreads load but makes queries and transactions across shards much harder.

Practice

Challenge: Split enrollments by status with list partitioning: one partition for 'active', one for 'completed' and 'dropped' together. Show which partition each row went to, then show that a query for active enrollments reads only one partition.

Show solution
SQL▶ Try it
CREATE TABLE enrollments_by_status (LIKE enrollments) PARTITION BY LIST (status);
CREATE TABLE enrollments_active PARTITION OF enrollments_by_status FOR VALUES IN ('active');
CREATE TABLE enrollments_closed PARTITION OF enrollments_by_status FOR VALUES IN ('completed', 'dropped');
 
INSERT INTO enrollments_by_status SELECT * FROM enrollments;
 
SELECT tableoid::regclass AS stored_in, student_id, course_id, status
FROM enrollments_by_status
ORDER BY 1, 2, 3;
 
EXPLAIN (COSTS OFF)
SELECT * FROM enrollments_by_status WHERE status = 'active';
Output
CREATE TABLE
 
CREATE TABLE
 
CREATE TABLE
 
INSERT 0 7
 
     stored_in      | student_id | course_id |  status
--------------------+------------+-----------+-----------
 enrollments_active |        101 |         3 | active
 enrollments_active |        101 |         4 | active
 enrollments_active |        102 |         1 | active
 enrollments_active |        102 |         4 | active
 enrollments_active |        103 |         5 | active
 enrollments_closed |        101 |         1 | completed
 enrollments_closed |        101 |         2 | completed
(7 rows)
 
                      QUERY PLAN
------------------------------------------------------
 Seq Scan on enrollments_active enrollments_by_status
   Filter: ((status)::text = 'active'::text)
(2 rows)

The query filters on the partition key, so the plan reads only enrollments_active. status is NOT NULL with a CHECK in the original table, so every row has a partition and no default is needed.

Quick check: Partitioning

4 questions
1A partition is created FOR VALUES FROM ('2025-01-01') TO ('2026-01-01'). Where does a payment dated 2026-01-01 go?
2Which query can use partition pruning on payments partitioned by paid_on?
3Why does CREATE TABLE ... (payment_id INTEGER PRIMARY KEY, paid_on DATE) PARTITION BY RANGE (paid_on) fail?
4What is the fastest way to remove all of 2025's payments from a table partitioned by year?

Key Takeaways

You want toUse
Create a partitioned tableCREATE TABLE t (...) PARTITION BY RANGE (col);
Add a partitionCREATE TABLE t_2026 PARTITION OF t FOR VALUES FROM (...) TO (...);
Catch rows with no partitionCREATE TABLE t_other PARTITION OF t DEFAULT;
See where a row is storedSELECT tableoid::regclass, * FROM t;
Check pruningEXPLAIN the query and look for the partitions it scans
Remove a periodALTER TABLE t DETACH PARTITION t_2025; then DROP TABLE t_2025;

Was this tutorial helpful?

Lesson 99 of 115