Sobes.tech
Middle

Tell about partitioning tables in PostgreSQL. Have you used it?

sobes.tech AI

Answer from AI

Partitioning tables in PostgreSQL is a way to split a large table into smaller ones called partitions, to improve performance and simplify data management.

Main types of partitioning:

  • Range: data is divided by ranges of values, for example, by date.
  • List: data is divided by specific values, for example, by region.
  • Hash: data is distributed across partitions using a hash function.

Advantages:

  • Faster queries that only concern a part of the data.
  • Simplifies archiving and deleting old data.
  • Improves parallelism in query processing.

Example of creating a partitioned table by date range:

CREATE TABLE orders (
    id serial,
    order_date date,
    amount numeric
) PARTITION BY RANGE (order_date);

CREATE TABLE orders_2023 PARTITION OF orders
    FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');

CREATE TABLE orders_2024 PARTITION OF orders
    FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');

In my practice, partitioning was used for log tables and transaction history to speed up queries and simplify the deletion of outdated data.