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.
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)
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.