Storing arrays in the database

丶灬走出姿态 提交于 2019-11-26 22:51:52

No, it's a terrible practice. Please refrain from inserting CSV, JSON*, serialize() or ANY kind of serialized data in a relational database. Denormalization is almost always a bad idea - don't do it unless you really know what you are doing, or you'll start asking questions like: this, this, this, this, ...

Doing that, you lose or it severely hinders your ability to:

  • Use JOINs.
  • Find or modify a particular element
  • Enforce referential integrity
  • Benefit from index usage
  • And it also wastes space

It may sound pedantic, but seeing people do this is one of my pet peeves - especially in light of the plethora of questions asked on SO that would be avoided if they did the right way.

Here's the right way to do one-to-many and many-to-many relationships in an RDBMS.

*Although some SQL databases have built-in support for JSON, it's often better to restructure your data so that you don't need this

Depends on your usage pattern. If you're going to need to access smaller portions of the array (e.g. for use in a where clause or similar), then it's a bad idea - you lose all the benefits of storing data in a relational database by making the data un-relatable. You'll end up with major overhead extracting that small piece of data over and over and over again.

On the other hand, if you're just using the database as a data store and never need to slice that stored array apart - just insert and retrieve, then there's probably no problem at all, other than maybe waste of space, as a serialized/json'd format tends to be "wordy" and take up more space than the raw data itself does.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!