Postgres Alter Column Integer to Boolean

DatabasePostgresql

Database Problem Overview


I've a field that is INTEGER NOT NULL DEFAULT 0 and I need to change that to bool.

This is what I am using:

ALTER TABLE mytabe 
ALTER mycolumn TYPE bool 
USING 
    CASE 
        WHEN 0 THEN FALSE 
        ELSE TRUE 
    END;

But I am getting:

ERROR:  argument of CASE/WHEN must be type boolean, not type integer

********** Error **********

ERROR: argument of CASE/WHEN must be type boolean, not type integer
SQL state: 42804

Any idea?

Thanks.

Database Solutions


Solution 1 - Database

Try this:

ALTER TABLE mytabe ALTER COLUMN mycolumn DROP DEFAULT;
ALTER TABLE mytabe ALTER mycolumn TYPE bool USING CASE WHEN mycolumn=0 THEN FALSE ELSE TRUE END;
ALTER TABLE mytabe ALTER COLUMN mycolumn SET DEFAULT FALSE;

You need to remove the constraint first (as its not a boolean), and secondly your CASE statement was syntactically wrong.

Solution 2 - Database

Postgres can automatically cast integer to boolean. The key phrase is

using some_col_name::boolean
-- here some_col_name is the column you want to do type change

Above Answer is correct that helped me Just one modification instead of case I used type casting

ALTER TABLE mytabe ALTER COLUMN mycolumn DROP DEFAULT;
ALTER TABLE mytabe ALTER mycolumn TYPE bool USING mycolumn::boolean;
ALTER TABLE mytabe ALTER COLUMN mycolumn SET DEFAULT FALSE;

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
QuestionsamsinaView Question on Stackoverflow
Solution 1 - DatabasecatchdaveView Answer on Stackoverflow
Solution 2 - DatabaseRahul ShindeView Answer on Stackoverflow