MySQL: JSON Functions: Concept
Module: Database-Specific Features
MySQL JSON type (5.7+) stores and validates JSON data with rich functions for querying and manipulation. Key features: (1) Native JSON type: Validates on INSERT, stores as binary (faster than TEXT). (2) Extraction: -> gets JSON, ->> gets text, $.path for nested data. (3) Modification: JSON_SET() updates, JSON_INSERT() adds, JSON_REMOVE() deletes. (4) Creation: JSON_OBJECT() creates objects, JSON_ARRAY() creates arrays. (5) Indexing: Generated columns + indexes for fast queries (100x faster). Real-world: Shopify uses JSON for product attributes. Slack uses JSON for user preferences. Trade-off: Slower than PostgreSQL JSONB (text vs binary) but simpler than normalized tables.
**1. JSON Type - Native JSON Support:**
MySQL 5.7+ supports native JSON type with validation and binary storage.
**JSON vs TEXT:**
- **JSON**: Validated on INSERT, binary storage, JSON functions
- **TEXT**: No validation, text storage, no JSON functions
```sql
-- Create table with JSON column
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255),
preferences JSON
);
-- Insert valid JSON
INSERT INTO users (email, preferences) VALUES
('john@example.com', '{"theme": "dark", "language": "en"}');
-- Success
-- Insert invalid JSON (fails)
INSERT INTO users (email, preferences) VALUES
('jane@example.com', '{invalid json}');
-- ERROR: Invalid JSON text
```
**2. Extraction Functions - Get JSON Values:**
**JSON_EXTRACT() or -> operator:**
Gets value as JSON (with quotes for strings).
```sql
-- JSON_EXTRACT: Get value
SELECT
email,
JSON_EXTRACT(preferences, '$.theme') as theme
FROM users;
-- Returns: "dark" (with quotes)
-- -> operator: Shorthand for JSON_EXTRACT
SELECT
email,
preferences->'$.theme' as theme
FROM users;
-- Same as JSON_EXTRACT
```
**->> operator:**