Partitioning

About

Partioning is splitting one table into, multiple smaller, logically divided and more manageable tables.

Postgres' query optimizer is able to exclude partitions that, for sure, won't be affected by the data that it is trying to be read or written. (Postgres automatically routes reads and writes to the right partition)

triangle-exclamation
circle-info

Don't think about partitioning before reaching several million records or having memory problems with queries, as there would be no gain in performance.

The administrative overhead of maintaining the partitions will outweight performance benefits.

triangle-exclamation
circle-check

Types of Partitions

range

The table is partitioned into ranges defined by a key column or set of columns, with no overlap between the ranges of values assigned to different partitions.

circle-info

Useful when working with dates, e.g. Daily/Weekly/Monthly/Yearly partitions.

Creating partition table

list

The table is partitioned by explicitly listing which key values appear in each partition.

circle-info

Ideal for conditions when you know known values of partition key, e.g contry_codes, month_names, etc.

Creating partition table

hash

The table is partitioned by specifying a modulus and a remainder for each partition.

Each partition will hold rows for the remainer, which is the hash value of the partition key divided by the specified modulus.

circle-info

This type is useful when we can't logically divide the data.

Creating partition table

default

Default partition tables are the ones that will receive all the data that does not fit in any of the created partitions.

Accessing Data

Almost always you interact with the master (aka parent or partitioned) table, not the individual partitions.

circle-exclamation
Operation
Use Parent Table?
What Happens Internally

SELECT

✅ Yes

Postgres uses partition pruning to scan only relevant partitions.

INSERT

✅ Yes

Data is routed to the correct partition automatically.

UPDATE

✅ Yes

Postgres finds which partition the row is in and moves it if necessary.

DELETE

✅ Yes

Postgres finds and deletes from the correct partition(s).

COPY

✅ Yes

Same as insert; routed correctly.

ANALYZE, VACUUM

❌ Run per partition

Not automatic on children unless specifically enabled.

Maintainance

detach

Unlink a partition from the partition group. (It does not delete it)

attach

You can atach an unlinked partition again with:

When you reatach yo specifiy the partition type values again RANGE, LIST or HASH.

circle-exclamation

Last updated