Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select value from an enumerated list in PostgreSQL

I want to select from an enumaration that is not in database.

E.g. SELECT id FROM my_table returns values like 1, 2, 3 I want to display 1 -> 'chocolate', 2 -> 'coconut', 3 -> 'pizza' etc. SELECT CASE works but is too complicated and hard to overview for many values. I think of something like

SELECT id, array['chocolate','coconut','pizza'][id] FROM my_table

But I couldn't succeed with arrays. Is there an easy solution? So this is a simple query, not a plpgsql script or something like that.

like image 989
Turtle Avatar asked Apr 04 '13 14:04

Turtle


People also ask

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.

How do I select a variable in PostgreSQL?

In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.

What is enumerated type in PostgreSQL?

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 do a wildcard search in PostgreSQL?

PostgreSQL provides you with two wildcards: Percent sign ( % ) matches any sequence of zero or more characters. Underscore sign ( _ ) matches any single character.


2 Answers

This is the correct syntax:

SELECT id, (array['chocolate','coconut','pizza'])[id] FROM my_table

But you should create a referenced table with those values.

like image 105
Clodoaldo Neto Avatar answered Sep 18 '22 13:09

Clodoaldo Neto


with food (fid, name) as (
  values 
     (1, 'chocolate'),
     (2, 'coconut'),
     (3, 'pizza')
)
select t.id, f.name
from my_table t
  join food f on f.fid = t.id;

or without a CTE (but using the same idea):

select t.id, f.name
from my_table t
  join (
     values 
       (1, 'chocolate'),
       (2, 'coconut'),
       (3, 'pizza')
  ) f (fid, name) on f.fid = t.id;
like image 23
a_horse_with_no_name Avatar answered Sep 20 '22 13:09

a_horse_with_no_name