How can I add a column that doesn't allow nulls in a Postgresql database?

后端 未结 8 1821
我在风中等你
我在风中等你 2020-12-07 09:08

I\'m adding a new, \"NOT NULL\" column to my Postgresql database using the following query (sanitized for the Internet):

ALTER TABLE mytable ADD COLUMN mycol         


        
相关标签:
8条回答
  • 2020-12-07 09:35

    This worked for me: :)

    ALTER TABLE your_table_name ADD COLUMN new_column_name int;
    
    0 讨论(0)
  • 2020-12-07 09:39

    Specifying a default value would also work, assuming a default value is appropriate.

    0 讨论(0)
  • 2020-12-07 09:39

    this query will auto-update the nulls

    ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) DEFAULT 'whatever' NOT NULL;
    
    0 讨论(0)
  • 2020-12-07 09:42

    Since rows already exist in the table, the ALTER statement is trying to insert NULL into the newly created column for all of the existing rows. You would have to add the column as allowing NULL, then fill the column with the values you want, and then set it to NOT NULL afterwards.

    0 讨论(0)
  • 2020-12-07 09:48

    You have to set a default value.

    ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL DEFAULT 'foo';
    
    ... some work (set real values as you want)...
    
    ALTER TABLE mytable ALTER COLUMN mycolumn DROP DEFAULT;
    
    0 讨论(0)
  • 2020-12-07 09:54

    Or, create a new table as temp with the extra column, copy the data to this new table while manipulating it as necessary to fill the non-nullable new column, and then swap the table via a two-step name change.

    Yes, it is more complicated, but you may need to do it this way if you don't want a big UPDATE on a live table.

    0 讨论(0)
提交回复
热议问题