Welcome to our comprehensive guide on SQL JSON! This tutorial is designed for both beginners and intermediate learners, aiming to explain JSON handling in SQL from the ground up. 📝 JSON stands for JavaScript Object Notation, a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
In modern data-driven applications, JSON is a common format for exchanging data between different systems. SQL JSON support allows us to store, query, and manipulate JSON data directly in SQL databases. This integration provides a seamless way to work with diverse data types and improves the efficiency of handling JSON data in our applications.
JSON is a collection of name/value pairs and an ordered list of values. Each name/value pair is an object, and each value can be a string, number, boolean, null, array, or another object. Here's a simple example of a JSON object:
{
"name": "John",
"age": 30,
"isMarried": true,
"children": ["Mike", "Anna"],
"address": {
"street": "Main St",
"city": "Anytown",
"state": "Anystate"
}
}SQL supports three JSON types:
{}.[].Let's dive into some SQL JSON examples using a MySQL database for demonstration purposes.
To store a JSON value in a MySQL table, use the JSON_OBJECT() function:
CREATE TABLE employees (
id INT PRIMARY KEY,
data JSON
);
INSERT INTO employees (id, data)
VALUES (1, JSON_OBJECT('name', 'John', 'age', 30, 'isMarried', true));To extract the name from the stored JSON value, use the JSON_EXTRACT() function:
SELECT id, JSON_EXTRACT(data, '$.name') as name
FROM employees
WHERE id = 1;Which SQL JSON type is a collection of name/value pairs enclosed in curly braces?
In the following lessons, we will explore more advanced JSON handling techniques in SQL, including JSON Array manipulation, JSON Path expressions, and JSON updates. Happy learning! 🎯