ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

JSON Data Extraction and Querying

SQL MySQL

Goal -- WPM

Ready
Exercise Algorithm Area
1CREATE TABLE user_profiles (
2profile_id INT AUTO_INCREMENT PRIMARY KEY,
3user_data JSON NOT NULL
4);
5
6-- Insert sample JSON data
7INSERT INTO user_profiles (user_data)
8VALUES
9('{
10"userId": 101,
11"username": "johndoe",
12"email": "john.doe@example.com",
13"address": {
14"street": "123 Main St",
15"city": "Anytown",
16"zip": "12345"
17},
18"interests": ["programming", "hiking", "reading"],
19"isActive": true
20}'),
21('{
22"userId": 102,
23"username": "janedoe",
24"email": "jane.doe@example.com",
25"address": {
26"street": "456 Oak Ave",
27"city": "Otherville",
28"zip": "67890"
29},
30"interests": ["painting", "gardening"],
31"isActive": false
32}'),
33('{
34"userId": 103,
35"username": "peterpan",
36"email": "peter.pan@example.com",
37"address": {
38"street": "789 Pine Ln",
39"city": "Anytown",
40"zip": "12345"
41},
42"interests": ["flying", "adventure"],
43"isActive": true
44}');
45
46-- Query 1: Extract specific values using JSON path expressions
47SELECT
48profile_id,
49user_data ->> '$.username' AS username,
50user_data -> '$.address.city' AS city_json,
51user_data ->> '$.address.city' AS city_text,
52user_data -> '$.interests[0]' AS first_interest_json,
53user_data ->> '$.interests[0]' AS first_interest_text
54FROM
55user_profiles;
56
57-- Query 2: Filter rows based on JSON values
58SELECT
59profile_id,
60user_data ->> '$.username' AS username
61FROM
62user_profiles
63WHERE
64user_data ->> '$.isActive' = 'true' -- Note: JSON boolean true is often treated as string 'true' in comparisons
65AND user_data ->> '$.address.city' = 'Anytown';
66
67-- Query 3: Using JSON_EXTRACT and JSON_UNQUOTE (alternative to -> and ->>)
68SELECT
69profile_id,
70JSON_UNQUOTE(JSON_EXTRACT(user_data, '$.username')) AS username_alt
71FROM
72user_profiles;
73
74-- Query 4: Updating a JSON value (example)
75/*
76UPDATE user_profiles
77SET user_data = JSON_SET(user_data, '$.isActive', false)
78WHERE profile_id = 101;
79*/
80
81-- Edge Case Handling:
82-- Accessing non-existent paths (e.g., '$.nonexistent.field') returns NULL.
83-- Accessing array elements out of bounds (e.g., '$.interests[10]') returns NULL.
84-- Comparisons with JSON booleans might require careful handling (e.g., comparing against 'true' or 'false' strings).
85-- For performance on large datasets, consider generated columns based on JSON values and indexing them.
Algorithm description viewbox

JSON Data Extraction and Querying

Algorithm description:

This scenario focuses on working with JSON data directly within MySQL. It involves creating a table with a JSON column and then demonstrating how to extract, filter, and manipulate JSON data using MySQL's built-in JSON functions and path expressions. This is crucial for applications that store semi-structured data, configuration settings, or API responses.

Algorithm explanation:

MySQL provides robust support for the JSON data type and a rich set of functions for manipulating it. The `->` operator extracts a JSON value (which can be a JSON object, array, string, number, boolean, or null), returning it as a JSON value. The `->>` operator extracts a JSON value and unquotes it, returning it as a string. JSON path expressions use dot notation for object members (e.g., `$.address.city`) and square brackets for array elements (e.g., `$.interests[0]`). Queries can filter rows based on these extracted values. The `JSON_SET` function can be used to update values within a JSON document. Accessing non-existent paths or out-of-bounds array indices returns `NULL`. Performance can be a concern for complex JSON queries on large tables; generated columns based on frequently queried JSON paths can be indexed for optimization. Time complexity for extraction and filtering depends on the complexity of the JSON path and the size of the JSON document, but is generally efficient for typical use cases. Space complexity is for storing the JSON data.

Pseudocode:

1. Define a table with a JSON column.
2. Insert sample JSON data, including nested objects and arrays.
3. Write a query to extract specific values using JSON path operators (`->`, `->>`).
4. Write a query to filter rows based on values within the JSON document.
5. Demonstrate using `JSON_EXTRACT` and `JSON_UNQUOTE` as alternatives.
6. (Optional) Show how to update JSON values using `JSON_SET`.
7. Consider edge cases like missing paths or array bounds.