Reputation: 3059
Here https://stackoverflow.com/a/53016193/10894456 is an answer provided for Oracle 11g, My question is the same:
What is the best approach to add a not null column with default value in production oracle database when that table contain one million records and it is live. Does it create any locks if we do the column creation , adding default value and making it as not null in a single statement?
but for PostgreSQL ?
Upvotes: 2
Views: 5340
Reputation: 1783
This prior answer essentially answers your query.
Cross referencing the relevant PostgreSQL doc with the PostgreSQL sourcecode for AlterTableGetLockLevel
mentioned in the above answer shows that ALTER TABLE ... ADD COLUMN
will always obtain an ACCESS EXCLUSIVE
table lock, precluding any other transaction from accessing the table for the duration of the ADD COLUMN
operation.
This same exclusive lock is obtained for any ADD COLUMN
variation; ie. it doesn't matter whether you add a NULL
column (with or without DEFAULT
) or have a NOT NULL
with a default.
However, as mentioned in the linked answer above, adding a NULL
column with no DEFAULT
should be very quick as this operation simply updates the catalog.
In contrast, adding a column with a DEFAULT
specifier necessitates a rewrite the entire table in PostgreSQL 10 or less.
This operation is likely to take a considerable time on your 1M record table.
According to the linked answer, PostgreSQL >= 11 does not require such a rewrite for adding such a column, so should perform more similarly to the no-DEFAULT
case.
I should add that for PostgreSQL 11 and above, the ALTER TABLE
docs note that table rewrites are only avoided for non-volatile DEFAULT
specifiers:
When a column is added with ADD COLUMN and a non-volatile DEFAULT is specified, the default is evaluated at the time of the statement and the result stored in the table's metadata. That value will be used for the column for all existing rows. If no DEFAULT is specified, NULL is used. In neither case is a rewrite of the table required.
Adding a column with a volatile DEFAULT [...] will require the entire table and its indexes to be rewritten. [...] Table and/or index rebuilds may take a significant amount of time for a large table; and will temporarily require as much as double the disk space.
Upvotes: 8