Back to Curriculum

MySQL JSON Support

📚 Lesson 13 of 15 ⏱️ 35 min

MySQL JSON Support

35 min

MySQL 5.7+ provides native JSON data type support, enabling storage and querying of JSON documents within relational databases. JSON support enables hybrid data models where some data is relational and some is semi-structured. This flexibility is valuable for applications with evolving schemas, user-defined attributes, or data that doesn't fit neatly into relational tables. Understanding JSON support enables you to leverage both relational and document-based data models.

JSON columns store JSON documents efficiently with automatic validation. MySQL validates JSON data when inserting or updating, ensuring only valid JSON is stored. JSON data is stored in an optimized binary format, enabling efficient storage and retrieval. JSON columns can be indexed using generated columns, enabling fast JSON queries. Understanding JSON storage enables effective use of JSON data.

JSON functions enable extracting, modifying, and querying JSON data. JSON_EXTRACT (or -> operator) extracts values from JSON, JSON_SET modifies JSON values, JSON_INSERT adds new values, JSON_REPLACE replaces values, and JSON_REMOVE removes values. JSON functions enable powerful JSON manipulation within SQL queries. Understanding JSON functions enables sophisticated JSON data processing.

JSON path expressions specify locations within JSON documents. Paths use $ for root, . for object properties, [] for array indices, and * for wildcards. Path expressions enable precise JSON data access. Understanding JSON paths enables effective JSON querying.

JSON indexes can be created using generated columns that extract values from JSON. Generated columns compute values from JSON using JSON functions, and these columns can be indexed normally. This enables fast queries on JSON data. Understanding JSON indexing enables performance optimization for JSON queries.

Best practices for JSON include using JSON for truly variable or semi-structured data, creating indexes on frequently queried JSON paths, and understanding when to use JSON vs normalized relational design. While JSON is powerful, overusing it for structured data can reduce query performance and data integrity compared to proper relational design. Understanding best practices enables effective JSON usage.

Key Concepts

  • MySQL provides native JSON data type support.
  • JSON columns store validated JSON documents efficiently.
  • JSON functions enable extracting, modifying, and querying JSON data.
  • JSON path expressions specify locations within JSON documents.
  • JSON indexes can be created using generated columns.

Learning Objectives

Master

  • Creating tables with JSON columns
  • Using JSON functions to manipulate JSON data
  • Querying JSON data with path expressions
  • Creating indexes on JSON data

Develop

  • Understanding hybrid relational/JSON data models
  • Designing flexible database schemas
  • Optimizing JSON query performance

Tips

  • Extract JSON: JSON_EXTRACT(column, '$.path') or column->'$.path'.
  • Set JSON value: JSON_SET(column, '$.path', value) to modify JSON.
  • Query JSON: WHERE JSON_EXTRACT(column, '$.field') = 'value'.
  • Create JSON index: ALTER TABLE ADD COLUMN field_extracted VARCHAR(255) GENERATED ALWAYS AS (JSON_EXTRACT(json_column, '$.field')) STORED, ADD INDEX (field_extracted);

Common Pitfalls

  • Not indexing JSON paths, causing slow JSON queries.
  • Storing all data in JSON when relational design would be better.
  • Not understanding JSON path syntax, writing incorrect queries.
  • Not validating JSON structure, causing query errors.

Summary

  • MySQL JSON support enables hybrid relational/JSON data models.
  • JSON functions enable powerful JSON data manipulation.
  • JSON indexes enable fast JSON queries.
  • Understanding JSON support enables flexible schema design.

Exercise

Work with JSON data types and functions in MySQL.

-- Create table with JSON column
CREATE TABLE user_profiles (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    profile_data JSON,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert JSON data
INSERT INTO user_profiles (user_id, profile_data) VALUES
(1, JSON_OBJECT('name', 'John Doe', 'age', 30, 'interests', JSON_ARRAY('reading', 'coding'))),
(2, JSON_OBJECT('name', 'Jane Smith', 'age', 25, 'interests', JSON_ARRAY('music', 'travel')));

-- Query JSON data
SELECT 
    user_id,
    JSON_EXTRACT(profile_data, '$.name') as name,
    JSON_EXTRACT(profile_data, '$.age') as age,
    JSON_EXTRACT(profile_data, '$.interests') as interests
FROM user_profiles;

-- Update JSON data
UPDATE user_profiles 
SET profile_data = JSON_SET(profile_data, '$.age', 31)
WHERE user_id = 1;

-- Add new field to JSON
UPDATE user_profiles 
SET profile_data = JSON_MERGE(profile_data, '{"location": "New York"}')
WHERE user_id = 1;

-- Query with JSON conditions
SELECT * FROM user_profiles 
WHERE JSON_EXTRACT(profile_data, '$.age') > 25;

-- Search in JSON arrays
SELECT * FROM user_profiles 
WHERE JSON_CONTAINS(profile_data->'$.interests', '"coding"');

-- Aggregate JSON data
SELECT 
    JSON_OBJECT('total_users', COUNT(*), 'avg_age', AVG(JSON_EXTRACT(profile_data, '$.age'))) as stats
FROM user_profiles;

Exercise Tips

  • Use -> operator: column->'$.path' is shorthand for JSON_EXTRACT(column, '$.path').
  • Use JSON_CONTAINS for array searches: JSON_CONTAINS(column->'$.array', 'value').
  • Create generated columns for JSON indexes: improve JSON query performance.
  • Validate JSON: MySQL automatically validates JSON on insert/update.

Code Editor

Output