Does adding a null column to a postgres table cause a lock?

前端 未结 3 1326
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 03:37

I think I read somewhere that running an ALTER TABLE foo ADD COLUMN baz text on a postgres database will not cause a read or write lock. Setting a default value

3条回答
  •  醉酒成梦
    2020-12-15 04:15

    Adding new null column will lock the table for very very short time since no need to rewrite all data on disk. While adding column with default value requires PostgreSQL to make new versions of all rows and store them on the disk. And during that time table will be locked.

    So when you need to add column with default value to big table it's recommended to add null value first and then update all rows in small portions. This way you'll avoid high load on disk and allow autovacuum to do it's job so you'll not end up doubling table size.

提交回复
热议问题