Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: what data type should I use for a string of comma separated values?

Tags:

types

mysql

I need to store a string of comma separated values.

'1,23,47' or '1' or '' (null)

What data type would work best for comma separated values?

Note: I am only asking which data type would be appropriate for this scenario.

like image 536
Andrew Avatar asked Dec 17 '09 04:12

Andrew


People also ask

How do I display comma separated values in MySQL?

In MySQL, you can return your query results as a comma separated list by using the GROUP_CONCAT() function. The GROUP_CONCAT() function was built specifically for the purpose of concatenating a query's result set into a list separated by either a comma, or a delimiter of your choice.

What is the data type for string in MySQL?

The string data types are CHAR , VARCHAR , BINARY , VARBINARY , BLOB , TEXT , ENUM , and SET . In some cases, MySQL may change a string column to a type different from that given in a CREATE TABLE or ALTER TABLE statement.


4 Answers

Depending on how big the string you expect world determine the size of varchar. If you have no idea how long the string would be you can just use TEXT data type.

like image 161
Luke101 Avatar answered Dec 07 '22 23:12

Luke101


Literal answer: a VARCHAR of some sort

A better answer: Don't store a list of comma separated values. Store one value per row, and use a SELECT query with GROUP_CONCAT to generate the comma separated value when you access the database.

like image 23
Jason S Avatar answered Dec 07 '22 22:12

Jason S


VARCHAR, it can store anything.

TEXT if you think it will be long.

like image 29
ari_aaron Avatar answered Dec 07 '22 23:12

ari_aaron


If you will never need to query specific sub-items in the list of values, then use varchar. However, if you will need to query the values I strongly recommend you consider a different database design, such as a value table where each row contains a join key to the main table and a single value.

like image 39
Jim Garrison Avatar answered Dec 07 '22 22:12

Jim Garrison