1

I have an existing table vault in my database, which has some data in it. I now added a new column to the table, is_master which tells whether some vault is a master vault or not. The SQL that I used was:

ALTER TABLE vault ADD COLUMN is_master BOOLEAN NOT NULL;

UPDATE vault
    SET is_master = (name = 'Master');

However, after running this migration against my existing database, I'm getting some null constraints errors and I can't figure why.

ERROR: column \"is_master\" contains null values

Could someone help me understand what's wrong?

1
  • Do you have rows with NULL in the name column? Commented Nov 6, 2019 at 8:08

2 Answers 2

2

1st add the column with allow null

ALTER TABLE vault ADD COLUMN is_master BOOLEAN

then do update all the rows

UPDATE vault
    SET is_master = name is not null and name = 'Master'

then make it not null

ALTER TABLE vault
    ALTER COLUMN is_master SET NOT NULL
Sign up to request clarification or add additional context in comments.

Comments

0

You have null entries in your name column. Try the below to filter out null names and then set the values you get from name. You can by default set the values as false while you alter

       ALTER TABLE vault ADD COLUMN 
         is_master BOOLEAN NOT NULL
         Set Default FALSE;

      UPDATE vault
       SET is_master = (name = 'Master')
       where name is not null

2 Comments

Which would leave is_master as null for those rows where name is null
Aha correct mate i would edit in a while but with the above update query dont you think though all not nulls would be added a value but left ones as you said ismaster left null would get a default data type value

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.