CREATE TABLE master_tbl AS
SELECT s.a AS master_id FROM generate_series(1,1000) AS s(a);

ALTER TABLE master_tbl ADD PRIMARY KEY (master_id);

DO $$
DECLARE
    i INT;
    child_name CHAR(2);

BEGIN
    FOR i IN 1..40 LOOP
 
        child_name := TO_CHAR(i, 'fm00');
        EXECUTE 'CREATE TABLE child_tbl' || child_name ||
                ' AS SELECT s.a AS child_id, s.a%10 AS master_id
                FROM generate_series(1,10000) AS s(a)';

        EXECUTE 'ALTER TABLE child_tbl' || child_name ||
                ' ADD PRIMARY KEY (child_id)';
        EXECUTE 'CREATE INDEX idx_child_tbl' || child_name ||
                ' ON child_tbl' || child_name || '(master_id)';
 
    END LOOP;
END;
$$ LANGUAGE plpgsql;

VACUUM;
