Table of Contents
1. Storing JSON Data in MySQL
Create a Table with a JSON Column
Insert JSON Data
2. Querying JSON Data
Extract Values Using -> and ->>
Search Within JSON
3. Updating JSON Fields
4. Indexing JSON Data (Indirectly)
Example: Index the Email Field Inside JSON
Best Practices
Home Database Mysql Tutorial How to Store JSON Data in MySQL and Query It?

How to Store JSON Data in MySQL and Query It?

Aug 08, 2025 pm 12:02 PM
mysql query json data

Using MySQL 5.7 and above, you can directly store and query JSON data through JSON data types; 2. Define JSON columns and insert legal JSON data when creating a table, and MySQL will automatically verify its validity; 3. Use the -> and ->> operators to extract JSON field values, among which ->> can be used to remove string quotations for comparison; 4. Search for JSON content in WHERE clauses through functions such as JSON_CONTAINS, CAST, etc., and note that numerical comparison requires type conversion; 5. Use the JSON_SET, JSON_REPLACE and JSON_REMOVE functions to modify the JSON field; 6. Although JSON columns cannot be directly indexed, indexes can be created by generating columns (such as virtual columns based on JSON_UNQUOTE) to improve query performance; 7. It is recommended to extract frequently queried fields into generated columns and establish indexes to avoid over-reliance on large JSON object queries, and maintain core data structure to achieve a balance of flexibility and performance.

How to Store JSON Data in MySQL and Query It?

Storing and querying JSON data in MySQL is straightforward if you're using MySQL 5.7 or later, as these versions have built-in support for JSON data types. This allows you to store semi-structed data flexible while still benefiting from SQL querying capabilities. Here's how to do it effectively.

How to Store JSON Data in MySQL and Query It?

1. Storing JSON Data in MySQL

To store JSON, use the JSON data type when defining a column in your table.

Create a Table with a JSON Column

 CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    profile JSON
);

Insert JSON Data

You can insert valid JSON objects or arrays:

How to Store JSON Data in MySQL and Query It?
 INSERT INTO users (name, profile) VALUES (
    'Alice',
    '{
        "age": 30,
        "city": "New York",
        "hobbies": ["reading", "cycling"],
        "contact": {
            "email": "alice@example.com",
            "phone": "123-456-7890"
        }
    }'
);

MySQL validates the JSON on insertion. Invalid JSON will cause an error.


2. Querying JSON Data

MySQL provides functions and operators to extract and search within JSON fields.

How to Store JSON Data in MySQL and Query It?

Extract Values Using -> and ->>

  • column->'$.path' returns the JSON value (with quotes for strings).
  • column->>'$.path' returns the unquoted, scalar value (better for comparisons).
 -- Get the full contact object
SELECT profile->'$.contact' AS contact FROM users WHERE name = 'Alice';

-- Get the unquoted email
SELECT profile->>'$.contact.email' AS email FROM users WHERE name = 'Alice';

-- Get age and city
SELECT 
    profile->>'$.age' AS age,
    profile->>'$.city' AS city
FROM users;

Search Within JSON

Use JSON_CONTAINS() or path expressions in WHERE clauses.

 -- Find users who have "cycling" in hobbies
SELECT name FROM users 
WHERE JSON_CONTAINS(profile->'$.hobbies', '"cycling"');

-- Find users older than 25
SELECT name FROM users 
WHERE CAST(profile->>'$.age' AS UNSIGNED) > 25;

-- Find users from New York
SELECT name FROM users 
WHERE profile->>'$.city' = 'New York';

Note: Since ->> returns text, you may need to cast values (eg, to SIGNED , UNSIGNED , or DECIMAL ) for numeric comparisons.


3. Updating JSON Fields

Use JSON_SET() , JSON_REPLACE() , or JSON_REMOVE() to modify JSON content.

 -- Add or update a field
UPDATE users 
SET profile = JSON_SET(profile, '$.age', 31, '$.city', 'Boston')
WHERE name = 'Alice';

-- Append to an array
UPDATE users 
SET profile = JSON_ARRAY_APPEND(profile, '$.hobbies', 'swimming')
WHERE name = 'Alice';

-- Remove a field
UPDATE users 
SET profile = JSON_REMOVE(profile, '$.contact.phone')
WHERE name = 'Alice';

4. Indexing JSON Data (Indirectly)

You cannot directly index a JSON column , but you can create generated (virtual) columns and index those.

Example: Index the Email Field Inside JSON

 ALTER TABLE users 
ADD COLUMN email VARCHAR(255) 
GENERATED ALWAYS AS (JSON_UNQUOTE(profile->>'$.contact.email')));

CREATE INDEX idx_email ON users(email);

Now queries filtering on email can use the index:

 SELECT name FROM users WHERE email = 'alice@example.com';

This greatly improves performance for frequent JSON-based looksups.


