A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-partition-existing-table.php below:

Website Navigation


Guide to Partitioning Existing Tables in PostgreSQL

Guide to Partitioning Existing Tables in PostgreSQLLast update on December 31 2024 13:03:59 (UTC/GMT +8 hours)

Partitioning an Existing Table in PostgreSQL

Partitioning in PostgreSQL is a powerful technique to improve query performance and manage large datasets. Partitioning an existing table allows you to split it into smaller, manageable chunks based on specific criteria like ranges or values, improving query efficiency and maintenance.

This guide explains how to partition an existing PostgreSQL table step-by-step using declarative partitioning.

Syntax:

Steps and Examples

Step 1: Create a New Partitioned Table

Code:

-- Step 1: Create a new partitioned table
CREATE TABLE sales_partitioned (
    id SERIAL PRIMARY KEY,          -- Primary key column
    sale_date DATE NOT NULL,        -- Partitioning column
    amount NUMERIC(10, 2) NOT NULL  -- Other data
) PARTITION BY RANGE (sale_date);   -- Partitioning strategy

Explanation:

Step 2: Create Partitions

Code:

-- Step 2: Create partitions for the table
CREATE TABLE sales_2022 PARTITION OF sales_partitioned
    FOR VALUES FROM ('2022-01-01') TO ('2023-01-01');  -- Data for 2022

CREATE TABLE sales_2023 PARTITION OF sales_partitioned
    FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');  -- Data for 2023

Explanation:

Step 3: Migrate Data to Partitions

Code:

-- Step 3: Insert data into the partitioned table
INSERT INTO sales_partitioned (id, sale_date, amount)
SELECT id, sale_date, amount FROM sales;  -- Copy data from the original table

Explanation:

Step 4: Drop Original Table (Optional)

Code:

-- Step 4: Drop the original table and rename the partitioned table
DROP TABLE sales;                       -- Remove the old table
ALTER TABLE sales_partitioned RENAME TO sales;  -- Rename the partitioned table

Explanation:

Benefits of Partitioning

Additional Considerations

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4