SQL JSON_EXTRACT Tutorial 🎯

beginner
20 min

SQL JSON_EXTRACT Tutorial 🎯

Welcome to CodeYourCraft's in-depth guide on SQL JSON_EXTRACT! In this lesson, we'll learn how to extract and manipulate JSON data within SQL databases. 💡 Pro Tip: If you're new to SQL, we recommend starting with our SQL Basics tutorial first!

What is JSON_EXTRACT?

JSON_EXTRACT is a powerful function in SQL that allows you to extract specific data from a JSON object within a database. It's essential for working with modern applications that rely on JSON data structures. 📝 Note: JSON stands for JavaScript Object Notation, a lightweight data interchange format.

Why Use JSON_EXTRACT?

JSON_EXTRACT is helpful when you need to interact with data stored as JSON objects in your SQL database. For example, a web application might store user preferences or API responses as JSON objects. With JSON_EXTRACT, you can extract the specific data you need for analysis, reporting, or further processing.

JSON_EXTRACT Syntax

The basic syntax for JSON_EXTRACT is as follows:

sql
JSON_EXTRACT(json_data, json_path)
  • json_data: The JSON data stored in the database column or a variable.
  • json_path: The path to the specific JSON element you want to extract.

Extracting JSON Data

Now that we understand the basics, let's try some examples!

Example 1: Extracting a Single Value

Consider the following JSON data stored in a column named user_preferences:

json
{ "name": "John Doe", "age": 30, "email": "john.doe@example.com", "preferences": { "theme": "dark", "notification": true } }

To extract the theme preference, you can use the following SQL query:

sql
SELECT JSON_EXTRACT(user_preferences, '$.preferences.theme') AS theme FROM users;

In this query, $.preferences.theme is the JSON path we use to specify the location of the theme preference within the JSON object.

Example 2: Extracting Multiple Values

If you want to extract multiple values, you can use an array for the json_path. Let's say we want to extract both theme and notification from the same JSON data:

sql
SELECT JSON_EXTRACT(user_preferences, '$.preferences.theme, $.preferences.notification') AS preferences FROM users;

This query will return an array containing both theme and notification values.

Quiz Time 📝

Quick Quiz
Question 1 of 1

What does the JSON_EXTRACT function do in SQL?

Stay tuned for more advanced examples, tips, and tricks on working with JSON data using SQL JSON_EXTRACT! ✅ You Got It! Keep learning and coding with CodeYourCraft!