0

I have a column (phase_mapped) in PostgreSQL 11.0 with integers and n/a values. Current datatype of the column in nchar(3). I would like to convert the datatype of this column to integer but n/a is throwing an error. How can I set int datatype of such columns.

phase   phase_mapped
Phase 1   1  
Phase 2   2  
n/a       n/a

I tried following query

ALTER TABLE table
  ALTER COLUMN phase_mapped TYPE INT USING phase_mapped::integer;

Any help is highly appreciated

1 Answer 1

2

You can provide an expression in the using part that deals with the n/a. You probably need to deal with empty strings as well.

ALTER TABLE table
  ALTER COLUMN phase_mapped TYPE INT 
  USING nullif(trim(nullif(phase_mapped,'n/a')),'')::integer;

Or simply remove all non-digit characters:

ALTER TABLE table
  ALTER COLUMN phase_mapped TYPE INT 
  USING nullif(regexp_replace(phase_mapped,'[^0-9]', '', 'g'),'')::integer;
Sign up to request clarification or add additional context in comments.

Comments

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.