MySQL: O Tipo de Dados JSON e o NoSQL

MySQL: The JSON Data Type and NoSQL

data

JSON is a practical way, in plain text format, to exchange data regardless of programming language or platform. JSON is like a CSV file on steroids, or a more compact XML. From time to time, an evolution of files, protocols, or data exchange methods arises. JSON is one of those evolutions.

What does JSON mean? JavaScript Object Notation… Hmm… if it has “java” in the name… A Tibetan monk once said: “Java is the best way to create an application that runs on any platform, but slower and with more crashes.” I am a technician, not a philosopher. But the fact is that JSON (pronounced Djei Zon) has gained followers and is one of the ways to exchange data between applications, servers, platforms, etc. Therefore, it deserves an exclusive data type.

MySQL has implemented typing, or the JSON data type, since version 5.7. Other relational databases also implement, in some way and/or level, the JSON format (type). But I believe the best implementation is still the one made by MySQL.

Some technical considerations about JSON implementation in MySQL:

  • Strings submitted to a JSON column are validated; if their formatting does not comply with RFC7159, an error will be returned and the data will not be stored in the column;
  • Properly formatted strings that constitute JSON are converted to an internal binary format that allows working with JSON (now called a document). This enables indirect indexing and smarter, faster searches;
  • There are several functions that extend the functionalities available to developers (and database administrators);

For those who were on Scarif in the last 5 years and never saw a “Jason” in front of them, it looks like this:

{"Sakila Forever", "8.0", 2020, false, null}

Or

{ "Product_ID": "0001", "Name": "Notebook XPTO", "Brand": "Apple"}

Note that a JSON document or array, ultimately, is just a “string.” Which can easily be misformatted. That is why MySQL validates this “string” when it is inserted into a JSON column.

Theoretical definition: A JSON “string” or document consists of a series of pairs known as Key/Value. The Key is separated from its value by a colon, and each key/value pair is separated from the others by commas. A complete “string” (document, or record if you prefer) is enclosed within curly braces.

data

Warming up, we will create a table with a JSON column:

CREATE TABLE `JTable` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `JColumn` json DEFAULT NULL,
  UNIQUE KEY `id` (`id`)
);

Let’s test MySQL to make sure it won’t accept poorly formatted “strings”:

INSERT INTO JTable VALUES (NULL, 'Testing 1… 2… 3…');
ERROR 3140 (22032): Invalid JSON text: “Invalid value.” at position 0 in value for column ‘MyJSON_table.JColumn’

Very good, at first glance, MySQL rejected the “string” submitted to the JColumn column (data type: JSON), since it cannot be transformed into a valid JSON document.

This time, let’s try with valid JSON documents (properly formatted strings):

INSERT INTO JTable VALUES (NULL, '{"Product_ID": "MEM1TB", "Description": "Memory Card 1TB", "Group": "Memory"}');

Query OK, 1 row affected (0.00 sec)

INSERT INTO JTable VALUES (NULL, '{"Product_ID": "HDD1TB", "Description": "Disk Drive 1TB 7200 RPM", "Group": "Disk Drives"}');

Query OK, 1 row affected (0.00 sec)

INSERT INTO JTable VALUES (NULL, '{"Product_ID": "HDD2TB", "Description": "Disk Drive 2TB 7200 RPM", "Group": "Disk Drives", "Brand": "Seagate"}');

Query OK, 1 row affected (0.00 sec)

INSERT INTO JTable VALUES (NULL, '{"Available": "YES", "Online_Sales": "YES", "Description": "Disk Drive 4TB 7200 RPM", "Group": "Disk Drives", "Brand": "Seagate", "Product_ID": "HDD472"}');

Query OK, 1 row affected (0.00 sec)

INSERT INTO JTable VALUES (NULL, '{"Available": "YES", "Online_Sales": "YES", "Description": "Disk Drive 4TB 10K RPM", "Group": "Open Box", "Brand": "Western Digital", "Product_ID": "HD41TB"}');

Query OK, 1 row affected (0.00 sec)

Wow! It really works!

data

Notice that in the first two INSERTs I used the following keys: Product_ID, Description, and Group.

In the third INSERT, business needs changed and I included the key: Brand.

In the 5th and last INSERT, I deliberately changed the order of the keys. At this point, why not associate a key with our good old column?

Associating new things with familiar things is a widely used way to reduce the learning curve. And I see no problem associating a JSON document or “string” with a record, and the keys with columns.

Welcome to the wonderful and chaotic world of NoSQL. Columns are created with every new document (row or record). It is a world where normalization makes no sense. We can have 1,000 records with 1,000 different models. Without the need for “ALTER TABLE.”

And what happens to documents (rows or records) that don’t have the new keys (columns) implemented? Ready for the answer? Be careful… Don’t continue reading if you don’t want your life radically changed:

Nothing happens! (I would use another phrase, but Oracle would get very angry)

Rows prior to the implementation of a certain key (column) continue their life without that or those new keys.

Very good! In this article, we learned (I hope) what JSON is, in theory and practice: how to create JSON columns, and how to insert documents (rows or records).

In the next article, we will manipulate this data.

Schedule a meeting here

Visit our Blog

Learn more about databases

Learn about monitoring with advanced tools

data

Have questions about our services? Visit our FAQ

Want to see how we’ve helped other companies? Check out what our clients say in these testimonials!

Discover the History of HTI Tecnologia

Compartilhar:

Quem somos

Somos especialistas em otimizar e proteger bancos de dados. Evoluímos para oferecer as soluções mais inovadoras em consultoria, monitoramento e sustentação de sistemas de dados. Nosso compromisso é garantir que sua infraestrutura tecnológica proporcione vantagens estratégicas.

Acesse a página

Compromisso com a Inovação

Foco na Segurança

Parcerias Estratégicas

Soluções Personalizadas

Expertise Comprovada

Nossa História

Mergulhe na nossa jornada, conheça os marcos que definiram nosso caminho e descubra como nos tornamos líderes em tecnologia da informação.

Acesse a página

Blog

Nossos especialistas compartilham estratégias e práticas recomendadas para otimizar a gestão dos seus dados, garantindo segurança, eficiência e inovação.

Acesse a página

FAQ

Tem dúvidas sobre nossos serviços? Confira nossa seção de Perguntas Frequentes para obter respostas detalhadas sobre sustentação, monitoramento e consultoria de banco de dados.

Acesse a página

Sustentação

Monitoramento

Consultoria

Testemunhos

Nossos clientes destacam nossa dedicação, expertise e a qualidade das soluções oferecidas, reforçando nosso compromisso com a excelência e a inovação.

Acesse a página