Senior
Tell about partitioning in PostgreSQL.
sobes.tech AI
Answer from AI
Partitioning in PostgreSQL is a method of dividing a large table into smaller parts (partitions) to improve performance and manageability of data.
Key points:
- Partitioning allows splitting a table based on a key (e.g., date or value range).
- Each partition is a separate table, but to the user, they appear as a single logical table.
- PostgreSQL supports different types of partitioning: RANGE (range), LIST (list of values), HASH (hashing).
- Queries on a partitioned table are optimized: PostgreSQL only accesses the necessary partitions (partition pruning).
Example of creating a partitioned table by date range:
CREATE TABLE sales (
id serial,
sale_date date,
amount numeric
) PARTITION BY RANGE (sale_date);
CREATE TABLE sales_2023 PARTITION OF sales
FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');
CREATE TABLE sales_2024 PARTITION OF sales
FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
Partitioning helps speed up queries, simplify archiving, and manage large volumes of data.