📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you work with JSON in SQL Server? Show OPENJSON, JSON_VALUE, JSON_QUERY, JSON_MODIFY and FOR JSON, explain how you index a JSON property, what the native json data type adds, and how you decide whether to store JSON at all instead of normal columns.

JSON in SQL Server and Azure SQL: parsing with OPENJSON and JSON_VALUE, producing JSON with FOR JSON, indexing JSON properties, the native json type and JSON index, and when JSON storage is the right design.

Mid-Level Sql Intermediate azure-sql database-design indexes json sql-server t-sql

🎯 Key points

  • OPENJSON with a WITH clause shreds JSON into typed rows; JSON_VALUE returns a scalar, JSON_QUERY an object or array
  • FOR JSON PATH builds JSON from query results, avoiding N+1 calls to build nested documents
  • Index a property with a computed column on JSON_VALUE plus a normal index (works on every version since 2016)
  • JSON_VALUE returns nvarchar(4000) by default; CAST it, and use strict vs lax paths deliberately
  • Native json type: binary storage, validated on write; GA in Azure SQL Database and Managed Instance and included in SQL Server 2025 (GA November 2025); Microsoft's docs list some pieces, such as CREATE JSON INDEX, as preview
  • JSON_OBJECT/JSON_ARRAY arrived in SQL Server 2022; JSON_OBJECTAGG/JSON_ARRAYAGG are GA in Azure SQL (May 2025) and available in SQL Server 2025
  • Store JSON for sparse, variable or opaque payloads; use columns for anything you filter, join, constrain or report on
  • ISJSON check constraint enforces validity on nvarchar(max) storage

⏱ 30-second answer

SQL Server reads JSON with OPENJSON (shred an array into typed rows using a WITH schema), JSON_VALUE (one scalar) and JSON_QUERY (an object or array), updates it with JSON_MODIFY, and produces it with FOR JSON PATH. To filter on a property quickly, add a computed column on JSON_VALUE and index it. The native json type stores a validated binary form and adds JSON_OBJECTAGG/JSON_ARRAYAGG and the JSON_CONTAINS/JSON index features; it's GA in Azure SQL and shipped with SQL Server 2025, though some features (like the JSON index) are documented as preview.

The design rule: JSON for sparse, variable or pass-through data; real columns for anything you filter, join, constrain or report on.

🗣 Full answer (senior)

How I would answer this in an interview

"SQL Server has had JSON functions since 2016, stored in nvarchar columns, and Azure SQL and SQL Server 2025 now add a native json type. For reading, OPENJSON with a WITH clause is the workhorse: I pass it a document or an array and declare the columns and types I want, and it returns rows I can join or insert. That's how I accept a batch of items from an API in one parameter. JSON_VALUE pulls out a single scalar, JSON_QUERY pulls out a nested object or array, and JSON_MODIFY changes one property. Going the other way, FOR JSON PATH turns a query into JSON, which is handy for returning an order with its lines as one document instead of several queries.

Performance is where people get caught. Filtering with WHERE JSON_VALUE(Data, '$.customer.country') = 'AU' parses every row's document. The fix is a computed column on that JSON_VALUE expression, cast to the right type, with a normal index on it; then it's a seek. The native json type stores a pre-parsed binary form, so reading is cheaper and invalid JSON is rejected on write, and there's a dedicated JSON index aimed at JSON_CONTAINS and path queries, though I'd check its preview status before relying on it.

The bigger question is whether to store JSON at all. I use it for data that's sparse or variable per row, like product attributes that differ between categories, external webhook payloads I need to keep verbatim, or user preferences the database never queries. The mistake I see is putting core fields in a JSON blob to avoid migrations: then you lose types, constraints, foreign keys and statistics, and every query is a parse. If you filter, join, sort, constrain or report on it, it should be a column."


Function reference

