40

I am trying to update a column in brs.parts table from character varying to boolean. The column has data as Y/N till now. I am using the below command

ALTER TABLE brs.parts ALTER COLUMN is_dpm_scanned TYPE BOOLEAN USING is_dpm_scanned::BOOLEAN

But I am getting the following error:

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

ERROR: default for column "is_dpm_scanned" cannot be cast automatically to type boolean
SQL state: 42804

The table definition was:

CREATE TABLE brs.parts (
    id serial NOT NULL PRIMARY KEY,
    webcrt_part_id INTEGER,
    event_id INTEGER,
    webcrt_job_id INTEGER,
    incoming_serial_number CHARACTER VARYING(256),
    outgoing_serial_number CHARACTER VARYING(256), 
    part_number CHARACTER VARYING(256),
    tag_number NUMERIC,
    is_dpm_scanned CHARACTER VARYING(1) DEFAULT 'N'::CHARACTER VARYING,
    current_operation_id INTEGER,
    creation_date DATE,
    created_by CHARACTER VARYING(20) NOT NULL,
    last_updated_date DATE,
    last_updated_by CHARACTER VARYING(20) NOT NULL,
    is_delete CHARACTER VARYING(1) DEFAULT 'N'::CHARACTER VARYING
);
0

2 Answers 2

79

You have to drop the default constraint before changing the type:

ALTER TABLE parts 
    ALTER COLUMN is_dpm_scanned DROP DEFAULT,
    ALTER COLUMN is_dpm_scanned TYPE BOOLEAN USING is_dpm_scanned::BOOLEAN,
    ALTER COLUMN is_dpm_scanned SET DEFAULT FALSE;

See also:

Sign up to request clarification or add additional context in comments.

Comments

4

If casting an integer column to boolean you need to specify explicitly what values are considered true and what are false. Usually, 0 is mapped to false and everything else to true. To do this execute:

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

1 Comment

Obviously, you don't need to use case. Casting integers to boolean works in Postgres as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.