Working with JSON in SQL Server: OPENJSON, JSON_VALUE and FOR JSON
Originally published at SQL & Cloud Lab . This post was drafted with AI assistance. Modern applications send and receive JSON everywhere, and SQL Server has built-in functions to read, write and query it, available since SQL Server 2016 and in Azure SQL. Used well, they let you store flexible data and exchange it with APIs without extra code. Used badly, they create slow, hard-to-query tables.…
SQL Server offers built-in functions for working with JSON, including OPENJSON, JSON_VALUE, and FOR JSON. These functions enable storing and querying JSON data within SQL Server tables efficiently. To store JSON, create a table with an NVARCHAR column, ensuring the data conforms to JSON syntax using a CHECK constraint. Azure SQL Database and modern SQL Server versions support a native JSON data type for more efficient storage.
Reading values from JSON is straightforward with JSON_VALUE. This function extracts a single scalar value from the JSON string, returning the result as text. However, it returns NULL for objects or arrays. For objects or arrays, use JSON_QUERY instead, which returns the parsed object or array.
OPENJSON is the primary function for converting JSON arrays into tables that can be joined, filtered, and queried like traditional SQL data. It allows defining typed columns using a WITH clause, making the data more readable and usable within queries. OPENJSON requires a database compatibility level of 130 or higher.
To expand an array nested within a JSON column, use CROSS APPLY alongside OPENJSON. This combination yields each array element as a separate row, enabling further processing and queries.
Modifying JSON data is achievable with JSON_MODIFY. This function updates a specific value within the JSON string, or appends data to an existing array. For instance, changing an employee's theme from "dark" to "light" can be accomplished by updating the Settings column.
Returning JSON-formatted results is possible with FOR JSON. This function can return an entire table as JSON data, with options to customize the output format. PATH mode creates nested JSON objects using dotted column aliases, while AUTO mode constructs the JSON shape based on the query results. Indexing JSON properties frequently used in WHERE clauses can significantly improve query performance, akin to indexing traditional columns.
However, JSON should not replace well-structured, typed data that requires constraints, foreign keys, or regular joins. JSON shines in scenarios involving optional settings, audit trails, API payloads, and variable attributes.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to