how to convert varchar variable to enum without first declaring the enum type?

41 views Asked by At

I am using SELECT to generate a result set from a database:

SELECT id countryname FROM dataset

where -countryname- is stored as varchar.

And I intend to convert the -countryname- to its equivalent enum type in this process, without having to first run the standard declaration statement:

CREATE TYPE countries AS ENUM ('US', 'France', 'S. Korea')

The reason is, in order to make such declaration, I need the list of all possible countries. But this list is not readily available to me and has to be obtained from finding the distinct values of -countryname- variable to start with. Thus having to add this extra line of declaration seems clumsy and unnecessary. It would appear appropriate to me that PostgreSQL have a function for an operation this.

To put it in another way, I am looking for something similar to the countryname.Parse() method (I guess?) in C, or a countryname.astype('category') method in pandas, that does the declaration and conversion in one step, like:

SELECT id CONVERTION_FUNCTION(countryname) FROM dataset
1

There are 1 answers

0
p3consulting On
with data(s) as (
  select 'US' union all 
  select 'France' union all
  select 'S. Korea' 
)
select s::countries  from data;

If you pass a string not part of the enum you will have:

ERROR:  invalid input value for enum countries: ...