Handling Nested JSON Arrays in SQL with OPENJSON
Query Nested JSON Arrays
Write a SQL query to extract elements from a nested JSON array.
Solution:
-- Extract elements from a nested JSON array.
SELECT
EmployeeID,
JSON_VALUE(Profile, '$.Name') AS Name,
JSON_VALUE(Skill.value, '$') AS Skill
FROM Employees
CROSS APPLY OPENJSON(Profile, '$.Skills') AS Skill;
Explanation:
- The goal is to extract individual skills from a nested JSON array (Skills) within the Profile column.
- OPENJSON : Parses JSON arrays into rows.
- CROSS APPLY : Joins the parsed JSON data with the main table.
- $.Skills : Specifies the path to the nested array.
- Nested JSON queries allow you to work with complex, hierarchical data structures stored in JSON format.
- For example, in recruitment systems, you might use this query to analyze employee skill sets stored in JSON format.
1. Purpose of the Query :
2. Key Components :
3. Why use Nested JSON Queries? :
4. Real-World Application :
Additional Notes:
- Use OPENJSON for parsing arrays and objects within JSON data.
- Use this exercise to teach how to handle deeply nested JSON structures.
For more Practice: Solve these Related Problems:
- Write a SQL query to extract individual project names from a nested JSON array stored in an employee's profile.
- Write a SQL query to parse and display all certifications from a nested JSON array in a professional profile table.
- Write a SQL query to extract elements from a JSON array representing a customer's order history.
- Write a SQL query to retrieve all languages spoken by users from a nested JSON array in a user preferences table.
Go to:
PREV : Combine PIVOT and UNPIVOT Operators.
NEXT : Use LAG and LEAD Functions
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.