Function Does Returns
ISJSON(x) Validity check (use in a CHECK constraint) 1/0
JSON_VALUE(x, path) Scalar at path nvarchar(4000) (2025/Azure: RETURNING type option)
JSON_QUERY(x, path) Object or array at path JSON fragment
JSON_MODIFY(x, path, v) Set, insert, delete a property Updated JSON
OPENJSON(x) WITH (...) Shred to typed rows Rowset
FOR JSON PATH / AUTO Query to JSON nvarchar(max)
JSON_OBJECT, JSON_ARRAY Build JSON values (2022+) JSON
JSON_OBJECTAGG, JSON_ARRAYAGG Aggregate rows into JSON JSON

Store as JSON or columns?

Data Choice
Order status, customer id, totals Columns (filtered, joined, constrained)
Category-specific product attributes JSON (sparse), with computed columns for the few that are filtered
Raw webhook payload for audit JSON (opaque, kept verbatim)
Values reported on by finance Columns

Production example

A product search filtered on JSON_VALUE(Attributes, '$.brand') over 2.4 million rows: a clustered index scan with 310,000 logical reads and about 1.8 seconds. Adding a persisted computed column Brand AS CAST(JSON_VALUE(Attributes, '$.brand') AS nvarchar(100)) with an index turned it into a seek of 40 reads and 3 ms.

🔍 What the interviewer is checking

Checks whether the candidate can use SQL Server's JSON features and makes a sound decision about storing JSON.

Green flags

  • Uses OPENJSON WITH, JSON_VALUE, JSON_QUERY and FOR JSON correctly
  • Indexes JSON properties through computed columns
  • Knows the native json type and checks its feature status
  • Gives a clear rule for JSON versus columns

Red flags

  • Puts core fields in JSON to avoid migrations
  • Filters on JSON_VALUE at scale with no index
  • Unaware of the nvarchar(4000) return type

📚 Learn in depth

1. Storage options

nvarchar(max) + ISJSON check     native json (Azure SQL, SQL Server 2025)
  text, parsed on every read       binary, parsed once on write
  any size up to 2 GB              up to 2 GB, nesting limit 128 levels
  works on SQL Server 2016+        validated on write, JSON index support

As of November 2026 the json type is generally available in Azure SQL Database and Azure SQL Managed Instance and is part of SQL Server 2025, which reached GA in November 2025. Microsoft's docs have listed some related pieces, such as CREATE JSON INDEX and the modify method, as preview; check the current status before using them in production.

2. Paths: lax vs strict

'$.customer.country' is lax by default: a missing property returns NULL. 'strict $.customer.country' raises an error, which is useful when the property must exist. JSON_VALUE returns NULL (lax) if the value is an object, and truncates at 4,000 characters, so use JSON_QUERY for objects and OPENJSON for long strings.

3. Indexing

ALTER TABLE Products ADD Brand AS CAST(JSON_VALUE(Attributes,'$.brand') AS nvarchar(100));
CREATE INDEX IX_Products_Brand ON Products(Brand);

WHERE JSON_VALUE(Attributes,'$.brand') = N'Acme'
   -> optimiser matches the expression to the computed column -> Index Seek

The expression must match exactly (including the CAST) for matching to happen; querying the computed column directly is more reliable. For the native type, CREATE JSON INDEX indexes paths for JSON_VALUE, JSON_PATH_EXISTS and JSON_CONTAINS.

4. OPENJSON for set-based input

A single JSON parameter replaces a table-valued parameter when the caller can't easily build one. OPENJSON with WITH gives typed columns and AS JSON for nested arrays, which you can CROSS APPLY into another OPENJSON.

5. EF Core

EF Core maps owned types and complex types to JSON columns (ToJson()), translating LINQ over JSON properties into JSON_VALUE/OPENJSON. EF Core 10 can use the native json type on Azure SQL or SQL Server 2025 when configured for it (for example UseAzureSql or compatibility level 170).

6. Privacy

JSON blobs often hide personal information. Under the Privacy Act 1988 and the APPs you still need to know where personal data lives, so document JSON schemas and avoid storing whole third-party payloads with unnecessary personal fields.

