Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store array of numbers in database field

Context: SQL Server 2008, C#

I have an array of integers (0-10 elements). Data doesn't change often, but is retrieved often.

I could create a separate table to store the numbers, but for some reason it feels like that wouldn't be optimal.

Question #1: Should I store my array in a separate table? Please give reasons for one way or the other.

Question #2: (regardless of what the answer to Q#1 is), what's the "best" way to store int[] in database field? XML? JSON? CSV?

EDIT: Some background: numbers being stored are just some coefficients that don't participate in any relationship, and are always used as an array (i.e. never a value is being retrieved or used in isolation).

like image 791
THX-1138 Avatar asked Mar 17 '11 15:03

THX-1138


People also ask

Can you store arrays in a database?

Storing arrays is not a big problem in itself: assuming simple data types, like integers, we can easily adopt the workaround of using a VARCHAR/TEXT column to store the values with an arbitrary separator (space is the most convenient), however, MySQL is (was) not designed to index this scenario.

How do I store an array of numbers in SQL?

Store it as a comma separated list of values. Use a separate table and store one value per row, with a foreign key pointing back to your table.

Can we store array in SQL column?

Conclusion. As you can see, SQL Server does not include arrays. But we can use table variables, temporary tables or the STRING_SPLIT function. However, the STRING_SPLIT function is new and can be used only on SQL Server 2016 or later versions.

How do you add an array to a database?

The following code will help to create a PHP function to insert array PHP data into MySQL. For Ex. We have following PHP array. $records = array( "0" => array("Parvez", "PHP", "12"), "1" => array("Devid", "Java", "34"), "2" => array("Ajay", "Nodejs", "22") );


2 Answers

Separate table, normalized

Not as XML or json , but separate numbers in separate rows

No matter what you think, it's the best way. You can thank me later

like image 118
gbn Avatar answered Sep 30 '22 20:09

gbn


The "best" way to store data in a database is the way that is most conducive to the operations that will be performed on it and the one which makes maintenance easiest. It is this later requirement which should lead you to a normalized solution which means storing the integers in a table with a relationship. Beyond being easier to update, it is easier for the next developer that comes after you to understand what and how the information is stored.

like image 25
Thomas Avatar answered Sep 30 '22 21:09

Thomas