'Is it possible to cast from one enum to another in PostgreSQL

I need to populate a new table in a second schema from an existing one, but having problems casting the "schema1.a.disclosure_level" column enum to the "schema2.b.disclosure_level" enum. A cast via ::text or :: varchar did not help. Casting to ::schema1.a.disclosure_level raises a cross-database reference error.

INSERT INTO schema1.a (id, disclosure_level)
SELECT schema2.b.id, schema2.b.disclosure_level
FROM schema2.b;

Any ideas?



Solution 1:[1]

@Bergi showed me the solution.

INSERT INTO schema1.a (id, disclosure_level)
SELECT schema2.b.id, schema2.b.disclosure_level::text:schema1.disclosure_level_enum
FROM schema2.b;

where my fault was to use the column name instead of the enum type definition in the cast: schema1.disclosure_level_enum (type) instead of schema1.a.disclosure_level (column)!

Solution 2:[2]

From here:

https://www.postgresql.org/docs/current/datatype-enum.html

8.7.3. Type Safety

Each enumerated data type is separate and cannot be compared with other enumerated types.

Example:

CREATE TYPE animal AS ENUM ('dog', 'cat', 'rabbit');
CREATE TYPE animal_2 AS ENUM ('dog', 'cat', 'rabbit');

create table enum_test(id integer, a animal, a2 animal_2);
insert into enum_test values (1, 'dog', 'cat');

select a::animal from enum_test ;
  a  
-----
 dog

 
select a::animal_2 from enum_test ;
ERROR:  cannot cast type animal to animal_2
LINE 1: select a::animal_2 from enum_test ;

So the answer is no you can't cast one enum to another.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Adrian Klaver