且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

postgresql - 将布尔列添加到表设置默认值

更新时间:2023-11-30 23:42:40

ALTER TABLE users
  ADD COLUMN "priv_user" BOOLEAN DEFAULT FALSE;

也可以直接指定NOT NULL

you can also directly specify NOT NULL

ALTER TABLE users
  ADD COLUMN "priv_user" BOOLEAN NOT NULL DEFAULT FALSE;

更新:以下仅适用于 postgresql 11 之前的版本.

UPDATE: following is only true for versions before postgresql 11.

正如 Craig 在填充表格中提到的,将其拆分为多个步骤会更有效:

As Craig mentioned on filled tables it is more efficient to split it into steps:

ALTER TABLE users ADD COLUMN priv_user BOOLEAN;
UPDATE users SET priv_user = 'f';
ALTER TABLE users ALTER COLUMN priv_user SET NOT NULL;
ALTER TABLE users ALTER COLUMN priv_user SET DEFAULT FALSE;