From b990cc38dc64f3333c1c61aba247bfbaea1475f8 Mon Sep 17 00:00:00 2001 From: Michael Paquier Date: Fri, 19 Jul 2019 11:43:05 +0900 Subject: [PATCH] Doc: clarify when table rewrites happen with column addition and DEFAULT 16828d5 has improved ALTER TABLE so as a column addition does not require a rewrite for a non-NULL default with constant expressions, but one spot in the documentation did not get updated consistently. The documentation also now clarifies the fact that this does not apply if the expression is volatile, where a table rewrite is still required. Reported-by: Daniel Westermann Author: Ian Barwick Reviewed-by: Michael Paquier, Daniel Westermann Discussion: https://postgr.es/m/DB6PR0902MB2184C7D5645CF15D75EB7957D2CF0@DB6PR0902MB2184.eurprd09.prod.outlook.com Backpatch-through: 11 --- doc/src/sgml/ddl.sgml | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index 9301f0227d..b2bab81840 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -1301,6 +1301,29 @@ ALTER TABLE products ADD COLUMN description text; value is given (null if you don't specify a DEFAULT clause). + + + From PostgreSQL 11, adding a column with + a constant default value no longer means that each row of the table + needs to be updated when the ALTER TABLE statement + is executed. Instead, the default value will be returned the next time + the row is accessed, and applied when the table is rewritten, making + the ALTER TABLE very fast even on large tables. + + + + However, if the default value is volatile (e.g. + clock_timestamp()) + each row will need to be updated with the value calculated at the time + ALTER TABLE is executed. To avoid a potentially + lengthy update operation, particularly if you intend to fill the column + with mostly nondefault values anyway, it may be preferable to add the + column with no default, insert the correct values using + UPDATE, and then add any desired default as described + below. + + + You can also define constraints on the column at the same time, using the usual syntax: @@ -1315,17 +1338,6 @@ ALTER TABLE products ADD COLUMN description text CHECK (description <> '') correctly. - - - Adding a column with a default requires updating each row of the - table (to store the new column value). However, if no default is - specified, PostgreSQL is able to avoid - the physical update. So if you intend to fill the column with - mostly nondefault values, it's best to add the column with no default, - insert the correct values using UPDATE, and then add any - desired default as described below. - - -- 2.40.0