Try it yourself

  1. Load 1 million rows with a JSON attribute and compare a JSON_VALUE filter before and after adding an indexed computed column.
  2. Shred a nested order document with OPENJSON ... WITH (Lines nvarchar(max) AS JSON) and CROSS APPLY.
  3. Return customers with their orders as nested JSON using FOR JSON PATH and compare with two separate queries.
  4. On Azure SQL, create a table with a json column, insert invalid JSON and observe the error.

💻 Code

Accepting a JSON batch, indexing a JSON property, and returning nested JSON.

CREATE TABLE dbo.Products (
    ProductId  int IDENTITY CONSTRAINT PK_Products PRIMARY KEY,
    Name       nvarchar(200) NOT NULL,
    CategoryId int NOT NULL,
    Attributes nvarchar(max) NULL CONSTRAINT CK_Products_Attributes CHECK (ISJSON(Attributes) = 1),
    -- On Azure SQL / SQL Server 2025 you could declare: Attributes json NULL
    Brand AS CAST(JSON_VALUE(Attributes, '$.brand') AS nvarchar(100)) PERSISTED
);
CREATE INDEX IX_Products_Brand ON dbo.Products (Brand) INCLUDE (Name); -- seekable JSON property
GO

-- Shred a batch sent as one JSON parameter
DECLARE @payload nvarchar(max) = N'[
  {"name":"Kettle","categoryId":3,"attributes":{"brand":"Acme","litres":1.7}},
  {"name":"Toaster","categoryId":3,"attributes":{"brand":"Acme","slots":4}}
]';

INSERT dbo.Products (Name, CategoryId, Attributes)
SELECT j.Name, j.CategoryId, j.Attributes
FROM OPENJSON(@payload)
WITH (
    Name       nvarchar(200) '$.name',
    CategoryId int           '$.categoryId',
    Attributes nvarchar(max) '$.attributes' AS JSON
) AS j;

-- Filter uses the indexed computed column
SELECT ProductId, Name FROM dbo.Products WHERE Brand = N'Acme';

-- Update one property
UPDATE dbo.Products
SET Attributes = JSON_MODIFY(Attributes, '$.warrantyYears', 2)
WHERE ProductId = 1;

-- Return orders with lines as one JSON document per customer
SELECT c.CustomerId, c.Name,
       (SELECT o.OrderId, o.OrderDate, o.Total
        FROM dbo.Orders o
        WHERE o.CustomerId = c.CustomerId
        FOR JSON PATH) AS Orders
FROM dbo.Customers c
WHERE c.CustomerId = 42
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;

⚠ Common mistakes

  • Mistake: Filtering on JSON_VALUE over a large table with no supporting index. Why it is wrong: Every row's document is parsed: a full scan. Instead: Add an indexed computed column (or a JSON index on the native type) for hot properties.
  • Mistake: Storing core relational fields in JSON to avoid migrations. Why it is wrong: You lose types, constraints, foreign keys and statistics, and every query pays parsing costs. Instead: Columns for anything filtered, joined, constrained or reported on.
  • Mistake: Forgetting JSON_VALUE returns nvarchar(4000). Why it is wrong: Comparisons with numbers or dates convert implicitly and long values become NULL in lax mode. Instead: CAST the result, use OPENJSON ... WITH for typed values, or JSON_QUERY for objects.
  • Mistake: No validity check on nvarchar JSON columns. Why it is wrong: Invalid documents break every query that parses them. Instead: CHECK (ISJSON(col) = 1) or the native json type.
  • Mistake: Building JSON in C# from several queries. Why it is wrong: N+1 round trips for nested documents. Instead: FOR JSON PATH with nested subqueries, or one projection in EF Core.
  • Mistake: Relying on preview features like the JSON index in production without checking status. Why it is wrong: Preview features can change and may not be supported. Instead: Check the docs for the version you run; fall back to computed columns.

🏛 Senior insight: trade-offs

JSON in a relational database is a schema decision, not a convenience. It's excellent at the edges (variable attributes, raw payloads, settings) and harmful at the core. My test: if the business ever asks "show me all X where property Y = Z" at scale, Y becomes a column or at least an indexed computed column.

