Bronze tables full of JSON usually end up one of two ways. Either the payload is a STRING that every query parses again with from_json or get_json_object, or it is a STRUCT that breaks whenever the producer adds or retypes a field. VARIANT stores semi-structured data in a binary encoding. Path lookups are fast, and the schema does not need to be fixed when you write. This cheat sheet covers the syntax and the design rules for running it in production.
Important
A column of type
VARIANTadds thevariantTypetable feature to the Delta table. Readers outside Databricks need a Delta client that supports it. Check Power BI, Synapse and Fabric support before you convert a table they read.
Choosing a type
| Need | STRING (raw JSON) | STRUCT | VARIANT |
|---|---|---|---|
| Producer schema changes often | Works, parse cost on every read | Breaks or needs schema evolution | Works |
| Fast field extraction | Slow, re-parses text | Fastest | Fast |
Mixed types for one field ("42" vs 42) | Keeps the text | Fails or nulls | Keeps each value's own type |
| File skipping on a field | No | Yes (stats on columns) | Don't rely on it; promote the field |
| External readers | Any | Any | Need variantType support |
A common pattern is VARIANT in bronze, typed columns in silver, with only the fields people actually query.
Ingest
-- One VARIANT column per JSON record, straight from files
CREATE OR REPLACE TABLE bronze.events_raw AS
SELECT raw, _metadata.file_path AS src_file, current_timestamp() AS ingested_at
FROM read_files(
'/Volumes/raw/landing/events/',
format => 'json',
singleVariantColumn => 'raw'
);
Auto Loader, streaming:
(spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("singleVariantColumn", "raw")
.load("/Volumes/raw/landing/events/")
.writeStream
.option("checkpointLocation", "/Volumes/raw/_chk/events_raw")
.toTable("bronze.events_raw"))
From an existing STRING column:
SELECT parse_json(payload) AS raw FROM bronze.events_text; -- fails on bad JSON
SELECT try_parse_json(payload) AS raw FROM bronze.events_text; -- NULL on bad JSON
Tip
Use
try_parse_jsonin pipelines and count the NULLs it produces from non-NULL input. Quarantine those rows. Don't let one malformed record fail the batch.
Query paths
| Task | Syntax |
|---|---|
| Field | raw:customer.id |
| Nested array element | raw:items[0].sku |
| Key with spaces or special chars | raw:['order id'] or raw:customer['e-mail'] |
| Cast while extracting | raw:amount::decimal(18,2) |
| Function form (JSONPath) | variant_get(raw, '$.amount', 'decimal(18,2)') |
| Cast that returns NULL instead of failing | try_variant_get(raw, '$.amount', 'decimal(18,2)') |
| Back to JSON text | to_json(raw:customer) |
SELECT
raw:event_id::string AS event_id,
raw:customer.id::bigint AS customer_id,
try_variant_get(raw, '$.amount', 'decimal(18,2)') AS amount,
raw:ts::timestamp AS event_ts
FROM bronze.events_raw
WHERE raw:event_type::string = 'purchase';
Path keys are case sensitive. raw:Customer and raw:customer are different fields, unlike column names.
Warning
::raises an error when the value cannot be cast, for example the string"n/a"cast todecimal. One bad record then fails the whole query. Usetry_variant_get(ortry_cast) in production transformations, and count the NULLs.
Nulls: JSON null vs missing
| Value in JSON | raw:x | raw:x IS NULL | is_variant_null(raw:x) |
|---|---|---|---|
"x": 5 | 5 | false | false |
"x": null | variant null | false | true |
| field missing | SQL NULL | true | false |
SELECT
count_if(raw:discount IS NULL) AS discount_missing,
count_if(is_variant_null(raw:discount)) AS discount_json_null
FROM bronze.events_raw;
Data quality checks that only test IS NULL miss explicit JSON nulls.
Arrays and objects
-- One row per array element
SELECT e.raw:event_id::string AS event_id,
i.pos,
i.value:sku::string AS sku,
i.value:qty::int AS qty
FROM bronze.events_raw e,
LATERAL variant_explode(e.raw:items) AS i;
variant_explode returns pos, key and value. For an object, key is the field name. For an array, key is NULL. Use variant_explode_outer to keep rows whose array is missing or empty.
Discover the schema
-- Type of one value
SELECT schema_of_variant(raw) FROM bronze.events_raw LIMIT 5;
-- Merged schema across many rows (sample first on big tables)
SELECT schema_of_variant_agg(raw)
FROM bronze.events_raw TABLESAMPLE (1 PERCENT);
-- Schema per event type, to spot producers that drift
SELECT raw:event_type::string AS event_type, schema_of_variant_agg(raw) AS schema
FROM bronze.events_raw
GROUP BY 1;
When types conflict across rows, for example amount is sometimes a string and sometimes a number, the merged schema shows VARIANT for that field. That tells you to fix the producer, or to cast with try_variant_get in silver.
Promote hot fields to silver
Fields used in filters, joins or clustering should become real columns:
CREATE OR REPLACE TABLE silver.purchases
CLUSTER BY (event_date, customer_id) AS
SELECT
raw:event_id::string AS event_id,
try_variant_get(raw, '$.customer.id', 'bigint') AS customer_id,
try_variant_get(raw, '$.amount', 'decimal(18,2)') AS amount,
to_date(try_variant_get(raw, '$.ts', 'timestamp')) AS event_date,
raw AS payload -- keep the rest
FROM bronze.events_raw
WHERE raw:event_type::string = 'purchase';
Keeping payload lets analysts reach rare fields without another schema change.
Limits and gotchas
| Gotcha | What to do |
|---|---|
VARIANT cannot be used directly in GROUP BY, ORDER BY, join keys, comparison, partitioning or clustering keys | Extract and cast the field first |
| Map keys must be strings | JSON objects always are; matters only when you build variants from Spark maps |
| Very large single values | There is a per-value size limit; check the current limit in the VARIANT type docs before you store whole documents |
| Older runtimes and external clients fail to read the table | Keep VARIANT tables for Databricks readers, or expose typed views and silver tables to the others |
typeof-style checks | schema_of_variant(raw:x) returns the type of one value |
| PySpark | parse_json, try_variant_get and friends are in pyspark.sql.functions on runtimes based on Spark 4.0; on older runtimes use F.expr("...") |
from pyspark.sql import functions as F
df = spark.table("bronze.events_raw").select(
F.expr("raw:event_id::string").alias("event_id"),
F.expr("try_variant_get(raw, '$.amount', 'decimal(18,2)')").alias("amount"),
)
Migrating a STRING JSON column
- Add the column:
ALTER TABLE bronze.events ADD COLUMN raw VARIANT; - Backfill in batches by date:
UPDATE bronze.events SET raw = try_parse_json(payload) WHERE event_date = '2026-11-01'; - Compare row counts where
payload IS NOT NULL AND raw IS NULLto find malformed JSON. - Change readers to use
raw, then droppayloadlater. Dropping a column needs column mapping, which is another table feature that external readers must support.
Prevent it next time
- Decide which layer owns typing. Bronze keeps VARIANT, silver casts with
try_variant_get. - Schedule a
schema_of_variant_aggcheck per event type and alert when a field's type changes. - Promote any field that appears in more than a few
WHEREclauses. You can see these in query history. - Confirm that every downstream reader supports
variantTypebefore you add a VARIANT column to a shared table.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get