postgresql - add boolean column to table set default

SqlPostgresql

Sql Problem Overview


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!

Sql Solutions


Solution 1 - Sql

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;

Solution 2 - Sql

If you want an actual boolean column:

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;

Solution 3 - Sql

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;

Solution 4 - Sql

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;

Solution 5 - Sql

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 .

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question1252748View Question on Stackoverflow
Solution 1 - SqlEelkeView Answer on Stackoverflow
Solution 2 - SqlrfuscaView Answer on Stackoverflow
Solution 3 - SqlLondonRobView Answer on Stackoverflow
Solution 4 - SqlFaisal ChohanView Answer on Stackoverflow
Solution 5 - SqlMeet PatelView Answer on Stackoverflow