2

I want to use ENUM feature in table using MySQL.

I have created a table tbl_test having id as primary key and enum_col field as ENUM data type.

CREATE TABLE tbl_test(
id INT NOT NULL AUTO_INCREMENT,
enum_col ENUM('a','b','c') NOT NULL,
PRIMARY KEY ( id )
);

When I try to store single enum value, it got inserted but when I try to store multiple enum values then it throws SQL error.

ERROR:

 Data truncated for column 'enum_col' at row 1

Single ENUM value (CORRECT):

INSERT INTO tbl_test(id, enum_col) values(1, 'a');

Multiple ENUM values (FAILED):

INSERT INTO tbl_test(id, enum_col) values(2, 'a,b');

Any idea to store multiple values in ENUM data type ?

1
  • ENUM is a value type, not a set or array type. Instead of storing arrays of values, it would be better to normalize your data so that all the normal querying and integrity features in MySQL can be used. Commented Jul 11, 2016 at 11:03

2 Answers 2

4

You should use SET data type instead of ENUM if you want to store multiple values

http://dev.mysql.com/doc/refman/5.7/en/set.html

Sign up to request clarification or add additional context in comments.

3 Comments

It's look nice solution.
i changed enum to set - i have problem with create and edit page ! create not saved and edit doesn't show data from database !
@Saltern sounds a bit confusing ) I trying to imaging a kind of problem that You faced with, but there is evidently not enough details in Your comment...
3

That is because you can only store one value in it and in fact you absolutely should store only one value in whatever type of column.

Use a seperate table. Then you can store as much values as you like with multiple records. Example:

tbl_test
--------
id   |  name
1    |  test_X
2    |  test_Y
3    |  test_Z


tbl_test_enums
--------------
test_id  | enum_value
1        | a
1        | b
2        | a
3        | c

3 Comments

Thanks. @juergen. Is it be well, if I use SET instead of ENUM because values are not duplicated ?
Never store multiple values in a single column! Just don't. It is bad for performance and poor table design.

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.