2

How to alter the table to add a column without blocking the statement in Postgresql?

The below statement at the time of execution is getting stuck forever.

ALTER TABLE test_table ADD COLUMN test_column integer;

I tried killing all long-running queries but it didn't help. This table is in active use by the backend. Backend fires mostly <10 ms queries on the table.

1
  • The ALTER TABLE will be quite fast (a few milliseconds) but there is no way to avoid the exclusive lock it tries to acquire. Commented Oct 28, 2021 at 14:19

1 Answer 1

5

Run below script:

while true
do
    date
    export PGPASSWORD='YOUR_DB_PASSWORD';
    psql -h DB_HOST_NAME -U USER_NAME DB_NAME -qX -v ON_ERROR_STOP=1 -f alter.sql && break
done

alter.sql looks like this.

begin;
    -- Try to acquire a lock on the table without blocking.
    lock table only test in ACCESS EXCLUSIVE MODE NOWAIT;
    -- Change timeout to higher unlimited so that migration can be complete.
    set statement_timeout = 0;
    ALTER TABLE test ADD COLUMN column_to_add INTEGER;     
commit;

Basically, this code continuously tries to acquire the lock without blocking any queries, run the alter command as soon as the lock is acquired.

Inspiration: https://www.depesz.com/2019/09/26/how-to-run-short-alter-table-without-long-locking-concurrent-queries/

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

1 Comment

Ok. This will lock after all current transactions are finished. But how about new transactions? Table will be locked until ALTER TABLE finish.

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.