The SQL Server error code 454, *"The unnest argument must be a nested array or table type"*, means your query expects an array or JSON value to use the `UNNEST` function, but the input is flat data (a single column, not an array). Fix it by ensuring your source data is properly structured as a table-valued or JSON array before unnesting. The fix is usually a simple data adjustment or query reformulation. Below is how to diagnose and resolve it.

What You'll Need

  • A SQL Server instance (2016 or later required for native `UNNEST` support)
  • An editor like SSMS, SQLCLR, or a code editor (Visual Studio Code, SQL Prompt) to test changes
  • Access to modify source tables if the issue stems from data structure

Step-by-Step

  1. Identify the unnest function usage: Search your query for `UNNEST`. This may appear as `UNNEST(column_name)` or `UNNEST(CAST(json_column AS NVARCHAR(MAX)))`. Open the query in SSMS or your editor to confirm the exact syntax.
  2. Verify input type:
    1. If the argument is a column (e.g., `UNNEST(orders)`), check if the column stores arrays. Use `SELECT * FROM YourTable WHERE orders IS NOT NULL` and query the column’s storage type. If it’s flat (e.g., `VARCHAR` or `INT`), you must reformulate the query (see Step 3).
    2. If the argument is a JSON column (e.g., `UNNEST(CAST(json_col AS NVARCHAR(MAX)))`), validate with: SELECT * FROM YourTable WHERE json_col LIKE '%[%]' If no results, the JSON column is empty or improperly formatted.
  3. Convert flat data to array/JSON: If the source column is not an array, use one of these methods:
    1. Create a table-valued function (TVF): For SQL Server 2016+, write a TVF that transforms rows into arrays. Example for JSON: CREATE FUNCTION dbo.ExtractJsonArrays(@json NVARCHAR(MAX)) RETURNS TABLE AS RETURN OPENJSON(@json, '$.items[*]'); Then use it in your query: `SELECT * FROM dbo.ExtractJsonArrays(json_col)` followed by `UNNEST(...)`.
    2. Use XML path expressions: For XML data, extract arrays with: SELECT * FROM YourTable CROSS APPLY OPENXML(json_col, '$.items', 2) WITH (item INT '@id')
    3. Manual row-by-row conversion: If data is simple (e.g., comma-separated values), split the column into rows using: SELECT value, SUBSTRING(orders, CHARINDEX(',', orders + ',') + 1, 100) OVER (PARTITION BY ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) Then cast the result to an array type with `CAST(STRING_AGG(...) AS NVARCHAR(MAX)).value('$.[]', 'INT')`.
  4. Check for NULL values: Unnesting fails if the input contains NULLs. Filter them out first: SELECT * FROM YourTable WHERE json_col <> '{}' AND json_col IS NOT NULL Or use `NULLIF` with `UNNEST`: SELECT * FROM YourTable WHERE json_col <> '{}' AND json_col IS NOT NULL CROSS APPLY OPENJSON(json_col)
  5. Validate the unnest step: Test the transformed query with: SELECT * FROM ( SELECT CAST(STRING_AGG(item_id, ',') AS NVARCHAR(MAX)) AS items FROM YourTable WHERE id = 1 ) AS t CROSS APPLY OPENJSON(items) If this works, the issue was the input data structure. If not, move to Step 6.

If That Did Not Work

If the query still fails after Steps 1–5, the problem likely lies deeper:
  1. Check for custom collations: Ensure your session collation supports UTF-8 or mixed Unicode (SQL Server collations must be compatible with the data). Run: SELECT COLLATIONPROPERTY(DB_NAME(), DEFAULT_COLLATION, 'Language') and verify it’s a valid Unicode collation. If not, switch collations or use `FOR XML PATH` instead of `UNNEST`.
  2. Use `FOR XML PATH` as a workaround: Replace `UNNEST` with: SELECT * FROM YourTable CROSS APPLY (SELECT value('$.item[@id]', 'INT') AS id FROM OPENJSON(json_col)) AS derived_table For arrays, use: SELECT * FROM YourTable CROSS APPLY STRING_AGG(item_id, ',') AS items CROSS APPLY OPENJSON(items) AS unnest_result
  3. Test with a sample dataset: Create a minimal table and query to isolate the issue: CREATE TABLE TestData (id INT, items VARCHAR(MAX)); INSERT INTO TestData VALUES (1, '["A","B","C"]'); SELECT * FROM TestData CROSS APPLY OPENJSON(items); If this fails, the environment (e.g., permissions, SQL Server version) is misconfigured.

