12

Is it possible insert more than one ENUM value in a column in postgres?

e.g. In Mysql, I can do.

create table 'foo'(
    'foo_id' smallint(5) unsigned NOT NULL AUTO_INCREMENT,
    `foo_enum` enum('foo','bar','dummy') DEFAULT 'foo',
);

insert into 'foo' ('foo_id', 'foo_enum') values (1, 'foo, bar')
1
  • Your syntax is totally wrong. An identifier (column name, table name) neither needs ' nor that stupid backtick from MySQL. 'foo' is not a table name. It's string literal (even with MySQL). Commented Feb 25, 2013 at 18:09

1 Answer 1

29

You can use CREATE TYPE to declare your enum:

CREATE TYPE tfoo AS ENUM('foo','bar','dummy');

And use an array of it to store the values:

CREATE TABLE foo (foo_id serial, foo_enum tfoo[]);

To insert:

INSERT INTO foo(foo_enum) VALUES('{foo,bar}');

Or

INSERT INTO foo(foo_enum) VALUES(ARRAY['foo','bar']::tfoo[]);

Another approach would be using another table to store the enums and a foreign key to the foo table. Example:

CREATE TABLE foo (foo_id serial primary key);
CREATE TABLE foo_enums (foo_id integer references foo(foo_id), value tfoo);

And them insert the multiple values into foo_enums:

INSERT INTO foo(foo_id) VALUES(nextval('foo_id_seq'));
INSERT INTO foo_enums(foo_id, value) VALUES
    (currval('foo_id_seq'), 'foo'),
    (currval('foo_id_seq'), 'bar');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.