What you will be able to do
- Explain when a VARIANT column beats a JSON STRING column or a predefined STRUCT for semi-structured data
- Create VARIANT columns with parse_json, try_parse_json, CTAS, INSERT and Auto Loader's singleVariantColumn option
- Query VARIANT data with the : path syntax, dot and bracket navigation, array indexes and escaped field names
- Choose between variant_get, try_variant_get, :: and ?:: based on how a failed cast should behave
- Name the operations a VARIANT column cannot take part in, and model a table that keeps hot fields outside the variant
Key concept
VARIANT — A column type that stores a whole semi-structured value (object, array or scalar) in an encoded form you can query by path without declaring a schema first. You parse a value into it once, then pull typed values out of it at query time.
1.Why VARIANT instead of a JSON string or a STRUCT
Semi-structured payloads such as clickstream events, webhook bodies and device telemetry rarely keep the same shape for long. A new attribute shows up in one release, and a nested object grows a field in the next. Before VARIANT there were two ways to store this kind of data, and each one fails in its own way. You could keep the payload as a plain STRING and run get_json_object in every query, so every read parses the text again. Or you could parse it into a STRUCT with from_json against an explicit schema, and then change that schema every time the payload gains a field.
VARIANT is the recommended type when the schema is changing or unknown. The VARIANT type holds objects, arrays and scalars in one column. Downstream queries reach any nested field by path, and nobody has to define or evolve a schema first. It is also fast enough to replace native complex types in some cases: Databricks says its read and write performance allows it to replace structs and arrays in some use cases.
When each option wins depends on how stable the shape is. A STRUCT still suits a payload whose fields are fixed and known, because the schema is part of the table contract. A STRING suits a payload you only store and pass on. For a bronze table that takes raw events with a schema that keeps drifting, where consumers need to query arbitrary nested fields, parse the string with parse_json and store the result as VARIANT. Turning on Auto Loader schema inference doesn't solve this. It produces typed columns that still have to evolve as the payload changes.
| Variant function | JSON string function | Behaviour to know |
|---|---|---|
| variant_get | cast and get_json_object | Takes an expression, path and type; follows variant path, casting and null rules |
| try_variant_get | try_cast and get_json_object | Same arguments as variant_get, but tolerates failed casts |
| is_variant_null | is null | Checks for a VARIANT-encoded NULL; use is null to check whether the expression itself is NULL |
| schema_of_variant / schema_of_variant_agg | schema_of_json / schema_of_json_agg | Infers a schema; conflicting types are derived as VARIANT |
| variant_explode / variant_explode_outer | explode / explode_outer | Outputs pos, key and value columns; key is always null for arrays |
Checkpoint 1 of 8· Check yourself
A bronze table takes in raw webhook events. New attributes keep appearing between releases, and analysts need to query any nested field without waiting for a schema change. How should the payload be stored?
VARIANT is the recommended type when the schema changes or is unknown. Any nested field can be reached by path without defining or evolving a schema. A STRING has to be parsed again on every read. A STRUCT and inferred typed columns both need schema changes as the payload grows.
“you should use variant over JSON strings whenever storing semi-structured data that requires flexibility for changing or unknown schema”Source: docs.databricks.com
Checkpoint 2 of 8· Exam question
A data engineer is building a bronze Lakeflow Spark Declarative Pipeline that ingests raw JSON event payloads from cloud storage via Auto Loader. The payloads have a frequently changing schema, and downstream consumers need to query arbitrary nested fields without the engineer having to pre-define or evolve a STRUCT schema for every new field. Which approach correctly loads the raw JSON string column into a queryable semi-structured representation in the bronze table?
Correct answer: A — Convert the raw JSON string with parse_json() before writing to bronze, storing it as a VARIANT column that supports variant_get and : path access without a predefined schema.
- A. Wrapping the raw string with
parse_json()produces aVARIANTvalue that Databricks recommends for semi-structured data precisely because it preserves the full nested structure without requiring a fixed schema up front. Fields can then be pulled out on demand withvariant_getor the:shorthand as consumers need them, which matches the flexibility requirement. - B. An explicit STRUCT schema is the opposite of schema flexibility: every new field forces a schema evolution event, and Auto Loader's evolution modes typically fail or restart the stream rather than silently rewriting the STRUCT mid-flight. This adds operational overhead the scenario is trying to avoid.
- C. Leaving the payload as a STRING and re-parsing it with
get_json_object()on every query works but throws away the structural parsing benefits ofVARIANT, forcing repeated string-based JSON parsing at query time instead of a single upfront conversion. - D. Automatic flattening into STRUCT columns commits the table to a rigid, field-by-field schema derived from whatever sample Auto Loader inferred, which breaks or requires evolution the moment a genuinely new or inconsistent field shows up in later files.
2.Creating VARIANT columns and loading data into them
**parse_json turns a STRING containing a JSON document into a VARIANT.** Its argument has to be a STRING expression. It accepts objects, arrays and bare scalars, so parse_json('123') returns the variant 123. If the text isn't valid JSON, the call raises MALFORMED_RECORD_IN_PARSING and the query fails. try_parse_json takes the same input and returns NULL for a document it can't parse. Use it when a few bad records shouldn't stop a load. You can also build variants without parsing text: CAST(123.456 AS VARIANT) converts a literal, and to_variant_object converts a STRUCT or MAP whose keys are strings.
The inverse is to_json, and it isn't exact. A round trip through to_json(parse_json(s)) can change whitespace, reorder keys and drop trailing zeros from numbers, so {"a" : 0.01000} comes back as {"a":0.01}. If you compare round-tripped strings with the originals, expect mismatches that aren't data loss.
A table can declare a VARIANT column directly with CREATE TABLE table_name (variant_column VARIANT), or get one from a CTAS. Existing variant columns are filled with INSERT INTO ... SELECT PARSE_JSON(json_string). XML and CSV strings go in through from_xml(xml_string, 'variant') and from_csv(csv_string, 'v variant').v. The CTAS below shows the modelling pattern that matters most: it promotes one field to its own column and keeps the whole document as a variant.
CREATE TABLE table_name AS
SELECT json_string:id AS id,
PARSE_JSON(json_string) variant_column
FROM source_dataFor streaming ingestion from cloud storage, Auto Loader can write each whole record into one variant column with the singleVariantColumn option. Auto Loader itself is taught in Auto Loader streaming pipelines. This pattern holds up when the source changes shape, because VARIANT is flexible about schema and type changes and keeps the case and NULLs of the source data. It has three costs, though. Malformed records can't be encoded as VARIANT, a single record can't exceed 16 MB, and no schema evolution happens during ingestion, so rescuedDataColumn isn't supported. If you only want some fields stored as variants, pass a schema such as "name STRING, address VARIANT" or use the cloudFiles.schemaHints option, and the other columns are inferred as usual.
(spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("singleVariantColumn", "variant_column")
.load("/Volumes/catalog_name/schema_name/volume_name/path")
.writeStream
.option("checkpointLocation", checkpoint_path)
.toTable("table_name")
)Checkpoint 3 of 8· Fill the gap
This Auto Loader stream must land every JSON record, whole, in the one VARIANT column of an existing table. Which option name completes it?
(spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option(" ? ", "variant_column")
.load("/Volumes/catalog_name/schema_name/volume_name/path")
.writeStream
.option("checkpointLocation", checkpoint_path)
.toTable("table_name")
)singleVariantColumn makes Auto Loader write each whole record into the named VARIANT column. In this mode no schema evolution happens, so rescuedDataColumn isn't supported. cloudFiles.schemaHints makes only the listed fields VARIANT and infers the rest. corruptRecordColumn holds bad or oversized records, not the data itself.
Source: docs.databricks.com3.Navigating a variant with : paths, dots, brackets and indexes
The SQL path operators for JSON strings also work on VARIANT. : selects a top-level field, . or ['key'] goes into nested fields, and [n] picks an array element with a 0-based index. With a table store_data whose variant column is raw, raw:owner returns the owner, raw:store.bicycle and raw:store['bicycle'] return the same nested object, and raw:store.fruit[0] returns the first fruit. The result of a : path is still a VARIANT. That's why raw:owner displays as "amy" with quotes, and why a path that doesn't exist returns NULL of type VARIANT.
Field names with special characters need the ['<field>'] form. It escapes spaces, periods, colons and square brackets. Backticks escape spaces and colons only. A field named zip.code escaped with backticks quietly returns NULL, while raw:['zip.code'] finds it. PySpark uses the same bracket syntax inside the variant_get path, for example "$['zip.code']".
-- Enclose a field name that contains special characters in single quotes inside square brackets.
SELECT raw:['zip code'], raw:['fb:testid'] FROM store_dataTwo habits from JSON strings break when queries move to VARIANT. First, every path element is matched with case sensitivity, so raw:OWNER and raw:owner look for different fields. A JSON-string query that relied on case-insensitive matching gets NULLs after migration and raises no error. Second, the [*] wildcard for unpacking every array element isn't supported. To turn an array into rows, use variant_explode, which returns pos, key and value columns.
NULL. A path that can't be found and an array index that is out of bounds both return null. Neither one raises an error.
Checkpoint 4 of 8· Check yourself
A team moves a JSON STRING column to a VARIANT column named raw. The stored key is "owner". Before the move, SELECT raw:Owner FROM store_data returned amy. Now it returns NULL and raises no error. What causes this?
Every variant path element is matched with case sensitivity, but JSON-string queries match case-insensitively. raw:Owner therefore looks for a field that doesn't exist and returns NULL with no error. The : operator works on VARIANT, and raw:owner returns "amy" without escaping or a cast.
“All variant path elements are matched in a case-sensitive way. JSON strings are case-insensitive.”Source: docs.databricks.com
4.Extracting typed values: variant_get, try_variant_get and casts
A path gives you another variant. Aggregations, joins and output columns usually need a real SQL type, so typed extraction is a separate step. variant_get(variantExpr, path, type) takes the variant, a JSON path literal such as '$.store.bicycle.price', and a type string such as 'double', and returns a value of that type. The SQL shorthand is a path followed by a cast, as in raw:store.bicycle.price::double. In PySpark the same call is variant_get(col("raw"), "$.owner", "string"), imported from pyspark.sql.functions.
variant_get treats a missing path and a failed cast differently. A missing path returns NULL. A value that exists but has the wrong type raises INVALID_VARIANT_CAST, and that one row fails the whole query or pipeline update. It doesn't substitute 0, and it doesn't skip the row. try_variant_get takes the same three arguments and returns NULL in both cases. The NULL lands in that one column of that one row, and every other row and column comes through unchanged.
-- Simple example
> SELECT variant_get(parse_json('{"key": 123, "data": [4, {"a": "hello"}, "str"]}'), '$.data[1].a', 'string')
hello
-- missing path
> SELECT variant_get(parse_json('{"key": 123, "data": [4, {"a": "hello"}, "str"]}'), '$.missing', 'int')
null
-- Invalid cast
> SELECT variant_get(parse_json('{"key": 123, "data": [4, {"a": "hello"}, "str"]}'), '$.key', 'array<int>')
Error: INVALID_VARIANT_CAST.The cast operators follow the same split. cast and :: convert a VARIANT to a specific type. try_cast and its operator form ?:: do the same conversion with error tolerance. So when a price field occasionally holds "N/A", try_variant_get(payload, '$.price', 'double') or payload:price ?::DOUBLE produces NULL for those rows and the pipeline keeps running. parse_json doesn't help here. It takes a STRING containing JSON text, and payload:price is already a VARIANT, so re-parsing has nothing to fix.
> SELECT '{"key": 123, "data": [4, {"a": "hello"}, "str"]}':data[1].a ?::STRING;
hello
> SELECT '{"key": 123, "data": [4, {"a": "hello"}, "str"]}':missing ?::STRING;
null
> SELECT '{"key": 123, "data": [4, {"a": "hello"}, "str"]}':key ?::BOOLEAN;
nullCheckpoint 5 of 8· Match them up
Assume v is parse_json('{"key": 123, "data": [4, {"a": "hello"}, "str"], "store": {"bicycle": {"price": 19.95}}}'). Match each expression to what it produces.
Tap a term, then the definition that fits it.
variant_get returns NULL only when the path is missing. If the value is found but can't be cast, it raises INVALID_VARIANT_CAST. try_variant_get returns NULL in both cases. A plain : path doesn't cast at all, so it returns another VARIANT.
“If the object cannot be found, NULL is returned. If the object is found but cannot be cast to the desired type, Databricks raises INVALID_VARIANT_CAST.”Source: docs.databricks.com
Checkpoint 6 of 8· Exam question
A Lakeflow Spark Declarative Pipeline reads a VARIANT column named payload where a small fraction of upstream events have a price field that is sometimes a string like "N/A" instead of a number. The engineer wants to extract price as a DOUBLE and have any row that fails the cast produce a NULL for that column instead of failing the entire pipeline run. Which expression should be used?
Correct answer: A — try_variant_get(payload, '$.price', 'double'), which returns NULL for values that cannot be cast to DOUBLE instead of raising an error for the whole batch.
- A.
try_variant_getis the safe-casting variant function: it attempts the extraction and type coercion in one step and falls back toNULLon failure rather than raising an error, which is exactly the row-level fault tolerance the pipeline needs. - B. Plain
variant_getdoes not substitute a default numeric value on a failed cast; it raises an error rather than silently inventing0.0, so this expression does not deliver the described behavior and would still risk failing the batch. - C. A failed cast does not cause Delta or Spark to drop the offending row on its own; casting failures either raise an error or, depending on ANSI mode, return
NULLfor that expression, but they do not silently delete rows from the batch. - D.
parse_jsonexpects a JSON-formatted string as input, not an already-extracted variant value, so applying it topayload:priceis the wrong composition and does not provide the described selective type-mismatch handling.
5.What a VARIANT column cannot do, and how to model around it
A raw VARIANT column can't be a physical layout key and can't be compared. It can't serve as a clustering key, a partition column or a Z-order key. Enabling Liquid Clustering doesn't lift this; the layout options themselves are compared in Delta optimization techniques. The type also can't be used for comparisons, grouping, ordering or set operations. That rules out ORDER BY raw, GROUP BY raw, an equality join on two variant columns, and UNION/INTERSECT deduplication over them. Selecting an extracted scalar alongside the variant in the same query doesn't make GROUP BY on the variant itself legal.
All of these work once the value has been extracted to a typed column. GROUP BY raw:owner::string groups by a STRING, and a join on variant_get(raw, '$.id', 'bigint') compares BIGINTs. Doing the extraction at query time costs work on every read, though. It's better to do it once when you build the table.
Promote the fields you query often to ordinary columns and keep the rest in the variant. Databricks recommends storing frequently queried fields as non-variant columns, both to speed up queries and to improve the storage layout. In practice, a table of events might carry event_id BIGINT, event_ts TIMESTAMP and customer_id STRING as typed columns extracted during ingestion, plus a payload VARIANT holding everything else. The typed columns can be clustered, filtered, grouped and joined. The variant keeps the long tail of attributes queryable without schema changes. One more restriction to know before you design: Iceberg v2 tables don't support VARIANT columns, and Iceberg v3 does.
Checkpoint 7 of 8· Check yourself
An events table stores each record in a VARIANT column named payload, and Liquid Clustering is enabled on the table. Most queries filter on customer_id, and a daily report groups by customer_id. Which table design supports these queries?
A VARIANT column can't be a clustering, partition or Z-order key, and enabling Liquid Clustering doesn't change that. It also can't be used for grouping or equality comparisons. Promoting customer_id to a typed column at ingestion gives a column you can cluster, filter, group and join on, while payload keeps the rest of the attributes queryable.
“Databricks recommends extracting frequently queried fields and storing them as non-variant columns to accelerate queries and optimize storage layout.”Source: docs.databricks.com
Checkpoint 8 of 8· Exam question
A team is designing a Delta table with a VARIANT column to store nested event attributes. During the design review, several proposals are made about how the VARIANT column can be used elsewhere in the table definition and in queries. Which of the following statements are correct limitations of the VARIANT data type? (Select all that apply.)(Select 3)
Correct answers: A, B, C — A VARIANT column cannot be used as a Z-order key.; A VARIANT column cannot be used as a table partition column.; Rows cannot be directly compared or sorted with ORDER BY on a raw VARIANT column.
- A. Databricks documentation explicitly states that
VARIANTcolumns cannot be used for Z-order keys, since the type does not support the ordering comparisons that Z-ordering relies on. - B.
VARIANTcolumns cannot be used as partition columns; the type is intended for flexible in-row storage of semi-structured values, not for defining the physical partition layout of a table. - C. Direct comparisons, grouping, ordering, and set operations are all unsupported on raw
VARIANTvalues, so sorting on the column withORDER BYis not possible without first extracting a typed scalar. - D. Grouping on a
VARIANTcolumn is unsupported regardless of what else the query selects; extracting a scalar field elsewhere in the query does not make the raw variant expression itself groupable inGROUP BY. - E. Equality comparisons and joins on raw
VARIANTvalues are not supported, so two variant expressions cannot be joined directly the way two STRUCT values might be compared field by field. - F. Clustering keys, including Liquid Clustering keys, cannot be defined on a
VARIANTcolumn; enabling Liquid Clustering on the table does not lift this restriction for the variant-typed column itself.
Sources
(6)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“you should use variant over JSON strings whenever storing semi-structured data that requires flexibility for changing or unknown schema”
↩︎ Why VARIANT instead of a JSON string or a STRUCT“allows it to replace native Spark complex types such as structs and arrays in some use cases”
↩︎ Why VARIANT instead of a JSON string or a STRUCT“The [*] syntax is not support for identifying or unpacking all elements in an array.”
↩︎ Navigating a variant with : paths, dots, brackets and indexes“Checks whether the expression is storing a VARIANT encoded NULL. Use is null to check if the input expression is NULL.”
↩︎ What a VARIANT column cannot do, and how to model around it“Databricks recommends variant as a replacement for storing semi-structured data using JSON strings.”
↩︎ Key concept“All variant path elements are matched in a case-sensitive way. JSON strings are case-insensitive.”
↩︎ Exam trap 3“All variant path elements are matched in a case-sensitive way. JSON strings are case-insensitive.”
↩︎ Checkpoint - 2.
“The type supports storing semi-structured data OBJECT, ARRAY, and scalar types.”
↩︎ Why VARIANT instead of a JSON string or a STRUCT“try_cast function to cast the VARIANT to a specific type with error toleration.”
↩︎ Extracting typed values: variant_get, try_variant_get and casts - 3.
“If the JSON string is not valid, Databricks raises MALFORMED_RECORD_IN_PARSING. To return NULL instead of an error, use the try_parse_json function.”
↩︎ Creating VARIANT columns and loading data into them“jsonStr: A STRING expression specifying a JSON document.”
↩︎ Extracting typed values: variant_get, try_variant_get and casts - 4.https://docs.databricks.com/aws/en/ingestion/variantOfficial docs
“VARIANT type can only hold records up to 16 MB in size.”
↩︎ Creating VARIANT columns and loading data into them“Because the entire record is recorded as a single VARIANT column, no schema evolution occurs during ingestion and rescuedDataColumn is not supported.”
↩︎ Creating VARIANT columns and loading data into them“In the default PERMISSIVE processing mode, overly large records are captured in the corruptRecordColumn.”
↩︎ Creating VARIANT columns and loading data into them“Databricks recommends extracting frequently queried fields and storing them as non-variant columns to accelerate queries and optimize storage layout.”
↩︎ What a VARIANT column cannot do, and how to model around it - 5.
“If the path cannot be found, or if the array-index is out of bounds, the result is null.”
↩︎ Navigating a variant with : paths, dots, brackets and indexes“A field name that contains a period or square brackets returns NULL when escaped with backticks”
↩︎ Navigating a variant with : paths, dots, brackets and indexes“VARIANT columns cannot be used for clustering keys, partitions, or Z-order keys.”
↩︎ What a VARIANT column cannot do, and how to model around it“The VARIANT data type cannot be used for comparisons, grouping, ordering, and set operations.”
↩︎ Exam trap 2 - 6.
“If the object is found but cannot be cast to the desired type, Databricks raises INVALID_VARIANT_CAST.”
↩︎ Extracting typed values: variant_get, try_variant_get and casts“If the object is found but cannot be cast to the desired type, Databricks raises INVALID_VARIANT_CAST.”
↩︎ Exam trap 1“If the object cannot be found, NULL is returned. If the object is found but cannot be cast to the desired type, Databricks raises INVALID_VARIANT_CAST.”
↩︎ Checkpoint