Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default for column "xxxx" cannot be cast automatically to type boolean in Postgres DB

Tags:

postgresql

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
);
like image 683
sromit Avatar asked Dec 14 '16 18:12

sromit


2 Answers

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:

  • Changing a column from string to string array in PostgreSQL for a detailed explanation.
  • How to cast varchar to boolean.
like image 104
klin Avatar answered Oct 22 '22 12:10

klin


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; 
like image 2
asherbret Avatar answered Oct 22 '22 13:10

asherbret