What you will be able to do
- Choose between typed structured columns and a VARIANT column, and convert JSON text with PARSE_JSON
- Extract VARIANT values with colon, dot and bracket notation or GET_PATH, handling case and quoting correctly
- Cast extracted values with :: and check runtime types with TYPEOF
- Turn nested arrays into rows with LATERAL FLATTEN while keeping parent columns
- Filter or transform arrays in place with higher-order functions
- Produce scoped, file or pre-signed URLs from a directory table so unstructured files can be processed
Key concept
VARIANT value plus type — A VARIANT holds a value together with its data type. A path such as src:vehicle[0].make returns another VARIANT. To get a plain SQL value, without JSON quoting, you cast it with ::.
1.Structured columns versus semi-structured VARIANT data
Data reaches a Snowflake transformation in one of three shapes. Structured data sits in typed relational columns, such as a table simple (x INTEGER, y INTEGER) where every row has the same fields. Semi-structured data, usually JSON, Avro, ORC or Parquet, normally lands in a single VARIANT column with arrays and objects nested inside it. Unstructured data, such as PDFs, images and audio, stays as files on a stage and you reach it through URLs and file functions.
A VARIANT records each value together with its type. That means a VARIANT holding a number can go straight into arithmetic, like my_variant_column * 3.14, without a cast. For mostly regular data made of native JSON types such as strings and numbers, storage and query performance in a VARIANT is close to that of relational columns. Dates and timestamps are the exception. Inside a VARIANT they are stored as strings, so operations on them can be slower and take more space than the same values in a typed DATE or TIMESTAMP column. Fields you filter or compute on often are good candidates to move out of the VARIANT into typed columns during transformation.
JSON that arrives as plain VARCHAR text is not yet a VARIANT. Path notation works on VARIANT values, so the text has to be converted with PARSE_JSON first. The sample car_sales table used below is built exactly this way: SELECT PARSE_JSON(column1) AS src. Each row's src then holds a dealership, a salesperson object, and customer and vehicle arrays.
Checkpoint 1 of 7· Fill the gap
Each row in VALUES holds JSON as plain VARCHAR text. Which function fills the blank so that src becomes a VARIANT whose nested objects and arrays you can query with path notation such as src:salesperson.name?
CREATE OR REPLACE TABLE car_sales
(
src variant
)
AS
SELECT ? (column1) AS src
FROM VALUESPath notation only works on VARIANT values, so JSON text stored as VARCHAR is not yet a VARIANT. PARSE_JSON reads the text and turns it into a VARIANT that holds the nested objects and arrays. TO_JSON does the opposite and turns a VARIANT into text. TO_VARIANT would keep the whole input as a single string value, so the JSON inside it would never be parsed.
Source: docs.snowflake.com2.Path notation, GET_PATH, case and quoting
A colon after the column name takes you into the VARIANT. From there, a dot steps into an object and [n] picks an array element by position, as in src:vehicle[0].make. Bracket notation reaches the same element with single-quoted names: src['salesperson']['name']. Either way, the result is still a VARIANT, so string results print wrapped in double quotes.
Case matters only after the colon. src and SRC name the same column, but Salesperson is a different key from salesperson. JSON keys also follow different rules from SQL identifiers, so a key that is not a valid identifier must be double-quoted in the path. That covers keys containing a space (src:"company name"), keys starting with a digit (zipcode_info:"94987"), and keys with symbols (measurements:"#sPerSquareInch").
SELECT src:salesperson.name
FROM car_sales
ORDER BY 1;
+----------------------+
| SRC:SALESPERSON.NAME |
|----------------------|
| "Frank Beasley" |
| "Greg Northrup" |
+----------------------+Path syntax is shorthand for the GET and GET_PATH functions. GET_PATH takes the path as a string and is equivalent to a chain of GET calls. Use the functions when the path itself is irregular. Take a colors table whose VARIANT column v holds one array of objects per row: [{r:255,g:12,b:0},{r:0,g:255,b:0},{r:0,g:0,b:255}] in the first row and [{c:0,m:1,y:1,k:0},{c:1,m:0,y:1,k:0},{c:1,m:1,y:0,k:0}] in the second. GET(v, ARRAY_SIZE(v)-1) computes the position of the last element instead of typing it, and returns {"b": 255, "g": 0, "r": 0} for the first row and {"c": 1, "k": 0, "m": 1, "y": 0} for the second. A hard-coded index cannot do this once the arrays differ in length.
SELECT GET_PATH(src, 'vehicle[0].make') FROM car_sales;
SELECT src:vehicle[0].make FROM car_sales;| Form | Example | When to reach for it |
|---|---|---|
| Dot notation | src:salesperson.name | Everyday paths through objects |
| Quoted dot notation | src:"company name" | Keys that are not valid SQL identifiers |
| Bracket notation | src['salesperson']['name'] | Same traversal, with single-quoted element names |
| Array index | src:vehicle[0].make | A fixed position in an array |
| GET_PATH / GET | GET(v, ARRAY_SIZE(v)-1) | Irregular or computed paths |
Checkpoint 2 of 7· Check yourself
A partners table has a VARIANT column src. Its JSON includes the key "company name", which contains a space. Which of these expressions correctly returns that element?
JSON keys follow different rules from SQL identifiers. A key with a space is not a valid identifier, so in dot notation it has to be put in double quotes. Single quotes belong to bracket notation, not dot notation. A key also cannot be renamed or changed to upper case, because element names must match the JSON key exactly.
“if it contains spaces, then you must enclose the name in double quotes”Source: docs.snowflake.com
Sources2
3.Casting extracted values and checking their type
VARCHAR, DATE, TIME and TIMESTAMP values read out of a VARIANT come back wrapped in double quotes. Casting with :: to the underlying type removes the quotes and gives you an ordinary SQL value that you can compare, join and store in a typed column. Write src:salesperson.name::VARCHAR to get Frank Beasley instead of "Frank Beasley". Numbers work the same way: my_variant_column::FLOAT.
SELECT 'Sample', 'Sample'::VARIANT, 'Sample'::VARIANT::VARCHAR;
+----------+-------------------+----------------------------+
| 'SAMPLE' | 'SAMPLE'::VARIANT | 'SAMPLE'::VARIANT::VARCHAR |
|----------+-------------------+----------------------------|
| Sample | "Sample" | Sample |
+----------+-------------------+----------------------------+TYPEOF returns the native type stored in a VARIANT. This matters when the same field arrives in different shapes from different upstream sources. Say attributes is an array in some records and a single object in others. Testing TYPEOF first lets a script send arrays to array logic and objects elsewhere.
A VARIANT can be empty in two different ways, and the data means something different in each. SQL NULL says no value is there; a VARIANT null is a real value that records the JSON null itself. PARSE_JSON(NULL) returns SQL NULL, while PARSE_JSON('null') returns a VARIANT null, because a null input string is read as a value rather than as absence. The distinction survives into later steps: a VARIANT null compares as equal to itself, and when elements are cast to a type that cannot hold JSON nulls, such as ARRAY(NUMBER), they become SQL NULL, whereas casting to ARRAY(VARIANT) leaves them as VARIANT nulls.
Checkpoint 3 of 7· Check yourself
You want to load the salesperson's name into a typed VARCHAR column. The query src:salesperson.name returns "Frank Beasley", with the double quotes. Which expression gives you the plain SQL value Frank Beasley?
Dot notation, bracket notation and GET_PATH are all ways of walking the same path, and each one still returns a VARIANT, so the string keeps its double quotes. Bracket notation's "strings" are VARIANT strings, which is why its output also shows "Frank Beasley" in quotes. Only a :: cast to VARCHAR turns the value into an ordinary SQL value without quotes.
“Enclose element names in single quotes. Values are retrieved as strings.”Source: docs.snowflake.com
4.Turning nested arrays into rows with LATERAL FLATTEN
FLATTEN is a table function. It takes a VARIANT, OBJECT or ARRAY and produces one row per element, which turns nested data into relational rows. Every output row has the same fixed columns. VALUE holds the element itself, INDEX its array position (NULL for objects), KEY the key when an object is flattened, PATH the element's path, THIS the compound being flattened, and SEQ a sequence number for the input record.
SELECT * FROM TABLE(FLATTEN(INPUT => PARSE_JSON('{"a":1, "b":[77,88]}'), PATH => 'b')) f;
+-----+------+------+-------+-------+-------+
| SEQ | KEY | PATH | INDEX | VALUE | THIS |
|-----+------+------+-------+-------+-------|
| 1 | NULL | b[0] | 0 | 77 | [ |
| | | | | | 77, |
| | | | | | 88 |
| | | | | | ] |
| 1 | NULL | b[1] | 1 | 88 | [ |
| | | | | | 77, |
| | | | | | 88 |
| | | | | | ] |
+-----+------+------+-------+-------+-------+Used as a lateral join, FLATTEN keeps the columns of the table it reads from. When one source row expands into several, its column values are copied onto each output row. Take an ORDERS table whose VARIANT payload holds a line_items array. Writing FROM orders, LATERAL FLATTEN(input => payload:line_items) f gives one row per line item with order_id on every row. Then f.value:sku::string and f.value:qty::number pull out each element's fields as typed values.
The alternatives fail for clear reasons. A hard-coded index such as payload:line_items[0] returns one element per order, so any order with more items loses them, and stacking [0], [1], [2] breaks as soon as array lengths differ. ARRAY_AGG goes the other way: as an aggregate, it collapses many rows into one array instead of expanding one array into many rows.
Two settings control the edges. By default, an input row whose array is empty, or whose path does not exist, is dropped from the output. Set OUTER => TRUE to keep one row for it, with NULL in KEY, INDEX and VALUE. For arrays nested inside arrays, chain FLATTEN calls with LATERAL so that each call can read the previous call's output. For a single-level array, TABLE(FLATTEN(...)) and LATERAL FLATTEN(...) give the same result.
With the default OUTER => FALSE, input rows that expand to zero rows are left out completely. Adding OUTER => TRUE produces one row for each such order, with NULL in VALUE, so the order_id still appears.
Checkpoint 4 of 7· Check yourself
An ORDERS table stores each order's line items in the payload:line_items array. You need one output row per line item. A teammate suggests ARRAY_AGG(payload:line_items) in place of LATERAL FLATTEN. Why won't that produce the rows you need?
ARRAY_AGG is listed among the aggregate functions, and an aggregate takes many input rows and returns a single output. That is the opposite of what you need here. FLATTEN is the table function that turns each array element into its own row. OUTER => TRUE is a FLATTEN setting, not an ARRAY_AGG one, and casting with :: has nothing to do with how many rows a query returns.
“An aggregate function takes multiple rows (actually, zero, one, or more rows) as input and produces a single output.”Source: docs.snowflake.com
Checkpoint 5 of 7· Exam question
A table ORDERS has a VARIANT column PAYLOAD holding each order's JSON, including a nested array line_items whose elements are objects with sku and qty keys. An analyst needs one output row per line item, keeping the parent order_id column from ORDERS attached to each row. Which approach correctly produces this result?
Correct answer: A — Join ORDERS to a LATERAL FLATTEN call on payload:line_items, then select order_id with value:sku::string and value:qty::number from the flattened rows.
- A. LATERAL FLATTEN explodes a VARIANT array into one row per element while keeping outer columns like
order_idin scope, which is exactly the join pattern needed to pair each line item with its parent order. - B. Hardcoding array index offsets only works if every order has the same fixed number of line items, and it silently drops or duplicates rows whenever the array length varies between orders.
- C. Aggregating with ARRAY_AGG followed by picking one element collapses the array back into a single representative value per order, which is the opposite of producing a row per line item.
- D. JSON text does not have a fixed comma-delimited layout that SPLIT_PART can reliably parse, so treating the VARIANT as a flat string breaks as soon as formatting or field order changes.
Sources5
5.Working on arrays in place with FILTER, TRANSFORM and REDUCE
Sometimes the result should stay an array, for example the same list with some elements dropped or every element rewritten. Then flattening to rows and aggregating back is a detour. The higher-order functions FILTER, TRANSFORM and REDUCE take an array and a lambda expression and work on it directly. They apply to both semi-structured and structured data. Without them, this kind of per-element work needs LATERAL FLATTEN or a user-defined function.
A lambda puts its argument to the left of -> and an expression to the right. It can declare argument types, call built-in functions and SQL UDFs, reference table columns, and run an uncorrelated scalar subquery. When a name could mean either, lambda arguments win over column names.
| Lambda | Effect on each element |
|---|---|
| a -> a * 2 | Doubles a numeric element |
| a -> a:value > 50 | Keeps elements whose value exceeds 50 (as a FILTER condition) |
| a -> a || ' some string' | Appends text |
| a -> a - table1.col2 | Subtracts a table column's value |
| (x INT, y INT) -> (x + y) | Adds two typed arguments |
Lambdas have firm limits. A lambda only exists as an argument to a higher-order function and must be anonymous. It cannot contain aggregate or window functions, UDFs written in languages other than SQL, CTE references or correlated subqueries. Use LATERAL FLATTEN when you need elements as rows to join or group on. Use a higher-order function when you want an array back.
Checkpoint 6 of 7· Check yourself
Which of these lambda expressions, passed to FILTER or TRANSFORM, would Snowflake reject?
A lambda cannot contain aggregate or window functions, so AVG(...) OVER () is rejected. A lambda can reference table columns, declare argument types and run an uncorrelated scalar subquery, so the other three are valid.
“Lambda expressions only accept built-in functions (excluding aggregate and window functions), SQL user-defined functions, and uncorrelated scalar subqueries.”Source: docs.snowflake.com
Sources2
6.Unstructured files: URLs from the directory table, then processing
Unstructured data is anything without a predefined data model: form responses, images, video, audio and industry formats such as VCF or HDF5. It lives on internal or external stages. A stage's Directory tables store a queryable catalog of its files. Transformation starts by selecting relative_path from DIRECTORY(@stage) and passing it to a URL function.
| URL type | Generate with | Who can use it | Expires |
|---|---|---|---|
| Scoped URL | BUILD_SCOPED_FILE_URL | Only the user who generated it; grants no stage privileges | When the query results cache period ends (currently 24 hours) |
| File URL | Directory table query or BUILD_STAGE_FILE_URL | Roles with USAGE (external) or READ (internal) on the stage | Permanent |
| Pre-signed URL | GET_PRESIGNED_URL | Anyone holding the URL, without authenticating | After the expiration_time you set |
Choose the URL type based on who will open it. A web app or BI tool that only needs to display images suits a pre-signed URL. Anyone can open it in a browser until it expires, so keep the expiry short. A scoped URL suits code and roles inside the account, and Snowflake logs in query history who used it and when.
SELECT GET_PRESIGNED_URL(@mystage, relative_path, 60) AS presigned_url
FROM DIRECTORY(@mystage);Processing reads the file from inside SQL. When you pass a file to a UDF or procedure, for example a PDF text extractor, pass a scoped URL from BUILD_SCOPED_FILE_URL so the code resists file injection. This matters most when the caller does not own the function. AI functions such as AI_PARSE_DOCUMENT can do the extraction as one step of the transformation (the wider Cortex AI functions, Cortex Search, Cortex Analyst family is covered separately). AI_PARSE_DOCUMENT returns a JSON-formatted string, so wrap it in PARSE_JSON to get a VARIANT you can query with the path notation above.
Checkpoint 7 of 7· Check yourself
A transformation calls AI_PARSE_DOCUMENT on a staged PDF and wants to read one field from the result with path notation, such as result:content. What has to happen to the function's output first?
AI_PARSE_DOCUMENT returns JSON as text, and JSON text is not yet a VARIANT. Path syntax reads elements from VARIANT values, so PARSE_JSON has to convert the string first. Casting to VARCHAR keeps the value as text. FLATTEN expects a VARIANT, OBJECT or ARRAY as input. It does not parse a string.
“Traversing Semi-structured Data describes the path syntax used to retrieve elements in a VARIANT column.”Source: docs.snowflake.com
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“For non-native data (such as dates and timestamps), the values are stored as strings when loaded into a VARIANT column.”
↩︎ Structured columns versus semi-structured VARIANT data“the performance is very similar for storage and query operations on relational data and data in a VARIANT column”
↩︎ Structured columns versus semi-structured VARIANT data“You can eliminate the double quotes by explicitly casting the values to the underlying data types”
↩︎ Casting extracted values and checking their type“native data type by using the TYPEOF function”
↩︎ Casting extracted values and checking their type“VARIANT null is a true value that compares as equal to itself.”
↩︎ Casting extracted values and checking their type“VARIANT data stores both the value and the data type of the value.”
↩︎ Key concept - 2.
“SELECT PARSE_JSON(column1) AS src”
↩︎ Structured columns versus semi-structured VARIANT data“then you must enclose the name in double quotes”
↩︎ Path notation, GET_PATH, case and quoting“Unlike the path syntax, these functions can handle irregular paths or path elements.”
↩︎ Path notation, GET_PATH, case and quoting“GET_PATH is equivalent to a chain of GET functions.”
↩︎ Path notation, GET_PATH, case and quoting“SELECT *, GET(v, ARRAY_SIZE(v)-1) FROM colors;”
↩︎ Path notation, GET_PATH, case and quoting“if the input string is null, it is interpreted as a VARIANT null value”
↩︎ Casting extracted values and checking their type“Without higher-order functions, this type of manipulation requires LATERAL FLATTEN operations or user-defined functions (UDFs).”
↩︎ Working on arrays in place with FILTER, TRANSFORM and REDUCE“Lambda expressions only accept built-in functions (excluding aggregate and window functions), SQL user-defined functions, and uncorrelated scalar subqueries.”
↩︎ Working on arrays in place with FILTER, TRANSFORM and REDUCE“The resolution of identifiers prioritizes lambda arguments first, then column names”
↩︎ Working on arrays in place with FILTER, TRANSFORM and REDUCE“the column name is case-insensitive but element names are case-sensitive”
↩︎ Exam trap 1“the column name is case-insensitive but element names are case-sensitive”
↩︎ Prediction“if it contains spaces, then you must enclose the name in double quotes”
↩︎ Checkpoint“Enclose element names in single quotes. Values are retrieved as strings.”
↩︎ Checkpoint“Traversing Semi-structured Data describes the path syntax used to retrieve elements in a VARIANT column.”
↩︎ Checkpoint - 3.
“Unstructured data is information that does not fit into a predefined data model or schema.”
↩︎ Structured columns versus semi-structured VARIANT data“Ideal for business intelligence applications or reporting tools that need to display the unstructured file contents.”
↩︎ Unstructured files: URLs from the directory table, then processing“Pre-signed URLs are open; any user or application can directly access or download the files.”
↩︎ Exam trap 3 - 4.
“if you are casting to ARRAY(NUMBER), JSON null values are converted to NULL”
↩︎ Casting extracted values and checking their type - 5.
“FLATTEN can be used to convert semi-structured data to a relational representation.”
↩︎ Turning nested arrays into rows with LATERAL FLATTEN“If TRUE, exactly one row is generated for zero-row expansions (with NULL in the KEY, INDEX, and VALUE columns).”
↩︎ Turning nested arrays into rows with LATERAL FLATTEN“use LATERAL so that each subsequent FLATTEN can reference the output of the previous one.”
↩︎ Turning nested arrays into rows with LATERAL FLATTEN“the values in this input row are replicated to match the number of rows produced by FLATTEN.”
↩︎ Exam trap 2 - 6.
“To make your code resilient to file injection attacks, always use a scoped URL”
↩︎ Unstructured files: URLs from the directory table, then processing - 7.
“Returns the extracted content from a document on a Snowflake stage as a JSON-formatted string.”
↩︎ Unstructured files: URLs from the directory table, then processing - 8.
“Both views query the RELATIVE_PATH column in a directory table to retrieve the scoped or pre-signed URL.”
↩︎ Unstructured files: URLs from the directory table, then processing
Also cited
“An aggregate function takes multiple rows (actually, zero, one, or more rows) as input and produces a single output.”
↩︎ Checkpoint