Common Mistakes

  • Assuming all columns are arrays: Many developers assume any column could be unnested, but only JSON/XML/array columns support it. Always verify with `SELECT * FROM YourTable WHERE json_col IS NOT NULL` or `CAST(json_col AS NVARCHAR(MAX)) LIKE '%[%'`.
  • Ignoring CASE sensitivity: SQL Server’s `UNNEST` is case-insensitive for JSON keys, but the data must be properly encoded. Use `STRING_AGG` or `OPENJSON` with explicit casting to avoid encoding errors.
  • Overlooking NULLs: NULL values in the source column or JSON object will break `UNNEST`. Always filter them out with `WHERE json_col <> '{}'` or `WHERE json_col IS NOT NULL`.
  • Using older SQL Server versions: `UNNEST` was introduced in SQL Server 2016. For earlier versions, use `FOR XML PATH` or a TVF.

Tips

  • Use the Data Explorer: In SSMS, right-click your table and select "Copy as Table" or "Copy as JSON" to experiment with data formatting before writing queries. This helps visualize the expected output.
  • Leverage `OPENJSON` for validation: Always test `OPENJSON` on a single row first: SELECT * FROM OPENJSON('{"items": ["A", "B"]}') This reveals syntax errors in JSON columns.
  • Document your data schema: Maintain a schema diagram or use tools like SQL Server Management Studio’s "Schema Visualizer" to track array/JSON columns. This prevents future errors.
  • Consider a TVF for complex cases: If your data is dynamic (e.g., nested arrays), write a reusable TVF to abstract the unnest logic. Example: CREATE FUNCTION dbo.UnnestArray(@arr NVARCHAR(MAX)) RETURNS TABLE AS RETURN OPENJSON(@arr); Then use it like `SELECT * FROM dbo.UnnestArray(CAST(json_col AS NVARCHAR(MAX)))`.

Troubleshooting

  1. Error persists after data adjustment:
    1. Check the SQL Server error log for additional details. Look for collation errors or permission issues.
    2. Verify the SQL Server version with: SELECT @@VERSION If it’s 2012 or earlier, use `FOR XML PATH` instead of `UNNEST`.
  2. Performance issues:
    1. For large JSON arrays, avoid `UNNEST` in production. Instead, use a TVF or index the flattened data.
    2. Partition your table by JSON columns (e.g., `WHERE country = 'USA'`) to optimize queries.
  3. Data corruption:
    1. If the JSON column contains malformed data, clean it with a stored procedure or script: UPDATE YourTable SET json_col = REPLACE(json_col, 'invalid', '[]') WHERE json_col LIKE '%invalid%'

Frequently Asked Questions

Why does my query fail even though I cast the column to JSON?

If the original column is a flat string (e.g., `"A,B,C"`), casting it to JSON (`CAST('A,B,C' AS NVARCHAR(MAX))`) still returns a string, not an array. Use `STRING_AGG` or a TVF to convert it to a valid JSON array first: SELECT CAST(STRING_AGG(item_id, ',') AS NVARCHAR(MAX)) AS items FROM YourTable

How do I unnest a column that contains NULLs?

Filter out NULLs explicitly. For JSON columns: SELECT * FROM YourTable WHERE json_col <> '{}' AND json_col IS NOT NULL CROSS APPLY OPENJSON(json_col) For array columns, use: SELECT item_id FROM YourTable WHERE array_col IS NOT NULL UNPICK array_col

What if I’m using SQL Server 2017 and still get the error?

Ensure your session collation supports Unicode. Set it temporarily with: WITH (CONNECTIONS = OFF) in your connection string, or use: ALTER SESSION SET CONCURRENT_ACCESS = OFF; And verify with `SELECT COLLATIONPROPERTY(DB_NAME(), DEFAULT_COLLATION, 'Language')`. If still failing, switch to a Unicode collation like `Latin1_General_CI_AS`.

Is there a way to unnest without OPENJSON?

Yes. For simple arrays, use `FOR XML PATH`: SELECT value('$.item', 'INT') AS item FROM YourTable CROSS APPLY STRING_AGG(array_col, ',') AS items CROSS APPLY OPENXML(items, '$.item[*]') WITH (item INT PATH 'item') For XML data, use `OPENXML` with explicit path parameters.

How do I debug unnest errors for a stored procedure?

Add error handling: BEGIN TRY -- Your unnest logic here END TRY BEGIN CATCH SELECT ERROR_NUMBER(), ERROR_MESSAGE() FROM SYS.DATABASE_FILES WHERE ID = DB_ID(); END CATCH This logs errors to the SQL Server error log.

Can I use UNNEST with a temporary table?

Yes, but ensure the temporary table’s data is properly formatted. Example: CREATE TABLE #TempData (id INT, items VARCHAR(MAX)); INSERT INTO #TempData VALUES (1, '["red","blue"]'); SELECT * FROM #TempData CROSS APPLY OPENJSON(items); DROP TABLE #TempData; For temporary tables, use `WITH` clauses to filter NULLs early.