CertSafari
    Databricks Certified Data Engineer Professional - October 9 onwards· Lessons

    Domain 3 · Lesson 19/45

    VARIANT data type: parse_json, variant_get and path queries

    Develop a model and query semi-structured data using the VARIANT data type and related functions (e.g., parse_json, variant_get).

    17 min read
    3% of exam
    6 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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 functions and the JSON-string functions they replace
    Variant functionJSON string functionBehaviour to know
    variant_getcast and get_json_objectTakes an expression, path and type; follows variant path, casting and null rules
    try_variant_gettry_cast and get_json_objectSame arguments as variant_get, but tolerates failed casts
    is_variant_nullis nullChecks for a VARIANT-encoded NULL; use is null to check whether the expression itself is NULL
    schema_of_variant / schema_of_variant_aggschema_of_json / schema_of_json_aggInfers a schema; conflicting types are derived as VARIANT
    variant_explode / variant_explode_outerexplode / explode_outerOutputs 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?

    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?

    Sources12

    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.

    CTAS that extracts id as a column and keeps the full document as VARIANTsql
    CREATE TABLE table_name AS
      SELECT json_string:id AS id,
        PARSE_JSON(json_string) variant_column
      FROM source_data

    For 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.

    Auto Loader writing every JSON record into a single VARIANT columnpython
    (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")
    )

    Sources34

    3.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']".

    Escaping field names that contain a space and a colonsql
    -- Enclose a field name that contains special characters in single quotes inside square brackets.
    SELECT raw:['zip code'], raw:['fb:testid'] FROM store_data

    Two 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.

    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?

    Sources15

    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.

    variant_get: a found value, a missing path, and a cast that failssql
    -- 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.

    The ?:: operator: a found value, a missing path, and a failed cast all give a value or NULL, never an errorsql
    > 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;
     null

    Checkpoint 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.

    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?

    Sources623

    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?

    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)

    0 of 3 selected

    Sources541

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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. 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. 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. 4.
      “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. 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. 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

    Spotted a mistake, or was something unclear? Tell us.