1

I have a table called temperature containing 5 columns : centre date tmpmax tmpmin rrquot, date tmpmax tmpmin rrquotare stored as character varying and I need to convert them to double precision in order to manipulate them to calculate some statistics. I used the following SQL command :

ALTER TABLE public.temperature
    ALTER COLUMN "TMPMAX" TYPE double precision
    USING cast("TMPMAX" AS double precision)

But it didn't work for the whole table because there are some cells that contains '' (nothing).

Concerning the date column, is there a way to cast it into date type (data are stored in this format : YYYYMMDD ex. 20030122) with YYYY-MM-DD format ex. 1968-01-13.

Please help in resolving those two problems.

2
  • 1
    I did not get why would you convert column you aim to make double precision to date and how it will help fighting empty values, so I suggested the way to fight empty values Commented May 4, 2017 at 13:35
  • I agree with Vao Tsun. If that is actually a date you should convert it to a DATE not a double Commented May 4, 2017 at 14:07

2 Answers 2

1

you can use condition in USING, like here:

t=# create table s106 (i text);
CREATE TABLE
t=# insert into s106 values ('1'),('');
INSERT 0 2
t=# alter table s106 alter COLUMN i type double precision
t-#     USING cast(i AS double precision);
ERROR:  invalid input syntax for type double precision: ""

conditional:

t=# alter table s106 alter COLUMN i type double precision
    USING cast(case when length(i) < 1 then null else i end AS double precision);
ALTER TABLE
Sign up to request clarification or add additional context in comments.

2 Comments

or cast(nullif(trim(i), '') as double precision)
yes - totally agree for my example. I was not sure If op wants to make them NULL, so I suggested full case to be clear and flexible
1

About date type, if I correctly understand, you have dates stored in character varying type field, like this: 20030122, and you need cast values to date type, (values become like this: 2003-01-22)

If so, you can try:

ALTER TABLE  temperature
ALTER COLUMN "date" TYPE date
USING  cast("date" as date)

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.