将列的值设置为其默认值

Man*_*uer 5 postgresql information-schema

我现有的表很少,我必须在其中修改各种列以使其具有默认值。

如何将默认值应用于的旧记录NULL,以便旧记录与新记录保持一致

ALTER TABLE "mytable" ALTER COLUMN "my_column" SET DEFAULT NOW();
Run Code Online (Sandbox Code Playgroud)

修改表后看起来像这样...

    Table "public.mytable"
 Column      |            Type             |                        Modifiers
-------------+-----------------------------+-----------------------------------------------
 id          | integer                     | not null default nextval('mytable_id_seq'::regclass)
 ....

 my_column   | timestamp(0) with time zone | default now()

Indexes:
  "mytable_pkey" PRIMARY KEY, btree (id)
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的方法可以使所有当前为空且具有默认值的列设置为默认值?

Ola*_*che 5

我只是试过了,很简单

update mytable
set my_column = default
where my_column is null
Run Code Online (Sandbox Code Playgroud)

参见sqlfiddle