Data Engineering/Database Engineering · Part 6 of 14
·13 min read
Partitioning: One Logical Table, Many Physical Ones
How partitioning splits a big table behind a single name, what pruning really buys you, why the course's demo didn't get faster, and the jobs where partitions win easily: cheap scans and instant deletes. Run on real Postgres, with a pruning simulator.
The course has a line I like: the quickest way to query a billion rows is to avoid querying a billion rows. Post 4 put partitioning on the ladder for very large tables. This post builds it on real Postgres, and tests when it helps.
The honest result matches the course's own experience. For a query that an index already answers, partitioning changed nothing. Its real wins are elsewhere, and they're large.
#What partitioning is
Take a million-row customers table, and split it into five tables of 200,000 rows. A query for id = 700001 checks the partition bounds, goes to the one partition that can hold that id, and works with a fifth of the data and a fifth of the index.
The parent table holds no rows itself: it's a name and a set of rules. Clients don't change at all.
#Horizontal or vertical
Horizontal is what people usually mean. Vertical matters for wide tables: a big, rarely read column moves out, so that more of the hot columns fit in each page. Postgres does a version of this automatically with TOAST.
#Three ways to choose a partition
#Partitioning isn't sharding
#Building it
The course's demo, on real Postgres, with five million rows where it used ten. First the plain table and its baseline:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, SUMMARY ON) SELECT count(*) FROM grades_org WHERE g = 30;
QUERY PLAN
---------------------------------------------------------------------------------------------------------
Aggregate (actual time=7.210..7.211 rows=1.00 loops=1)
Buffers: shared hit=1 read=45
-> Index Only Scan using grades_org_g on grades_org (actual time=0.782..5.702 rows=49847.00 loops=1)
Index Cond: (g = 30)
Heap Fetches: 0
Index Searches: 1
Buffers: shared hit=1 read=45
Planning:
Buffers: shared hit=70
Planning Time: 0.599 ms
Execution Time: 7.408 ms
(11 rows)
Now the partitioned version: a parent with PARTITION BY RANGE (g), and four partitions attached to it. Insert through the parent and each row is routed automatically:
CREATE TABLE grades_parts (id serial NOT NULL, g int NOT NULL) PARTITION BY RANGE (g);
CREATE TABLE g0035 (LIKE grades_parts INCLUDING INDEXES);
ALTER TABLE grades_parts ATTACH PARTITION g0035 FOR VALUES FROM (0) TO (35);
-- and the same for 35 to 60, 60 to 80, 80 to 100
INSERT INTO grades_parts SELECT * FROM grades_org;
SELECT tableoid::regclass AS partition, count(*), min(g), max(g) FROM grades_parts GROUP BY 1 ORDER BY 3;
partition | count | min | max
-----------+---------+-----+-----
g0035 | 1748097 | 0 | 34
g3560 | 1250407 | 35 | 59
g6080 | 1002141 | 60 | 79
g80100 | 999355 | 80 | 99
(4 rows)
Look at the max column: the partition FROM (0) TO (35) tops out at 34. The docs say range bounds are inclusive at the lower end and exclusive at the upper, and the course says it learned that the hard way.
Since Postgres 11 you create an index once, on the parent, and it appears on every partition:
CREATE INDEX grades_parts_g ON grades_parts (g);
SELECT tablename, indexname FROM pg_indexes WHERE tablename ~ '^g[0-9]|grades_parts' ORDER BY 1;
tablename | indexname
--------------+----------------
g0035 | g0035_g_idx
g3560 | g3560_g_idx
g6080 | g6080_g_idx
g80100 | g80100_g_idx
grades_parts | grades_parts_g
(5 rows)
SELECT relname, pg_size_pretty(pg_relation_size(oid)) AS size FROM pg_class WHERE relname IN ('grades_org', 'grades_org_g', 'g0035', 'g0035_g_idx') ORDER BY pg_relation_size(oid) DESC;
relname | size
--------------+--------
grades_org | 173 MB
g0035 | 60 MB
grades_org_g | 33 MB
g0035_g_idx | 12 MB
(4 rows)
The first partition's index is 12 MB, against 33 MB for the whole table's.
Try it yourself, on a smaller table:
#Does it make queries faster?
Here's the same query on the partitioned table, then with pruning turned off:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY ON) SELECT count(*) FROM grades_parts WHERE g = 30;
QUERY PLAN
----------------------------------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
Buffers: shared hit=1 read=45
-> Index Only Scan using g0035_g_idx on g0035 grades_parts (actual rows=49700.00 loops=1)
Index Cond: (g = 30)
Heap Fetches: 0
Index Searches: 1
Buffers: shared hit=1 read=45
Planning:
Buffers: shared hit=120 read=21
Planning Time: 1.202 ms
Execution Time: 2.614 ms
(11 rows)
SHOW enable_partition_pruning;
enable_partition_pruning
--------------------------
on
(1 row)
SET enable_partition_pruning = off;
EXPLAIN (COSTS OFF) SELECT count(*) FROM grades_parts WHERE g = 30;
QUERY PLAN
-------------------------------------------------------------------------
Aggregate
-> Append
-> Index Only Scan using g0035_g_idx on g0035 grades_parts_1
Index Cond: (g = 30)
-> Index Only Scan using g3560_g_idx on g3560 grades_parts_2
Index Cond: (g = 30)
-> Index Only Scan using g6080_g_idx on g6080 grades_parts_3
Index Cond: (g = 30)
-> Index Only Scan using g80100_g_idx on g80100 grades_parts_4
Index Cond: (g = 30)
(10 rows)
With pruning on, the plan touches only g0035. With it off, there's an Append over all four partitions. Always check this in EXPLAIN: without pruning, partitioning only adds work.
Now compare with the baseline. The plain table read 46 pages for this query, and so did the partitioned one. Timing differences here are just caching. An index already narrows the search to the same rows, so splitting the table doesn't reduce them further.
The course hit the same wall, and its explanation is that the benefit shows up when a big index no longer fits in memory, which small per-partition indexes avoid. That makes sense given post 4's cliff, though I didn't run a test big enough to show it.
Where I could see a clear win was a query with no useful index. The same range, with no index anywhere:
SET max_parallel_workers_per_gather = 0;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF) SELECT count(*) FROM grades_org WHERE g BETWEEN 85 AND 90;
QUERY PLAN
--------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
Buffers: shared hit=10432 read=11692
-> Seq Scan on grades_org (actual rows=299399.00 loops=1)
Filter: ((g >= 85) AND (g <= 90))
Rows Removed by Filter: 4700601
Buffers: shared hit=10432 read=11692
Planning:
Buffers: shared hit=20 read=6
Planning Time: 0.455 ms
Execution Time: 180.533 ms
(10 rows)
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF) SELECT count(*) FROM grades_parts WHERE g BETWEEN 85 AND 90;
QUERY PLAN
-----------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
Buffers: shared hit=4420
-> Seq Scan on g80100 grades_parts (actual rows=299399.00 loops=1)
Filter: ((g >= 85) AND (g <= 90))
Rows Removed by Filter: 699498
Buffers: shared hit=4420
Planning:
Buffers: shared hit=82 read=19
Planning Time: 1.290 ms
Execution Time: 56.241 ms
(10 rows)
22,124 pages against 4,420, and 180 ms against 56 ms. The partition is a smaller table, so a sequential scan over it just reads less. That's also the course's point about the planner: choosing between index and table scan gets simpler when the table is small.
#The easy wins
#Removing old data
Time-partitioned tables often only ever need to drop their oldest range. This is the case where partitioning has no real competition:
-- remove a year of data from a 2,000,000-row table
DELETE FROM events WHERE at < '2024-01-01';
DELETE 500049
Time: 407.2 ms
ALTER TABLE events_p DETACH PARTITION events_2023;
DROP TABLE events_2023;
Time: 46.3 ms
The DELETE took 407 ms and left half a million dead rows for vacuum to clean up. Detaching and dropping took 46 ms and left nothing: a file was removed. The gap grows with the data, because DELETE works row by row.
#Loading and archiving
- Bulk loading. Load into a standalone table, then
ATTACHit, so the load doesn't touch the live table. - Archiving. Move cold partitions to a cheap tablespace, and keep hot ones on fast disks.
#What it costs
Queries that don't filter on the key. If the database can't rule anything out, it searches every partition:
EXPLAIN (COSTS OFF) SELECT * FROM grades_parts WHERE id = 7;
QUERY PLAN
--------------------------------------------------------
Gather
Workers Planned: 2
-> Parallel Append
-> Parallel Seq Scan on g0035 grades_parts_1
Filter: (id = 7)
-> Parallel Seq Scan on g3560 grades_parts_2
Filter: (id = 7)
-> Parallel Seq Scan on g6080 grades_parts_3
Filter: (id = 7)
-> Parallel Seq Scan on g80100 grades_parts_4
Filter: (id = 7)
(11 rows)
Partition by what your queries filter on, or you've made them slower.
Rows that change partition. An update to the partition key moves the row. It's a delete and an insert into another table:
SELECT tableoid::regclass, id, g FROM grades_parts WHERE id = 1;
tableoid | id | g
----------+----+----
g_low | 1 | 10
(1 row)
Time: 10.410 ms
UPDATE grades_parts SET g = 90 WHERE id = 1;
Time: 8.991 ms
SELECT tableoid::regclass, id, g FROM grades_parts WHERE id = 1;
tableoid | id | g
----------+----+----
g_high | 1 | 90
(1 row)
Time: 5.904 ms
UPDATE grades_parts SET g = 20 WHERE id <= 100000 AND id > 1;
Time: 128.929 ms
UPDATE grades_parts SET g = 80 WHERE id <= 100000 AND id > 1;
Time: 144.868 ms
The row moved from g_low to g_high, automatically. The course warns these updates are slow. In this test, moving 100,000 rows took 145 ms, against 129 ms for updating them in place, so the extra cost was small on a table with no indexes. Postgres writes a new row version for any update anyway. With indexes it would be higher. Either way, choose a key that rarely changes.
Schema changes need the database to support them across partitions, and more objects mean more to manage.
A NULL key. My notes say partition columns must be NOT NULL, but that's the course's demo rather than a rule:
INSERT INTO grades_parts (g) VALUES (NULL);
ERROR: no partition of relation "grades_parts" found for row
DETAIL: Partition key of the failing row contains (g) = (null).
CREATE TABLE g_default PARTITION OF grades_parts DEFAULT;
INSERT INTO grades_parts (g) VALUES (NULL);
SELECT tableoid::regclass, id, g FROM grades_parts;
tableoid | id | g
-----------+----+---
g_default | 2 |
(1 row)
A NULL doesn't fall in any range, so the insert fails, unless you add a DEFAULT partition to catch it. That partition also catches anything else outside the ranges, which can hide bad data.
#Automating partitions
A billion customers at 10 million per partition is 100 partitions, which is too many to write by hand. The course uses a Node script. Any language works, including Postgres's own:
CREATE TABLE customers (id int NOT NULL, name text) PARTITION BY RANGE (id);
DO $$
BEGIN
FOR i IN 0..99 LOOP
EXECUTE format('CREATE TABLE customers_%s PARTITION OF customers FOR VALUES FROM (%s) TO (%s)', i, i * 10000000, (i + 1) * 10000000);
END LOOP;
END $$;
SELECT count(*) AS partitions FROM pg_inherits WHERE inhparent = 'customers'::regclass;
partitions
------------
100
(1 row)
INSERT INTO customers VALUES (123456789, 'Ana');
SELECT tableoid::regclass, id, name FROM customers WHERE id = 123456789;
tableoid | id | name
--------------+-----------+------
customers_12 | 123456789 | Ana
(1 row)
EXPLAIN (COSTS OFF) SELECT * FROM customers WHERE id = 123456789;
QUERY PLAN
------------------------------------
Seq Scan on customers_12 customers
Filter: (id = 123456789)
(2 rows)
The planner still prunes to one of the hundred partitions.
SELECT 2147483647 AS largest_int;
largest_int
-------------
2147483647
(1 row)
SELECT 2147483647 + 1;
ERROR: integer out of range
SELECT 2147483647::bigint + 1 AS as_bigint;
as_bigint
------------
2147483648
(1 row)
#Things that can trip you up
- Forgetting to check pruning. A query can look fine and scan every partition. Read the plan.
- A non-constant filter. Pruning needs a value it can match against bounds. A function on the key can defeat it.
- Too many partitions. Planning takes longer as partitions grow, as the planning buffers above suggest.
- Unique constraints must include the partition key. Each partition enforces its own, so global uniqueness on another column isn't possible.
- Inclusive and exclusive bounds.
FROM (0) TO (35)excludes 35. - A
DEFAULTpartition slows attaching. A new partition has to be checked against it. - Partitioning isn't a substitute for an index. Each partition still needs one.
#Reproduce this yourself
- ✅ In any Postgres 18:
Load before creating indexes, as the course advises: it's much faster.
CREATE TABLE grades_org (id serial NOT NULL, g int NOT NULL); INSERT INTO grades_org (g) SELECT floor(random() * 100) FROM generate_series(1, 5000000); - ✅ Create the parent and partitions as shown, then
INSERT INTO grades_parts SELECT * FROM grades_org;. - ✅ Check where rows went with
SELECT tableoid::regclass, count(*) FROM grades_parts GROUP BY 1;. - ✅ Compare
EXPLAIN (ANALYZE, BUFFERS)on both tables, and withSET enable_partition_pruning = off;. - 📘 For MySQL's take, including the CSV engine trick the course mentions, see its partitioning chapter. I didn't run it.
#Glossary
| Term | Meaning |
|---|---|
| Partition | One physical table behind a partitioned parent |
| Partition key | The column that decides where a row goes |
| Horizontal, vertical | Splitting by rows, or by columns |
| Range, list, hash | Three ways of mapping keys to partitions |
| Pruning | Skipping partitions that can't match |
| Default partition | Catches rows that fit no other partition |
| Attach, detach | Adding an existing table as a partition, or removing one |
#Summary
Partitioning puts many smaller tables behind one name, and the database routes rows and queries, so clients don't change. Pruning is what makes it pay, and only filters on the partition key can prune. Here, with a good index, it read the same pages as a plain table. It clearly helped scans with no index, and it turned deleting a year of data into dropping a file. It costs you on queries off the key, on rows that change partition, and in more objects to manage.
#Concepts at a glance
| Concept | In one line | Why it matters |
|---|---|---|
| Parent table | Holds rules, not rows | Clients keep using one name |
| Automatic routing | Inserts go to the right partition | No application changes |
| Exclusive upper bound | TO (35) stops at 34 | A classic off-by-one |
| Index on the parent | Creates one per partition | One statement, not many |
| Pruning | Rules partitions out at planning | Without it, partitioning hurts |
| Off-key query | Scans every partition | Pick the key by your queries |
| Drop a partition | Removes a file, not rows | Near-instant data retention |
| Row movement | Key updates delete and insert | Pick a stable key |
#Test yourself
A query with a good index read the same pages on a partitioned table as on a plain one. Why, and when would partitioning still help?
The index already narrowed the search to the same rows, so the smaller partition gave nothing extra. It helps when there's no selective index, since a scan covers less, when a whole index no longer fits in memory, and when dropping old data.
A table is partitioned by grade. Why is SELECT * FROM t WHERE id = 7 a problem?
The filter isn't on the partition key, so pruning can't exclude anything, and every partition has to be searched. That can be slower than one table.
Why is dropping a partition so much faster than DELETE?
DELETE marks each row dead one by one, and leaves them for vacuum. Dropping a partition removes its whole file, regardless of how many rows it held.
An insert into a range-partitioned table fails with "no partition found for row". What are two causes?
The value is outside every range, for example 100 when the last range ends at TO (100), or it's NULL. A DEFAULT partition would catch both.
#Open questions and gaps
- I didn't reproduce the course's main claim about memory: small per-partition indexes winning when one big index can't fit. That needs a larger table or a memory-limited server.
- The row-move test used a table without indexes, so it understates the cost.
- 📘 Vertical partitioning, MySQL's partitioning and the CSV storage engine are described, not run.
#Sources
- Hussein Nasser, Fundamentals of Database Engineering
- PostgreSQL docs: Table Partitioning
- MySQL 8.4 docs: Partitioning