What is MySQL JSON Data Type?
Last Updated :
04 Jul, 2024
The MySQL JSON data type is a significant advancement in database management, especially in meeting the needs of contemporary online applications that require dynamic and flexible data storage. JavaScript Object Notation, or JSON, is a widely used format for data transfer because it is easy to read, simple to use, and compatible with a wide range of platforms and programming languages
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format commonly used for representing structured data. It is easy for humans to read and write and easy for machines to parse and generate. JSON consists of key-value pairs enclosed in curly braces {}
, where keys are strings and values can be strings, numbers, arrays, or null.
Example JSON
{
"id": 1,
"name": "John Doe",
"email": "[email protected]",
"roles": ["admin", "user"]
}
MySQL JSON Data Type
The MySQL JSON data type was introduced in MySQL 5.7 as a native data type for storing JSON documents. It provides efficient storage and retrieval of JSON data along with built-in functions and operators for querying and manipulating JSON documents.
Features of MySQL JSON Data Type
- Efficient Storage: The JSON documents are stored in an optimized binary format resulting in the efficient use of the storage space.
- Indexing Support: MySQL allows indexing of the JSON columns using generated columns or virtual columns enabling fast retrieval of the JSON data.
- Querying and Manipulation: MySQL provides a set of JSON functions and operators for querying and manipulating JSON documents directly within the SQL statements.
- Schema-less Data: With the JSON data type MySQL allows the storing of schema-less or semi-structured data providing flexibility in the data storage.
Examples of MySQL JSON Data Type
Example 1
Creating a Table with JSON Column:
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(100),
details JSON
);
Inserting JSON Data:
INSERT INTO products (id, name, details)
VALUES (1, 'Product A', '{"price": 10, "category": "Electronics"}');
Output:
+----+-----------+------------------------------------------+
| id | name | details |
+----+-----------+------------------------------------------+
| 1 | Product A | {"price": 10, "category": "Electronics"} |
+----+-----------+------------------------------------------+
Querying JSON Data:
-- Retrieving product details
SELECT name, details->'$.price' AS price
FROM products
WHERE details->'$.category' = 'Electronics';
Output:
+-----------+-------+
| name | price |
+-----------+-------+
| Product A | 10 |
+-----------+-------+
Updating JSON Data:
-- Updating product details
UPDATE products
SET details = JSON_SET(details, '$.price', 15)
WHERE id = 1;
Output:
+----+-----------+------------------------------------------+
| id | name | details |
+----+-----------+------------------------------------------+
| 1 | Product A | {"price": 15, "category": "Electronics"} |
+----+-----------+------------------------------------------+
Indexing JSON Column:
-- Creating an index on JSON column
CREATE INDEX idx_category ON products ((details->'$.category'));
Example 2
Creating a Table with JSON Column
Let's create a table named employees
with a JSON column to store additional details about each employee.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
details JSON
);
Inserting JSON Data:
INSERT INTO employees (id, name, details)
VALUES
(1, 'Alice Smith', '{"age": 30, "department": "HR", "skills": ["recruiting", "communication"]}'),
(2, 'Bob Johnson', '{"age": 35, "department": "IT", "skills": ["programming", "networking"]}');
Output:
+----+-------------+----------------------------------------------------------------------------+
| id | name | details |
+----+-------------+----------------------------------------------------------------------------+
| 1 | Alice Smith | {"age": 30, "skills": ["recruiting", "communication"], "department": "HR"} |
| 2 | Bob Johnson | {"age": 35, "skills": ["programming", "networking"], "department": "IT"} |
+----+-------------+----------------------------------------------------------------------------+
Querying JSON Data:
Retrieve the names and departments of employees who have a specific skill:
SELECT name, details->'$.department' AS department
FROM employees
WHERE JSON_CONTAINS(details->'$.skills', '"programming"');
Output:
+-------------+------------+
| name | department |
+-------------+------------+
| Bob Johnson | "IT" |
+-------------+------------+
Updating JSON Data
Update the JSON data to add a new skill for an employee:
UPDATE employees
SET details = JSON_ARRAY_APPEND(details, '$.skills', 'management')
WHERE id = 1;
Querying to Verify the Update
Retrieve the updated details for the employee to verify the changes:
SELECT name, details
FROM employees
WHERE id = 1;
Expected Output:
+-------------+------------------------------------------------------------------------------------------+
| name | details |
+-------------+------------------------------------------------------------------------------------------+
| Alice Smith | {"age": 30, "skills": ["recruiting", "communication", "management"], "department": "HR"} |
+-------------+------------------------------------------------------------------------------------------+
Conclusion
The MySQL JSON data type heralds a new era in database management catering to the evolving needs of modern web applications. Its efficient storage, indexing support, querying, and manipulation capabilities make it a versatile choice for handling dynamic and flexible data structures. By embracing JSON MySQL empowers developers and administrators the unlock new possibilities in data storage and retrieval paving the way for enhanced performance and scalability.
Similar Reads
PostgreSQL - JSON Data Type
JSON (JavaScript Object Notation) is a widely used format for storing data in the form of key-value pairs. Its popularity comes from being easy for humans to read and understand, making it ideal for communication between servers and clients. This readability and ease of use have made JSON a standard
4 min read
What is MySQL?
MySQL is an open-source, relational database management system (RDBMS) that uses Structured Query Language (SQL) to manage and manipulate data. It is one of the most popular database systems used in web applications, known for its speed, reliability, and ease of use. MySQL is commonly used in conjun
5 min read
What is JSONB in PostgreSQL?
PostgreSQL is a powerful object-relational database management system that excels at handling structured and semi-structured data, especially through its support for JSONB. JSONB (Binary JSON) allows efficient storage and querying of JSON data and making it ideal for applications that require quick
5 min read
SQL Data Types
SQL Data Types are very important in relational databases. It ensures that data is stored efficiently and accurately. Data types define the type of value a column can hold, such as numbers, text, or dates. Understanding SQL Data Types is critical for database administrators, developers, and data ana
5 min read
PL/ SQL Data Types
PL/SQL (Procedural Language/Structured Query Language) is a procedural extension language for SQL used specifically for the Oracle database to ease the management of data and the flow of operations. A core feature of PL/SQL is its diverse set of data types, designed to handle everything from simple
6 min read
PostgreSQL - VARCHAR Data Type
In the world of relational databases, PostgreSQL stands out with its robust support for various data types, including the flexible VARCHAR data type. This character data type allows us to store strings of variable length, making it an essential choice for many applications.In this article, we will e
3 min read
MySQL Insert Date Time
In today's world, working with data is now a data-to-data activity, so therefore managing data with proper data and time is also crucial. MySQL provides functionalities to handle data and time properly in the database. Understanding how to insert data and time into MySQL database with functions prov
4 min read
DATETIME vs TIMESTAMP Data Type in MySQL?
When designing a database schema in MySQL, choosing the appropriate data type for storing date and time information is important. MySQL offers two primary data types for this purpose DATETIME and TIMESTAMP. Each has its characteristics and use cases and understanding these can help us make the right
6 min read
PHP | Inserting into MySQL database
Inserting data into a MySQL database using PHP is a crucial operation for many web applications. This process allows developers to dynamically manage and store data, whether it be user inputs, content management, or other data-driven tasks. In this article, We will learn about How to Inserting into
6 min read
MySQL JSON Functions
JSON functions in MySQL allow working with JSON data in the database and retrieve JSON data from it. These functions help in storing and accessing JSON data efficiently and such data is widely used in web applications as it is flexible and easy to use. In this article, We will learn about the MySQL
4 min read