Have you ever received JSON data in SQL Server, only to discover that some fields are missing, values have unexpected data types, or the data does not match what your application expects?
JSON is a flexible and popular format for exchanging data, but that flexibility can also introduce problems when processing it in a database.
Fortunately, SQL Server provides OPENJSON, which allows us to convert JSON data into rows and columns. By using an explicit schema, we can define the expected fields and data types, making the data easier to process and maintain.
In this article, we’ll explore how to use OPENJSON with an explicit schema, how it helps create a clearer data contract, and why additional validation is still important to ensure data meets our business requirements.
Begin with a small known payload
The following example requires SQL Server 2016 or later and database compatibility level 130 or higher. It uses a variable and does not modify permanent tables.
DECLARE @Payload nvarchar(max) = N'[
{"productId": 101, "quantity": 2, "unitPrice": 12.50},
{"productId": 102, "quantity": 1, "unitPrice": 7.00}
]';
SELECT ProductId,
Quantity,
UnitPrice,
Quantity * UnitPrice AS LineTotal
FROM OPENJSON(@Payload)
WITH
(
ProductId int '$.productId',
Quantity int '$.quantity',
UnitPrice decimal(10,2) '$.unitPrice'
)
ORDER BY ProductId;
Based on the above code, we expect two rows, with line totals 25.00 and 7.00. The WITH clause states how JSON properties map to relational columns. Explicit paths also make the expected property names visible.
Parsing does not establish business validity
A parsed quantity of zero might be valid JSON and a valid integer, yet invalid for an order line. A product identifier might have the correct type while referring to a product that does not exist.
After parsing, apply the rules the operation requires: positive quantities, permitted price ranges, known products and an acceptable number of lines. Decide whether duplicate product entries are allowed or should be combined or rejected.
These decisions belong to the business contract. They should not emerge accidentally from whichever rows an INSERT happens to accept.
Choose missing-property behaviour deliberately
With the default lax path behaviour, a missing scalar property can produce NULL. If the operation requires Quantity, accepting that NULL without further validation can move an incomplete record deeper into the system.
Strict paths can raise an error for a missing property, but strictness alone does not check every rule. Explicit JSON null values, out-of-range numbers and incompatible types still need a considered error-handling strategy.
For a tolerant ingestion process, consider extracting appropriate raw values into staging and recording validation failures before converting them. For an interactive order submission, rejecting the complete invalid request may be more appropriate.
Treat the request boundary as part of the design
Limit payload size and line count before expensive processing. Authenticate the caller and validate that the caller may perform the requested operation. A valid JSON structure is not permission to insert data for any customer.
For a multi-line order, decide whether all lines must succeed together. If so, put validation and persistence within a carefully designed transaction workflow and account for concurrent changes to referenced data.
Do not log the full payload automatically when it contains personal or sensitive values. Record a request identifier and useful error details instead.
Test the contract, not only the happy path
Try an empty array, a missing required property, a JSON null, an incorrect type, a negative quantity, duplicate entries and malformed JSON. Record whether each case should succeed, be rejected or enter a review queue.
OPENJSON solves the transformation from a document to rows. A reliable ingestion endpoint adds explicit validation, authorisation and persistence behaviour around that transformation.
Technical references
Continue learning
To build the database and query foundations behind this topic, explore my course SQL Server Fundamentals – SQL Database for Beginners on Udemy. Review the curriculum and preview to see whether it fits your next learning goal.
Read Also
- Working with XML and JSON Data in SQL Server
- SQL Server Database Design Best Practices
- Python Data Access Fundamentals
Stay connected
Subscribe to the GnoelixiAI Hub newsletter on LinkedIn for practical insights on AI, data and technology.
Watch more on YouTube: SQLNetHub TV and my personal channel.
Originally published on SQLNetHub.
© SQLNetHub
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.