I have multiple tables in which I would like to perform the following operation:
ALTER TABLE table_one
DROP COLUMN id,
ADD id SERIAL PRIMARY KEY;
Is there I can do it all at once?
I have multiple tables in which I would like to perform the following operation:
ALTER TABLE table_one
DROP COLUMN id,
ADD id SERIAL PRIMARY KEY;
Is there I can do it all at once?
You can create sequences for each table and add default value to id column, for example, for two tables, table1
and table2
, this will be like:
do $$
declare maxid int;
begin
select coalesce(max(id)+1, 1) from table1 into maxid;
execute 'create sequence table1_id_seq START WITH '||maxid ;
alter table table1 alter column id set default nextval('table1_id_seq');
select coalesce(max(id)+1, 1) from table2 into maxid;
execute 'create sequence table2_id_seq START WITH '||maxid ;
alter table table2 alter column id set default nextval('table2_id_seq');
end;
$$ language plpgsql