Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance impact of default value set on table's column in postgresql

Tags:

sql

postgresql

if a table have default value on a column for e.g.

    create table emp
(
       flag    smallint default 1
)

so is there any impact of this default column in bulk import , if I am not using in insert statement.

like image 607
Rahul Gour Avatar asked Sep 05 '25 03:09

Rahul Gour


1 Answers

According to the docs:

Before 11:

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.

source

11 and after:

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.

source

like image 188
mif Avatar answered Sep 07 '25 17:09

mif