3

I have a generated column in PostgreSQL 12 defined as

create table people (
   id bigserial primary key,
   a varchar,
   b boolean generated always as (a is not null) stored
);

but now i want column b to be settable but i don't want to lose the data already in the column, i could drop the column and recreate it but that would lose the current data.

Thanks In Advance

2 Answers 2

3

You can run several ALTER TABLE statements in a transaction:

BEGIN;
ALTER TABLE people ADD b_new boolean;
UPDATE people SET b_new = b;
ALTER TABLE people DROP b;
ALTER TABLE people RENAME b_new TO b;
COMMIT;
Sign up to request clarification or add additional context in comments.

Comments

1
  1. alter table people add column temp_data boolean;
  2. update people set temp_data=b --(copy data from column b to temp_data)
  3. Do whatever you want with column "b".
  4. update people set b=temp_data --(move data back)
  5. alter table people drop column temp_data --(optional)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.