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

后端 未结 8 1858
我在风中等你
我在风中等你 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:57

    You either need to define a default, or do what Sean says and add it without the null constraint until you've filled it in on the existing rows.

    0 讨论(0)
  • 2020-12-07 10:01

    As others have observed, you must either create a nullable column or provide a DEFAULT value. If that isn't flexible enough (e.g. if you need the new value to be computed for each row individually somehow), you can use the fact that in PostgreSQL, all DDL commands can be executed inside a transaction:

    BEGIN;
    ALTER TABLE mytable ADD COLUMN mycolumn character varying(50);
    UPDATE mytable SET mycolumn = timeofday();    -- Just a silly example
    ALTER TABLE mytable ALTER COLUMN mycolumn SET NOT NULL;
    COMMIT;
    
    0 讨论(0)
提交回复
热议问题