2

We have a very large table (1 Million records) in some cases and we need to add boolean fields to it which have default values. If we add only column it takes 3 minutes and we add 3 columns in the same statement it takes same time.

$ALTER TABLE Job ADD COLUMN test BOOLEAN NOT NULL default false;
ALTER TABLE
Time: 186506.603 ms

    $ALTER TABLE Job ADD COLUMN test BOOLEAN NOT NULL default false , 
    ADD COLUMN test1 BOOLEAN NOT NULL default false, 
    ADD COLUMN test2 BOOLEAN NOT NULL default false;
    ALTER TABLE
    Time: 179055.546 ms

We are on Postgres 9.1 . Is there a postgres feature allows to add multiple boolean fields with default values in one shot? This is for a database change management /upgrade solution . Is it better than using temp table to copy and insert to add multiple boolean fields with default values to a table ? The temp table approach is described in this blog: http://blog.codacy.com/2015/05/14/how-to-update-large-tables-in-postgresql/

3

1 Answer 1

5

You've already shown the best (simple) way - a compound ALTER TABLE statement that adds them all at once.

To do it without a long lock, you have to do it in multiple steps. Add the column as nullable without the default. Add the default but leave it nullable. UPDATE all existing rows to add the new value, preferably in batches. Then finally alter the table to add the not null constraint.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a hassle to do, but sadly the only reliable way to avoid locking the table for a long time.

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.