PostgreSQL ADD COLUMN DEFAULT NULL locks and performance

There’s a issue in the response of Vao Tsun in point 2.

If you use ALTER TABLE my_table ADD COLUMN my_column BOOLEAN; it won’t rewrite all the tuples, it will be just a change in the metadata.

But if you use ALTER TABLE my_table ADD COLUMN my_column BOOLEAN DEFAULT NULL, it will rewrite all the tuples, and it will last for ever on long tables.

The documentation itself tells this.

When a column is added with ADD COLUMN, all existing rows in the table are initialized with the column’s default value (NULL if no DEFAULT clause is specified). If there is no DEFAULT clause, this is merely a metadata change and does not require any immediate update of the table’s data; the added NULL values are supplied on readout, instead.

This tell us that if there is a DEFAULT clause, even if it is NULL, it will rewrite all the tuples.

This is due to a performance issue on the updates clause. If you need to make an update over a no rewrited tuple, it will need to move the tuple to another disk space, consuming more time.

I tested this by my own on Postgresql 9.6, when i had to add a column, on a table that had 300+ million tuples. Without the DEFAULT NULL it lasted 11 ms, and with the DEFAULT NULL it lasted more than 30 minutes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)