Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an Integer to Enum in PostgreSQL

I have created a custom data type enum like so:

create type "bnfunctionstype" as enum ( 
    'normal', 
    'library', 
    'import', 
    'thunk', 
    'adjustor_thunk' 
);

From an external data source I get integers in the range [0,4]. I'd like to convert these integers to their corresponding enum values.

How can I do this?

I'm using PostgreSQL 8.4.

like image 486
BuschnicK Avatar asked Dec 01 '09 15:12

BuschnicK


People also ask

Does PostgreSQL have enum?

PostgreSQL enum is the data type that was used in PostgreSQL to stored same type of values in column field, we can store same type of values using enum.

How do enums work in Postgres?

Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.

How do I create an enum in SQL?

In MySQL one can create an enum as such: USE WorldofWarcraft; CREATE TABLE [users] ( ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, username varchar(255), password varchar(255), mail varchar (255), rank ENUM ('Fresh meat', 'Intern','Janitor','Lieutenant','Supreme being')DEFAULT 'Fresh meat', );

How do I select enum type in PostgreSQL?

Enumerated types can be selected in the same way as standard data types. You can pick the Enum type from the datatype drop-down. Tip: A default value can be defined for the column. Expand the column detail by clicking the arrow icon and specify the value in the Default value field.


1 Answers

If you have an enum like this:

CREATE TYPE payment_status AS ENUM ('preview', 'pending', 'paid', 
                                    'reviewing', 'confirmed', 'cancelled');

You can create a list of valid items like this:

SELECT i, (enum_range(NULL::payment_status))[i] 
  FROM generate_series(1, array_length(enum_range(NULL::payment_status), 1)) i

Which gives:

 i | enum_range 
---+------------
 1 | preview
 2 | pending
 3 | paid
 4 | reviewing
 5 | confirmed
 6 | cancelled
(6 rows)
like image 64
Johan Dahlin Avatar answered Oct 06 '22 13:10

Johan Dahlin