I like the answer from @Frank Heikens. Thanks for that. Anyway I would like to improve a bit;
Let's assume our partitioned table name is partitioned_table
and we have a number suffix which we increase each time. Like partitioned_table_00
, partitioned_table_01
... partitioned_table_99
CREATE OR REPLACE drop_old_partitioned_tables(schema_name TEXT, partitioned_table_name TEXT, suffix TEXT)
RETURNS TEXT
LANGUAGE plpgsql
AS
$$
DECLARE
drop_query text;
BEGIN
SELECT 'DROP TABLE IF EXISTS ' || string_agg(format('%I.%I', table_schema, table_name), ', ')
INTO drop_query
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema = schema_name
AND table_name <= CONCAT(partitioned_table_name, '_', suffix) -- It will also drop the table which equals the given suffix
AND table_name ~ CONCAT(partitioned_table_name, '_\d{2}');
IF drop_query IS NULL THEN
RETURN 'There is no table to drop!';
ELSE
EXECUTE drop_query;
RETURN CONCAT('Executed query: ', (drop_query));
END IF;
END;
$$;
and for the execution, you can run the below code;
SELECT drop_old_partitioned_tables('public', 'partitioned_table', '10')
Just a side note, if you want to partition your table for each year, your table suffix should be year like partitioned_table_2021
. Even if your data bigger which cannot be partitionable for annually, you can do that monthly like partitioned_table_2021_01
. Don't forget to adjust your code depending on your needs.