Introduction
In the previous articles, we explored three important complex data types in Databricks SQL: STRUCT, ARRAY and MAP. These types are useful when working with nested data. But what happens when the structure of your incoming JSON data is not always the same?
For example:
- One JSON record contains a phone_number, while another does not.
- A new API version introduces additional fields.
- Different records contain different attributes.
- You do not know the complete JSON structure in advance.
This is where the VARIANT data type becomes useful.In this article, we will explore what VARIANT is, how to store JSON data in a VARIANT column, and how to extract fields from it using Databricks SQL.
We are building upon what we already have :
- Databricks series : Starting a new python project in Visual Studio Code (Part I)
- Databricks series : setting up a connection to Databricks from local IDE (Part II)
- Databricks series : Setting up a Databricks project in Visual Studio Code (part III)
- Databricks series : Deployment from Visual Studio Code (Part IV)
- Databricks series : Execute the job in Databricks (Part V)
- Databricks series : A configrable framework in Databricks (Part VI)
- Databricks series : Loading strategies in Databricks (Part VII)
- Databricks series : Data contracts in Databricks (Part VIII)
- Databricks series : Debugging Python code in Visual Studio Code with arguments (Part IX)
- Databricks series : ODCS Data contracts in Databricks (Part X)
- Databricks series : reading an API (Part XI)
- Databricks series : Building a mediallion architecture with SCD Type 2 (step 1)(Part XII)
- Databricks series : Building a mediallion architecture with SCD Type 2 (step 2) (Part XIII)
- Databricks series : Building a mediallion architecture with SCD Type 2 (step 3) (Part XIV)
- Databricks series : Working with JSON in Databricks SQL : STRUCT
- Databricks series : Working with JSON in Databricks SQL : ARRAY
- Databricks Series : Working with JSON in Databricks SQL : MAP
What is VARIANT?
VARIANT is a data type designed for storing semi-structured data. Unlike a STRUCT, where you define the fields and their data types in advance, VARIANT allows you to store JSON data without having to define the complete structure first. For example, imagine that you receive these two JSON records:
record 1
{ "customer_id": 1001, "name": "Jan Jansen", "country": "Netherlands" }
Record 2
{ "customer_id": 1002, "name": "Sarah Johnson", "country": "USA", "email": "sarah@example.com", "preferences": { "language": "English", "newsletter": true } }
Both records have some common fields, but the second record contains additional information. With a traditional STRUCT, you would need to define a schema that accommodates these fields. With VARIANT, you can store both JSON records in the same column without first defining all their fields.
This makes VARIANT particularly useful when working with:
- REST APIs
- JSON files
- Event streams
- Changing data structures
- Semi-structured source data
2. Create a table with a VARIANT column
Let's start by creating a table in Databricks. We will store the customer information in a column called payload.
CREATE OR REPLACE TABLE main.demo.customer_variant ( payload VARIANT );
Notice that we do not define individual columns for customer_id, name or country. The complete JSON document will be stored in the payload column.
Insert JSON data using PARSE_JSON
To convert a JSON string into a VARIANT value, Databricks provides the PARSE_JSON() function.
Let's insert two customer records.
INSERT INTO main.demo.customer_variant VALUES ( PARSE_JSON( '{ "customer_id": 1001, "name": "Jan Jansen", "country": "Netherlands" }' ) ), ( PARSE_JSON( '{ "customer_id": 1002, "name": "Sarah Johnson", "country": "USA", "email": "sarah@example.com", "preferences": { "language": "English", "newsletter": true } }' ) );
The PARSE_JSON() function converts the JSON string into a VARIANT value. You can now query the table:
SELECT * FROM main.demo.customer_variant;
Results in :
The complete JSON document is stored in one column.
4. Extract fields from VARIANT
Storing the complete JSON document is useful, but in most cases you also want to access individual fields. Databricks SQL supports the colon (:) operator to navigate through VARIANT data.
For example:
SELECT payload:customer_id AS customer_id, payload:name AS customer_name, payload:country AS country FROM main.demo.customer_variant;
Results in :
You may notice that the extracted values are still VARIANT values.
SELECT TYPEOF(payload) AS payload_type, TYPEOF(payload:customer_id) AS customer_id_type, TYPEOF(payload:name) AS name_type FROM main.demo.customer_variant;
Resulting in :
If you want to work with them as regular SQL data types, you can cast them.
SELECT payload:customer_id::INT AS customer_id, payload:name::STRING AS customer_name, payload:country::STRING AS country FROM main.demo.customer_variant;
Resulting in :
Now the extracted fields have explicit SQL data types.
5. Access nested fields
VARIANT also supports nested JSON structures. Remember that our second customer record contains a preferences object:
{ "preferences": { "language": "English", "newsletter": true } }
You can access nested fields using the same colon notation.
SELECT payload:customer_id::INT AS customer_id, payload:preferences:language::STRING AS language, payload:preferences:newsletter::BOOLEAN AS newsletter FROM main.demo.customer_variant;
REsulting in :
The result for the first customer will contain NULL values because that record does not have a preferences object. The second customer will return the language and newsletter preference. This is one of the benefits of VARIANT: records do not all need to contain exactly the same fields.
Access arrays inside VARIANT
VARIANT can also contain arrays. Let's insert another customer with a list of orders.
INSERT INTO main.demo.customer_variant VALUES ( PARSE_JSON( '{ "customer_id": 1003, "name": "Peter Smith", "country": "UK", "orders": [ { "order_id": 5001, "amount": 125.50 }, { "order_id": 5002, "amount": 89.99 } ] }' ) );
You can access an individual array element using its index. Remember that array indexing starts at zero.
SELECT payload:customer_id::INT AS customer_id, payload:orders[0]:order_id::INT AS first_order_id, payload:orders[0]:amount::DECIMAL(10,2) AS first_order_amount FROM main.demo.customer_variant;
Resulting in :
This example retrieves the first order from the array. If you want to retrieve all orders as separate rows, you can use VARIANT_EXPLODE. This turns the array elements into separate rows.
Inspect the structure of VARIANT data
Sometimes you receive JSON data without knowing its exact structure. Databricks provides the SCHEMA_OF_VARIANT() function to inspect the structure of an individual VARIANT value.
SELECT SCHEMA_OF_VARIANT(payload) AS detected_schema FROM main.demo.customer_variant;
This returns a schema description based on the contents of the VARIANT value. You can also use SCHEMA_OF_VARIANT_AGG() to derive a combined schema from multiple records.
SELECT SCHEMA_OF_VARIANT_AGG(payload) AS combined_schema FROM main.demo.customer_variant;
Resulting in :
This can be helpful when exploring new or changing data sources.
8. Handle invalid JSON
What happens when the incoming JSON is not valid? For example:
{ "customer_id": 1004, "name": "Invalid JSON"
The JSON document is missing a closing brace. Using PARSE_JSON() on malformed JSON raises an error. If you prefer to return NULL instead of stopping the operation, you can use TRY_PARSE_JSON().
SELECT TRY_PARSE_JSON('{"customer_id": 1004, "name": "Invalid JSON"') AS payload;
This returns NULL when the JSON cannot be parsed. This can be useful when ingesting data from external systems where the input is not always reliable.
VARIANT versus STRUCT, ARRAY and MAP
We have now seen how VARIANT works. But when should you use it instead of STRUCT, ARRAY or MAP?
A simple rule of thumb:
Use STRUCT when you know the structure and want strongly typed fields.
Use ARRAY when you need an ordered list of values.
Use MAP when you need key-value pairs.
Use VARIANT when the structure of your incoming data can change or is not known in advance.
VARIANT does not mean that you should store every field in one JSON column forever. If you frequently query fields such as customer_id, country or event_timestamp, it is often better to extract those fields into regular typed columns. This makes the data easier to use in analytical queries and helps with data organization and performance.
Important considerations
There are a few things to keep in mind when using VARIANT in Databricks:
- VARIANT is supported in Databricks SQL and Databricks Runtime 15.3 and above.
- VARIANT is designed for semi-structured data such as JSON objects, arrays and scalar values.
- JSON field names are case-sensitive.
- A VARIANT column cannot be used as a partitioning or clustering key, or in operations such as GROUP BY and ORDER BY.
- Frequently queried fields should generally be extracted into regular columns.
Always check the supported features of the Databricks Runtime or SQL warehouse you are using.
Conclusion
The VARIANT data type adds another useful option when working with semi-structured data in Databricks. Where STRUCT, ARRAY and MAP require you to work with defined data structures, VARIANT gives you more flexibility when the structure of your incoming JSON data is unknown or changes over time. It is particularly useful in ingestion and raw data layers, where you may want to preserve the original payload before deciding how to transform and model it. Once the data is understood, you can extract the relevant fields and move them into structured tables for further processing and analytics.
In short: VARIANT gives you flexibility at ingestion time, while STRUCT, ARRAY and MAP provide more explicitly defined structures for working with your data.























