← Back to Chapters

JSON Functions

? JSON Functions

? Quick Overview

MySQL provides powerful JSON functions to store, read, update, and manipulate JSON data directly inside database columns. These functions are widely used in modern applications where flexible schema and nested data structures are required.

? Key Concepts

  • JSON is stored using the JSON data type
  • Access JSON using path expressions like $.key
  • Functions allow read, update, search, and validation
  • Indexes can be created on generated JSON values

? Syntax / Theory

  • JSON_EXTRACT(json_doc, path)
  • -> and ->> operators
  • JSON_OBJECT(), JSON_ARRAY()
  • JSON_SET(), JSON_REPLACE(), JSON_REMOVE()

? Code Examples

? View Code Example
-- Creating table with JSON column
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
profile JSON
);
? View Code Example
-- Inserting JSON data
INSERT INTO employees VALUES
(1,'Amit','{"city":"Pune","skills":["SQL","Python"],"experience":5}');
? View Code Example
-- Reading JSON value using arrow operator
SELECT profile->>'$.city' AS city FROM employees;
? View Code Example
-- Extracting array from JSON
SELECT JSON_EXTRACT(profile,'$.skills') FROM employees;
? View Code Example
-- Updating JSON key value
UPDATE employees
SET profile = JSON_SET(profile,'$.city','Mumbai')
WHERE id = 1;

? Live Output / Explanation

Result Explanation

The JSON functions allow you to read nested values, update individual keys without rewriting entire JSON, and return structured data directly from queries.

? Interactive Example / Diagram

Think of JSON as a document inside a column where each key behaves like a mini-column. Paths like $.skills[0] directly access array values.

? Use Cases

  • Storing user preferences
  • Dynamic form data
  • API responses storage
  • Configuration and metadata

✅ Tips & Best Practices

  • Always validate JSON using JSON_VALID()
  • Create generated columns for indexing
  • Avoid deeply nested JSON for performance
  • Use ->> for scalar values

? Try It Yourself

  • Create a JSON column and store user address
  • Extract a nested value using path
  • Update one key without touching others
  • Create an index on a generated JSON column