'How to rename a partitions table with child tables

I am trying to rename parent table in partitions. I created 3 child tables on year wise manner. I can alter the name of parent table but I don't know how to alter the 3 child table references.

This is my structure of partition tables.

CREATE TABLE IF NOT EXISTS test_demos(
id bigserial NOT NULL,  
partition_by integer NOT NULL,
names character varying (80) NOT NULL,
age integer,
aed character varying (5) NOT NULL,
entered_user_id integer,
entered_post_id integer,
entered_office_id integer,
dept_code character varying (25) NOT NULL,
owner_dept_code character varying (25) NOT NULL,
approval character varying (5) NOT NULL,
which inet,
whom macaddr,
who character varying(50),
row_created_at timestamp(0) WITHOUT TIME ZONE NOT NULL DEFAULT 
CURRENT_TIMESTAMP)
PARTITION BY LIST(partition_by);

CREATE TABLE IF NOT EXISTS test_demos2019s PARTITION OF test_demos FOR VALUES IN (2019);

CREATE TABLE IF NOT EXISTS test_demos2020s PARTITION OF test_demos FOR VALUES IN (2020);

CREATE TABLE IF NOT EXISTS test_demos2021s PARTITION OF test_demos FOR VALUES IN (2021);


Solution 1:[1]

In PostgreSQL this works, as I think, like this.

ALTER TABLE test_demos2019s RENAME TO new_table_name;
ALTER TABLE test_demos2020s RENAME TO new_table_name2;
ALTER TABLE test_demos2021s RENAME TO new_table_name3;

Solution 2:[2]

The syntax to change the table name is,

alter table table_name to new_table_name;

In your case it's:

alter table test_demos2019s to new_table_name;
alter table test_demos2020s to new_table_name;
alter table test_demos2021s to new_table_name;

Solution 3:[3]

In general, you can crete a function, which can rename all child partitions using some pattern

create or replace function rename_partitions()
    returns void as
$BODY$
declare 
    table_rec record;
begin
    for table_rec in
        select 
            inhrelid::regclass::text as c_tbl_name, 
            -- you can use any postgres function to generate new names for child tables
            split_part(inhrelid::regclass::text, '_', 2) as new_tbl_name
                         from   pg_catalog.pg_inherits
                         where  inhparent = 'test_demos'::regclass
    loop
        EXECUTE format($$alter table %I rename to %I$$, 
                   table_rec.c_tbl_name, table_rec.new_tbl_name);
    end loop;
END;
$BODY$
  LANGUAGE plpgsql;

Of course, you can add parameters for this function and make it more generic.

More information is available here:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ScienceKitten
Solution 2 halfer
Solution 3 Alex