How do I change column default value in PostgreSQL

Once a table is created you can alter its configuration and set default values for a column. When altering a table an setting a default value only new rows will receive the new default value. Below is the general syntax.

ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB'; 

To remove the default value you can use a similar SQL statement.

ALTER TABLE ONLY users ALTER COLUMN lang DROP DEFAULT;

According to the PostgreSQL Documentation: “If ONLY is specified before the table name, only that table is altered. If ONLY is not specified, the table and all its descendant tables (if any) are altered.”

Once you have set a default value you can UPDATE existing rows by simply updating the NULL values.

UPDATE users SET lang = 'en_GB' 
WHERE lang IS NULL;

Matt McGuire

Proven technology leader with 25+ years of experience in the installation, administration, development, design, and maintenance of various enterprise data related systems.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.