Option Fits when Cost Not when
Relational columns Filtered, joined, constrained data Migrations for changes Highly variable shapes
nvarchar(max) JSON + ISJSON Variable data, any SQL Server version Parse on every read Hot filters without computed columns
Native json type Azure SQL / SQL Server 2025, frequent reads Version requirement, some features in preview Older servers, cross-version code
Separate document store (Cosmos DB) Document-first workloads at scale Another system, consistency Data needs joins with relational tables

Measure with SET STATISTICS IO, TIME ON before and after adding computed columns, and watch Query Store CPU for queries that parse JSON.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions EF Core mapping to JSON columns Why: Checks the EF Core side: ToJson, owned and complex types, and indexing JSON columns.
    How to answer

    Use a JSON column (ComplexProperty(...).ToJson() or OwnsOne/OwnsMany(...).ToJson()) for data that is owned by one row, read and written with it, and rarely queried alone: preferences, a variable set of attributes, a snapshot of an address at order time. Use tables when you need to join, filter or aggregate across rows at scale, enforce foreign keys, unique or check constraints, or update parts concurrently. Performance trade-off: reading the whole document with its owner is cheap (one row, no join), but filtering inside JSON means parsing every document unless you index it. On SQL Server, index a property by adding a computed column over JSON_VALUE(Data, '$.Country') and indexing that column; it works on every supported version. EF Core 10 can map to the native json data type on Azure SQL and SQL Server 2025, which stores documents in a binary form that is faster to read; check your target's support for dedicated JSON indexes before relying on them.

  2. When: Candidate says filtering on JSON_VALUE causes a scan Why: Checks the general SARGability principle behind expression filters.
    How to answer

    A predicate is SARGable (Search ARGument-able) when the optimiser can turn it into a seek range on an index. The rule: leave the column bare and put any calculation on the other side.

    • YEAR(OrderDate) = 2026 scans; OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' seeks.
    • Price * 1.1 > 100 scans; Price > 100 / 1.1 seeks.
    • An implicit conversion of the column (e.g. varchar column vs nvarchar parameter) often scans; match types.
    • LIKE 'abc%' seeks; LIKE '%abc' cannot.
    • ISNULL(col, 0) = 0 scans; col = 0 OR col IS NULL seeks.

    When the expression is unavoidable, index a persisted computed column. Trade-off: the rewrite is free; the computed column costs storage and writes.

🛠 Real-world problems: how you handle them

Product search scanning JSON attributes
Situation
An [online catalogue] stored category-specific attributes as JSON in an nvarchar(max) column on Azure SQL, about [2.4 million] products. A new brand filter was added to the search page.
Signals
Search p95 latency jumped from 120 ms to 1.9 s after release; Query Store showed the new query at the top for CPU and logical reads; DTU usage peaked during business hours.
Investigation
Pulled the plan from Query Store: a clustered index scan with a Filter operator evaluating JSON_VALUE on every row, about 310,000 logical reads per execution. Checked how many queries filtered on JSON properties and found brand and colour were the only hot ones.
Resolution
Added persisted computed columns for brand and colour cast to nvarchar(100) with nonclustered indexes, and changed the query to filter on the computed columns. Left the rest of the attributes as JSON.
Prevention
Added a design guideline: any JSON property used in a filter gets a computed column and index; added an ISJSON check constraint; set a Query Store alert on logical reads regressions after deployments.

How to tell it (STAR)

**S:** At [company], adding a brand filter to product search made the page slow during business hours. **T:** I had to fix it without redesigning the whole attributes model. **A:** Query Store showed a full scan parsing JSON on every row. I added indexed computed columns for the two attributes people filter on, kept the rest in JSON, and wrote a guideline for future filters. **R:** The query went from about [1.8 seconds and 310,000 reads] to [3 ms and 40 reads], and search p95 returned to [120 ms].

↩ Usually asked after

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me