Senior
What is the purpose of partitioning in PostgreSQL?
sobes.tech AI
Answer from AI
Partitioning in PostgreSQL is used to divide a large table into smaller, logically related parts — partitions. This improves database performance and manageability.
Main advantages of partitioning:
- Faster queries: with proper configuration, the DBMS only accesses the necessary partitions, reducing the amount of data processed.
- Easier maintenance: old data can be quickly deleted or archived by working with individual partitions.
- Increased scalability: facilitates working with very large tables.
Example of creating a partitioned table by date range:
CREATE TABLE sales (
id serial PRIMARY KEY,
sale_date date NOT NULL,
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');
This approach helps efficiently manage data and improve query performance.