postgresql - add boolean column to table set default

余生颓废 提交于 2020-11-30 02:19:09

问题


Is this proper postgresql syntax to add a column to a table with a default value of false

ALTER TABLE users
ADD "priv_user" BIT
ALTER priv_user SET DEFAULT '0'

Thanks!


回答1:


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

you can also directly specify NOT NULL

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

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

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;



回答2:


If you want an actual boolean column:

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;



回答3:


Just for future reference, if you already have a boolean column and you just want to add a default do:

ALTER TABLE users
  ALTER COLUMN priv_user SET DEFAULT false;



回答4:


If you are using postgresql then you have to use column type BOOLEAN in lower case as boolean.

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;




回答5:


In psql alter column query syntax like this

Alter table users add column priv_user boolean default false ;

boolean value (true-false) save in DB like (t-f) value .



来源:https://stackoverflow.com/questions/11938621/postgresql-add-boolean-column-to-table-set-default

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!