Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql - add boolean column to table set default

Tags:

sql

postgresql

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!

like image 482
1252748 Avatar asked Oct 05 '22 07:10

1252748


People also ask

How do you create a default value of boolean column in SQL?

ALTER TABLE table_name ALTER COLUMN col_name SET NOT NULL; Or you can put them all together in a single statement: ALTER TABLE table_name ADD COLUMN “col_name” BOOLEAN DEFAULT FALSE; This way it might take longer if the operation is huge.

How do I change the default value of a column in PostgreSQL?

Changing a Column's Default Value. To set a new default for a column, use a command like: ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77; Note that this doesn't affect any existing rows in the table, it just changes the default for future INSERT commands.


1 Answers

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;
like image 442
Eelke Avatar answered Oct 06 '22 21:10

Eelke