Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change column type from varchar to timestamp

I have a table that is defined like this:

CREATE TABLE session_requests
(
  id character varying(255) NOT NULL,
  authorization_enc character varying(255),
  auto_close integer,
  date_created character varying(255) DEFAULT '1970-01-01 01:00:00'::character varying,,
....
)

I'm trying to do

alter table session_requests alter column date_created type timestamp using date_created::timestamp;

the error that I'm getting is

ERROR:  default for column "date_created" cannot be cast automatically to type timestamp

Anyone has any suggestions?

like image 615
treaz Avatar asked Nov 04 '14 15:11

treaz


People also ask

How to change column type to timestamp in SQL?

To change a MySQL column datatype from text to timestamp, you need to use ALTER command. ALTER TABLE yourTableName MODIFY COLUMN yourColumnName TIMESTAMP; To understand the above syntax, let us create a table.

How do I change varchar?

You can use the ALTER table command to change the length of a varchar column. You can increase the length of a varchar column to a maximum size of 64,000.


1 Answers

Do it in one transaction. You can even do it in a single statement:

ALTER TABLE session_requests
  ALTER date_created DROP DEFAULT
 ,ALTER date_created type timestamp USING date_created::timestamp
 ,ALTER date_created SET DEFAULT '1970-01-01 01:00:00'::timestamp;

SQL Fiddle.

Aside: character varying(255) is almost always a bad (pointless) choice in Postgres. More:

  • Refactor foreign key to fields
like image 193
Erwin Brandstetter Avatar answered Sep 23 '22 12:09

Erwin Brandstetter