Best Practices

  • Use JSON for flexible or optional attributes (eg, user preferences, settings).
  • Keep frequently queried or critical fields (like email, status) as regular columns or use generated columns with indexes.
  • Avoid storing large JSON blobs if you query them often—normalize when possible.
  • Validate JSON structure in your application to prevent errors.

Storing JSON in MySQL gives you flexibility without sacrificing too much performance—especially when you combine it with generated columns and proper indexing. It's ideal for evolving schemas or hierarchical data that don't fit neatly into rigid tables.

The above is the detailed content of How to Store JSON Data in MySQL and Query It?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1585
276
PHP development tips: How to use Redis to cache MySQL query results PHP development tips: How to use Redis to cache MySQL query results Jul 02, 2023 pm 03:30 PM

PHP development tips: How to use Redis to cache MySQL query results Introduction: In the process of web development, database query is one of the common operations. However, frequent database queries can cause performance issues and affect the loading speed of web pages. In order to improve query efficiency, we can use Redis as a cache and put frequently queried data into Redis, thereby reducing the number of queries to MySQL and improving the response speed of web pages. This article will introduce the development of how to use Redis to cache MySQL query results.

How do PHP and MySQL handle JSON data? How do PHP and MySQL handle JSON data? Jul 12, 2023 am 10:00 AM

How do PHP and MySQL handle JSON data? In modern web applications, JSON (JavaScriptObjectNotation) is often used to store and exchange data. PHP and MySQL are two commonly used technologies, and how to use them to process JSON data is a common question. This article will introduce how to use PHP and MySQL to process JSON data and provide some code examples. 1. Export data from MySQL to JSON First, let’s

PHP development tips: How to use Memcached to cache MySQL query results PHP development tips: How to use Memcached to cache MySQL query results Jul 02, 2023 am 08:48 AM

PHP development tips: How to use Memcached to cache MySQL query results Memcached is a high-performance distributed memory object caching system that can be used to reduce the load on the database and improve application performance. In PHP development, we often encounter situations where we need to query the database frequently. At this time, using Memcached to cache query results can greatly improve the response speed of the system. This article will share how to use Memcached to cache MySQL query results

How to parse incoming JSON data using request body in FastAPI How to parse incoming JSON data using request body in FastAPI Jul 28, 2023 pm 04:17 PM

How to parse incoming JSON data using request body in FastAPI FastAPI is a modern Python-based web framework that provides rich functionality and high-performance asynchronous support. When using FastAPI to handle HTTP requests, it is often necessary to parse the incoming JSON data. This article will introduce how to use the request body to parse incoming JSON data in FastAPI and provide corresponding code examples. Import dependencies First, we need to import FastAPI dependencies and JS

PHP development tips: How to use Xcache to cache MySQL query results PHP development tips: How to use Xcache to cache MySQL query results Jul 02, 2023 pm 05:33 PM

PHP development tips: How to use Xcache to cache MySQL query results Introduction: In web applications, we often need to perform a large number of database query operations. These query operations may consume a lot of system resources and time. To improve performance and reduce load on the server, we can use caching to store and reuse query results. In this article, we will discuss how to use the Xcache extension to cache MySQL query results to improve the responsiveness and performance of your web applications. Introduction to Xcache

Data query implementation technology in MySQL Data query implementation technology in MySQL Jun 14, 2023 am 11:04 AM

MySQL is one of the most popular relational database systems today. It has the characteristics of high performance, security, and scalability, and is widely used in data management work in various industries. Among them, data query is one of the most basic operations of MySQL, and it is also something we often come into contact with in daily development. This article will introduce the technology of data query implementation in MySQL, including the use of SQL statements, indexing, optimization, etc., to help everyone better master the data query technology of MySQL. The use of SQL statements SQL is a structured query language (St

How to create high-performance MySQL data query operations using Go language How to create high-performance MySQL data query operations using Go language Jun 17, 2023 am 08:42 AM

In modern software development, data processing and query operations are essential. As a relational database management system, MySQL plays an important role in most enterprise-level applications. As an efficient and fast programming language, Go language is increasingly used in data processing and query operations. This article will introduce how to use Go language to create high-performance MySQL data query operations, including database connection, query statement construction and execution, etc. 1. Database connection using Go language to operate MySQL

Solution to the problem that the PHP interface cannot return data in JSON format Solution to the problem that the PHP interface cannot return data in JSON format Mar 12, 2024 pm 05:45 PM

Solution to the problem that the PHP interface cannot return JSON format data. During the development process, we often encounter situations where we need to use the PHP interface to return JSON format data. However, sometimes you may encounter problems that cannot correctly return JSON format data. This article will introduce some solutions and give specific code examples. Problem Analysis When we use PHP to write interfaces, we usually need to convert data into JSON format and return it to the front-end page or other applications. But sometimes, we may encounter the following problems: Interface

See all articles