Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql change column type from int to UUID

Tags:

postgresql

I'd like to change the column type from an int to a uuid. I am using the following statement

ALTER TABLE tableA ALTER COLUMN colA SET DATA TYPE UUID; 

But I get the error message

ERROR:  column "colA" cannot be cast automatically to type uuid HINT:  Specify a USING expression to perform the conversion. 

I am confused how to use USING to do the cast.

like image 751
user1802143 Avatar asked Dec 03 '13 04:12

user1802143


People also ask

How do I change the datatype of a column in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.

What is the data type for UUID in PostgreSQL?

What is the Postgres UUID Type? The Postgres UUID data type stores UUIDs as defined by RFC 4122, which are 128-bit quantities generated by algorithms that minimize the probability of having duplicate identifiers. A UUID comprises of 32 hexadecimal digits, represented in groups of 8,4,4,4 and 12.

Can Postgres generate UUID?

Unfortunately, while PostgreSQL is great for storing and comparing UUID data, it lacks capabilities for creating UUID values in its core. Instead, it relies on third-party modules to create UUIDs using specified techniques.

What is the data type for UUID?

The UUID data type is considered a subtype of the STRING data type, because UUID values are displayed in their canonical textual format and, in general, behave the same as string values in the various SQL operators and expressions.


1 Answers

You can't just cast an int4 to uuid; it'd be an invalid uuid, with only 32 bits set, the high 96 bits being zero.

If you want to generate new UUIDs to replace the integers entirely, and if there are no existing foreign key references to those integers, you can use a fake cast that actually generates new values.

Do not run this without a backup of your data. It permanently throws away the old values in colA.

ALTER TABLE tableA ALTER COLUMN colA SET DATA TYPE UUID USING (uuid_generate_v4()); 

A better approach is usually to add a uuid column, then fix up any foreign key references to point to it, and finally drop the original column.

You need the UUID module installed:

CREATE EXTENSION "uuid-ossp"; 

The quotes are important.

like image 174
Craig Ringer Avatar answered Oct 12 '22 11:10

Craig Ringer