AI Hints
Home›PostgreSQL Tutorial›Partitioning, VACUUM and Statistics
PostgreSQL · Lesson 88 of 120

Partitioning

Split big tables.

⏱ 2 min read▶ Video at 1:19:11🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Page views grow by millions of rows a month. Old months are rarely read, and eventually deleted. Partitioning splits one big table into smaller ones, one per month, behind a single name.

  • Millions per month
  • Old months rarely read
  • One table per month

A table per month

Partition by range on viewed at makes a partitioned table. Each partition holds one month. Inserts go to the right partition automatically. Run it. Rows land in January and February, and a query for February only reads that partition.

query.sqlsql
CREATE TABLE views (viewed_at timestamptz NOT NULL, book_id int)
  PARTITION BY RANGE (viewed_at);
CREATE TABLE views_2025_01 PARTITION OF views FOR VALUES FROM ('2025-01-01') TO ('2025-02-01');
CREATE TABLE views_2025_02 PARTITION OF views FOR VALUES FROM ('2025-02-01') TO ('2025-03-01');

INSERT INTO views VALUES ('2025-01-15', 1), ('2025-02-03', 2), ('2025-02-20', 3);
SELECT tableoid::regclass AS partition, count(*) FROM views GROUP BY 1 ORDER BY 1;

EXPLAIN (COSTS OFF) SELECT * FROM views WHERE viewed_at >= '2025-02-10';
Output
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 3
   partition   | count
---------------+-------
 views_2025_01 |     1
 views_2025_02 |     2
(2 rows)

                                 QUERY PLAN
-----------------------------------------------------------------------------
 Seq Scan on views_2025_02 views
   Filter: (viewed_at >= '2025-02-10 00:00:00+00'::timestamp with time zone)
(2 rows)
Also uses _empty
1

Why partition

Queries skip partitions they don't need, called pruning. Dropping an old month is instant, instead of a huge delete. Each partition has smaller indexes. But only partition really big tables, since it adds complexity.

keyvalue
Pruningskip partitions
Old dataDROP a partition
Indexessmaller each
Onlyvery big tables

Summary

Partitioning splits a big table into parts, for pruning and easy cleanup. Next, vacuum.

Key takeaways
  • PARTITION BY RANGE
  • Pruning
  • Drop old months
Next up: VACUUM and Autovacuum — cleaning up dead rows