15

Hey I have just started working on PostgreSQL, and I am wondering how can we change a column's data type, I tried the following command:

alter table tableName alter column columnName type timestamp with time zone;

However I got the following message:

 column "columnName" cannot be cast to type timestamp with time zone

The current column's data type is int, and i would like to change it to timestamp

4 Answers 4

11

Postgres doesn't know how to translate int to timestamp. There are several cases and usually they have different starting date.

  1. Create temporary column with timestamp
  2. Update table and copy data from old column to temporary column using your own translation
  3. Drop old column
  4. Rename temporary column.

If you look into documentation, you will find one line syntax with example how to convert unix time integer type:

ALTER [ COLUMN ] column [ SET DATA ] TYPE type [ USING expression ]
Sign up to request clarification or add additional context in comments.

3 Comments

An example from the docs covers this case perfectly: ALTER TABLE foo ALTER COLUMN foo_timestamp SET DATA TYPE timestamp with time zone USING timestamp with time zone 'epoch' + foo_timestamp * interval '1 second';
Just tell PostgreSQL what time zone to use in the USING expression
Can anyone actually explain how that using expression works? I want to alter disallow a boolean column from being null, but it won't work because some of the values are already null. I want to use a using expression to change that
8

Postgres does't allow int type column to change directly into timezone. To achive this, you have to first change column type to varchar and then change it to timezone.

alter table tableName alter column columnName type varchar(64);

alter table tableName alter column columnName type timestamp with time zone;

Comments

6

There is a better way to do this, with the USING clause. Like so:

ALTER TABLE tableName 
ALTER columnName type TIMESTAMP WITH TIME ZONE 
USING to_timestamp(columnName) AT TIME ZONE 'America/New_York';

Comments

1

I achieved it from timestamp to timestamp with time zone by:

ALTER TABLE tableName ALTER COLUMN columnName SET DATA TYPE timestamp with time zone;

but if it is from timestamp to int or bigint you may need to do this:

ALTER TABLE tableName ALTER COLUMN columnName SET DATA TYPE int8 USING columnName::bigint

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.