Search code examples
sqlpostgresqldefault-valueinformation-schema

How can I set all columns' default value equal to null in PostgreSQL


I would like to set the default value for every column in a number of tables equal to Null. I can view the default constraint under information_schema.columns.column_default. When I try to run update information_schema.columns set column_default = Null where table_name = '[table]' it throws "ERROR: cannot update a view HINT: You need an unconditional ON UPDATE DO INSTEAD rule."

What is the best way to go about this?


Solution

  • You need to run an ALTER TABLE statement for each column. Never ever try to do something like that by manipulating system tables (even if you find the correct one - INFORMATION_SCHEMA only contains view to the real system tables)

    But you can generate all needed ALTER TABLE statements based on the data in the information_schema views:

    SELECT 'ALTER TABLE '||table_name||' ALTER COLUMN '||column_name||' SET DEFAULT NULL;'
    FROM information_schema.columns
    WHERE table_name = 'foo';
    

    Save the output as a SQL script and then run that script (don't forget to commit the changes)