In this tutorial, we explore how to work with JSON columns and indexes in Azure SQL Database. JSON support in Azure SQL allows you to store and query semi-structured data alongside traditional relational data.
What You'll Learn
- How to create a table with a JSON column
- How to insert and query JSON data
- How to create indexes on JSON properties for better performance
Steps
- Create a table with an
NVARCHAR(MAX)column using theJSONconstraint. - Insert sample data as JSON strings.
- Query using
JSON_VALUE,JSON_QUERY, andOPENJSON. - Create indexes on computed columns extracted from JSON.
Example
-- Create table
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDetails NVARCHAR(MAX) CHECK (ISJSON(OrderDetails)=1)
);
-- Insert JSON data
INSERT INTO Orders VALUES (1, '{"Customer": "John", "Items": [{"Product": "Laptop", "Price": 1200}]}');
-- Query
SELECT OrderID, JSON_VALUE(OrderDetails, '$.Customer') AS Customer FROM Orders;
By using JSON columns and indexes, you can blend the flexibility of NoSQL with the power of relational databases in Azure SQL.