Should I use blob or text for JSON in MySQL?

MysqlTextBlobMysql Json

Mysql Problem Overview


I am planning to store a json_encoded string on my database. I can't precisely tell the length its going to be, but I'm pretty sure it will be long. My concern is which field type I am going to use for this, is it blob or text?

I prefer the one where I can save space as much as possible over fast searching, in any case I have other column where I should just index.

Mysql Solutions


Solution 1 - Mysql

As stated in the documentation of MySQL, since 5.7.8 a native JSON data type is supported.

The JSON data type provides these advantages over storing JSON-format strings in a string column:

  • Automatic validation of JSON documents stored in JSON columns. Invalid documents produce an error.
  • Optimized storage format. JSON documents stored in JSON columns are converted to an internal format that permits quick read access to document elements. When the server later must read a JSON value stored in this binary format, the value need not be parsed from a text representation. The binary format is structured to enable the server to look up subobjects or nested values directly by key or array index without reading all values before or after them in the document.

So, as the MySQL documentation states, the JSON data type should be used and not the text.

Solution 2 - Mysql

blob is usually for things like images, binaries etc. text should be good enough for your case, or you can use longtext which has even bigger space capacity if that's really a concern.

Searching-wise, since you are storing json_encode'd stuff, you'll still need to call json_decode on it anyway for it to be useful in your application, I don't think choice of datatype matters in this case.

A better way is to normalize your database design instead of storing related stuff in one big string of json.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeandro GarciaView Question on Stackoverflow
Solution 1 - Mysqlcs04iz1View Answer on Stackoverflow
Solution 2 - MysqlAndreas WongView Answer on Stackoverflow