You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
5 Hrs
13 Min
47 Seg
Curso de SQL y MySQL

Curso de SQL y MySQL

Genaro Bernardino

Genaro Bernardino

Uso de JSON en MySQL: Almacenamiento Eficiente de Datos Estructurados

11/19
Resources

The JSON format has become an indispensable standard for data handling in modern applications. Although it originally emerged from the JavaScript ecosystem, today its presence is ubiquitous in software development. In the context of databases, JSON offers extraordinary flexibility, but it requires in-depth knowledge to take advantage of its benefits without falling into inefficient practices. Let's see how MySQL has incorporated this data type and how we can use it correctly.

What is JSON and why is it important in databases?

JSON (JavaScript Object Notation) is a data interchange format that allows storing structured information in a flexible way. In the world of databases, there are two main families:

  • Relational databases: MySQL, Oracle, PostgreSQL, etc. They organize information in tables with a defined structure.
  • Document databases: They store documents (similar to JSON objects) where information is organized hierarchically.

Although these approaches were traditionally considered mutually exclusive, MySQL revolutionized its approach in 2017 by incorporating the JSON data type, allowing to combine the best of both worlds. This decision, while controversial to some purists, offers unprecedented flexibility when used correctly.

The key is understanding when to use JSON columns. They are ideal for data that:

  • Are not always present
  • Have variable structure
  • Don't need to be queried frequently on an individual basis

For example, in an online store, we might use JSON to store product-specific characteristics such as brand, size, or color, which vary by product type.

How to implement and manipulate JSON columns in MySQL?

Creating JSON columns

To add a JSON column to an existing table, we use the standard ALTER TABLE syntax:

ALTER TABLE productsADD COLUMN data JSON AFTER price;

This statement creates a column named "data" of type JSON after the "price" column.

Types of values in JSON

MySQL allows to store several types of data inside a JSON object:

  • Objects: key-value pairs {"brand": "Apple", "size": "L"}
  • Arrays: Lists of values [1, 2, 3].
  • Strings: Text in quotes "Hello, how are you?"
  • Numbers: Integer or float 42 or 3.14
  • Booleans: true or false
  • Null: Null value null

It is important to note that for data requiring decimal precision (such as monetary values), it is not recommended to use JSON. In these cases, it is better to use specific types such as DECIMAL or DOUBLE.

Inserting JSON data

We can insert JSON data directly as text, and MySQL will take care of validating and storing it in an optimized way:

UPDATE productsSET data = '{"brand": "Pear", "HDSize": "40 gigabytes"}'WHERE product_id = 10;

Modifying JSON data

MySQL provides three main functions for manipulating JSON data:

  1. JSON_REPLACE: Replaces existing values.
UPDATE productsSET data = JSON_REPLACE(data, '$.brand', 'Banana')WHERE product_id = 10;
  1. JSON_REMOVE: Remove items
UPDATE productsSET data = JSON_REMOVE(data, '$.HDSize')WHERE product_id = 10;
  1. JSON_SET: Add or update items
UPDATE productsSET data = JSON_SET(data, '$.color', 'black')WHERE product_id = 10;

It is crucial to understand that these functions do not directly modify the JSON column, but return a new modified JSON object. That is why we must assign the result to the column with an UPDATE.

Navigation in JSON documents

To access elements within a JSON, MySQL uses a path notation:

  • $: Represents the root of the document
  • $.property: Accesses a property of the root object
  • $[n]: Accesses element n of an array
  • $[*]: Represents all the elements of an array

For example, $.brand accesses the value of the "brand" property in the root object.

What are the best practices when using JSON in MySQL?

When working with JSON columns in MySQL, it is important to consider:

  1. Selective use: not everything should go in JSON. Data that needs to be indexed or queried frequently should be in regular columns.

  2. Consistent structure: Although JSON allows flexibility, maintaining some consistency in structure makes queries easier.

  3. Performance: Operations on JSON can be more expensive than on traditional columns, especially in searches.

  4. Validation: MySQL automatically validates that the JSON is correct before storing it.

  5. Numeric precision: For values that require exact decimal precision (such as financial data), use specific columns instead of JSON.

The JSON data type in MySQL represents a bridge between the relational and documentary worlds, offering flexibility without sacrificing the advantages of relational databases. By properly using the JSON_REPLACE, JSON_REMOVE and JSON_SET functions, we can efficiently manipulate this complex data. In upcoming lessons, we will explore how to efficiently search within JSON columns and how to implement indexes to optimize performance, overcoming one of the traditional limitations of this data type.

Have you used JSON columns in your projects and what advantages or challenges have you encountered? Share your experience in the comments.

Contributions 0

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?