Is it possible cast enum to integer? Starting from 1 the first element
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
While you can’t cast enum to integer as Catcall explained, you can use the PostgreSQL-specific and possibly not-version-to-version compatible
pg_enumsystem catalog table to get an ordinal representation.This looks easy, but it isn’t. Observe:
From this you can see that
enumsortorderprovides ordering, but no fixed ‘distance’. If support for removing values from enums is ever added, it’ll likely create ‘holes’ in the sequence, too.To get the enum position you’ll need to use the
row_number()window function to get the ordering, and thepg_typeofto get theoid(regtype) of the enum type. You need this to make sure that you return the right ordinal when there are multiple enums with the same label.This function does the job:
Note:
STABLEnotIMMUTABLE, because adding (or if support in Pg is later added, removing) values from enums would change the ordering and break indexes relying on the ordering; soSTRICTbecause it should return null for a null inputYou can now use this function to
CREATE CASTfor specific enums tointeger. You cannot create a generic cast for all enums tointeger, because theanyenumpseudo-type cannot be used for casts. For example, if I want to allow the demohappinessto be cast to integer, I would write:after which I could successfully execute:
Note that this is probably an insane thing to do, is unsupported, and is quite likely a terrible idea. Your code must be aware that the ordinal values will change when you add or (if later supported) remove a value from the enum.
Indexes created based on this cast (only possible if the function is defined immutable) will begin producing crazy and wrong results if you change the definition of the enum (except by appending new values to the end of it) because PostgreSQL believes you when you say a function is immutable. Don’t do that.