I have a postgresql DB and a table with almost billion of rows. when I try to add a new column with default value:
ALTER TABLE big_table
ADD COLUMN some_flag integer NOT NULL DEFAULT 0;
The transaction goes on for 30+ min .. and the DB logs starts to shoots warnings.
Any way to optimize the query ?
In Object Explorer, right-click the table with columns for which you want to change the scale and select Design. Select the column for which you want to specify a default value. In the Column Properties tab, enter the new default value in the Default Value or Binding property.
If you use ALTER TABLE statement, it will automatically add the new column to the end of the table. The ALTER privilege is required to perform this: ALTER TABLE table_name ADD col_name data_type NULL | NOT NULL; It will not drop any existing data.
You cannot alter a column to specify a default value if one of the following conditions exists: The table is referenced by a view.
Besides doing it in batches (which will still take a while):
You could dump the table as COPY statements and write a script to edit the contents of the COPY statements to insert another column (COPY can be CSV IIRC).
Then you just reload your altered COPY
dump and it should in theory be faster than the ALTER
because COPY will not log transactions.
The other option is to turn off fsync
while you run the command... just remember to turn it back on.
You can also do both of the above in batches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With