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.
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 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With