CertSafari
    Snowflake SnowPro Advanced: Data Engineer (DEA-C02)· Lessons

    Domain 5 · Lesson 19/22

    Querying and building semi-structured data in Snowflake: VARIANT paths, FLATTEN, OBJECT_CONSTRUCT and ARRAY_AGG

    Handle and transform semi- structured data.

    19 min read
    3.57% of exam
    5 sources
    Published 20 Oct 2026
    Docs as of 4 Oct 2026

    What you will be able to do

    • Use colon, dot and bracket paths and GET_PATH to pull elements out of a VARIANT column
    • Cast VARIANT path results to typed columns so they work in arithmetic, comparisons and string output
    • Turn arrays and objects into rows with FLATTEN and LATERAL FLATTEN, including chained flattens over nested arrays
    • Build OBJECT values from columns or whole rows with OBJECT_CONSTRUCT, and collect rows into arrays with ARRAY_AGG

    Key concept

    A path result is still VARIANT — Every colon, dot or bracket step into a semi-structured column returns a VARIANT, not a typed SQL value. To use the result as a column you have to cast it to a concrete type, and to get one row per element you have to explode it with FLATTEN.

    1.Traversing a VARIANT with colon, dot and bracket paths

    JSON, Avro, ORC and Parquet data usually lands in Snowflake as a single VARIANT column that holds nested OBJECTs and ARRAYs. Getting that data into a structured shape starts with reaching inside the column. The standard example is a car_sales table with one VARIANT column, src. Each row is a sale with a dealership string, a salesperson object, and customer and vehicle arrays. Inside each vehicle sits a further extras array. Loading files into a VARIANT column is covered in ingesting semi-structured formats. Querying what has landed is covered here.

    The first step into the column is always a colon: <column>:<level1_element>. So src:dealership returns each sale's dealership. Deeper levels use dots, as in src:salesperson.name. Bracket notation reaches the same element: src['salesperson']['name'], with each element name in single quotes. Array elements are addressed by a zero-based index, so src:vehicle[0].make is the make of the first vehicle in each sale.

    Bracket notation returning the same salesperson names as src:salesperson.namesql
    SELECT src['salesperson']['name']
        FROM car_sales
        ORDER BY 1;

    Case is the first thing that breaks a path. The column name follows SQL identifier rules, but the keys inside it are JSON keys and must match exactly. Odd keys break paths too. A key such as company name (contains a space), 94987 (starts with a digit) or #sPerSquareInch is a valid JSON key but not a valid SQL identifier, so it has to be double-quoted: src:"company name". Any element name may be double-quoted, so quoting is always safe when you are unsure.

    An index reads exactly one element. src:vehicle[0] returns the first vehicle and nothing else. It never produces extra rows for the remaining elements. If an array's length varies from row to row, hard-coding [0], [1] and so on either misses elements or returns NULLs. That is the problem FLATTEN solves.

    Checkpoint 1 of 9· Fill the gap

    This query uses bracket notation to return each salesperson's name from the car_sales table, the same result as src:salesperson.name. Which token completes it?

    SELECT src['salesperson'] ? 
        FROM car_sales
        ORDER BY 1;

    Sources1

    2.Casting path results to typed columns, and GET_PATH

    A path expression returns a VARIANT, even when the output looks like a plain number or string. That is why src:dealership displays as "Tindel Toyota" in double quotes: the VARIANT contains a string but is not a string itself. The risk is sharpest with numbers. Each vehicle in car_sales is stored like this:

    A vehicle object from car_sales: price is a quoted stringjson
    {"make": "Honda", "model": "Civic", "year": "2017", "price": "20275", "extras":["ext warranty", "paint protection"]}

    "price": "20275" is a quoted string, so src:vehicle[0].price is a VARIANT wrapping text, even though it reads like a number.

    To get a typed column, cast with ::. For example, src:vehicle[0].price::NUMBER returns a number you can multiply, and value:name::string returns a string without the surrounding double quotes. This is the standard fix when arithmetic on a path result fails with a type error. Casting does not mean re-parsing the data. The column is already VARIANT, and calling PARSE_JSON on it a second time is not the cure. A VARIANT also records the type of the value it holds, so one holding a true JSON number can go straight into an expression. Values that arrive as JSON strings need the cast.

    The path syntax is shorthand for two functions. GET(v, n) takes a VARIANT, OBJECT or ARRAY and returns one element. GET_PATH(src, 'vehicle[0].make') takes a whole path as a string and behaves like a chain of GET calls. Both return VARIANT, just as the operators do, so switching from : to GET does not remove the need to cast. Use the functions when the path is irregular, or when the element has to be computed. For example, GET(v, ARRAY_SIZE(v)-1) reads the last element of each array, whatever the array's length.

    GET_PATH and the colon path return the same resultsql
    SELECT GET_PATH(src, 'vehicle[0].make') FROM car_sales;
    
    SELECT src:vehicle[0].make FROM car_sales;

    Checkpoint 2 of 9· Check yourself

    A data engineer wants the total sale price as a number they can multiply by a tax rate. They write src:vehicle[0].price against car_sales, where the JSON holds "price": "20275". What change gives them a typed numeric column?

    Checkpoint 3 of 9· Exam question

    A pipeline loads JSON order payloads into a table with a VARIANT column named payload. An analyst runs SELECT payload:total_amount FROM orders and then tries to multiply the result by a tax rate, but the multiplication fails with a numeric type error even though the value looks like a plain number in the output. What is the correct fix?

    Sources12

    3.Exploding arrays into rows with FLATTEN and LATERAL FLATTEN

    FLATTEN is a table function. It takes a VARIANT, OBJECT or ARRAY and returns one row per element, which turns nested data into relational rows. You write it in the FROM clause, not the SELECT list. The LATERAL keyword correlates FLATTEN with the table before it: each source row is expanded, and that row's columns are repeated on every row it produces. That repetition is how a dealership or a vehicle make ends up next to each exploded element.

    FLATTEN arguments and what each controls
    ArgumentDefaultEffect
    INPUT => exprrequiredThe VARIANT, OBJECT or ARRAY to explode into rows
    PATH => constant_exprzero-length stringThe element inside the input to flatten; empty means the outermost element
    OUTER => TRUE | FALSEFALSEFALSE drops rows that cannot be expanded; TRUE keeps one row with NULL in KEY, INDEX and VALUE
    RECURSIVE => TRUE | FALSEFALSEFALSE expands only the element PATH points to; TRUE expands every sub-element
    MODE => 'OBJECT' | 'ARRAY' | 'BOTH'BOTHRestricts which kind of compound value is flattened

    Each output row has six columns: SEQ, KEY, PATH, INDEX, VALUE and THIS. VALUE is the one you usually read. It is a VARIANT, so you drill into it and cast it like any other path result, for example f.value:name::string. INDEX holds the array position, or NULL for object members. KEY holds the object key. THIS is the element being flattened, which mainly helps when RECURSIVE is on. In car_sales, each sale's customer is an array of objects. To get one row per customer, the query is SELECT f.value:name::STRING AS customer_name, src:dealership::STRING FROM car_sales, LATERAL FLATTEN(INPUT => src:customer) f. Each sale has one customer, so it returns two rows, with the dealership repeated beside each name.

    OUTER matters when some rows have empty or missing arrays. With the default OUTER => FALSE, a sale with an empty extras array disappears from the output entirely. With OUTER => TRUE, it stays as a single row with NULLs, the same way a left join keeps unmatched rows. If a report has to list every sale, including those with nothing to explode, set OUTER => TRUE.

    Nested arrays need one FLATTEN per level, chained with LATERAL. extras lives inside each element of vehicle. The first FLATTEN explodes src:vehicle into one row per vehicle. The second takes vm.value:extras from that output and explodes it again. Each vehicle's make and model are repeated on every one of its extras.

    Two chained LATERAL FLATTEN calls: one row per extra, carrying the parent vehicle's make and modelsql
    SELECT
      vm.value:make::string as make,
      vm.value:model::string as model,
      ve.value::string as "Extras Purchased"
      FROM
        car_sales
        , LATERAL FLATTEN(INPUT => SRC:vehicle) vm
        , LATERAL FLATTEN(INPUT => vm.value:extras) ve
      ORDER BY make, model, "Extras Purchased";

    Neither RECURSIVE nor MODE replaces the chain. RECURSIVE => TRUE expands every sub-element at every depth, so customers, salespeople and vehicles come back mixed together. You would then have to pick out the extras by matching path strings, and the link between each extra and its parent row is lost. MODE only decides whether objects, arrays or both are flattened. It does not walk through an intermediate array, so in car_sales the path src:vehicle:extras does not reach inside each vehicle: vehicle is an array, and extras belongs to its elements. RECURSIVE does have a real use: listing every key and path in an object you have never seen before. For a known shape, chain the flattens.

    Checkpoint 4 of 9· Check yourself

    In an orders table, each row holds a VARIANT payload with an items array, and each item has its own extras array. You need one row per extra, with that item's sku beside it. Which approach gives that result?

    Checkpoint 5 of 9· Check yourself

    Some sales in car_sales have an empty extras array. A report built with LATERAL FLATTEN(INPUT => vm.value:extras) must still show every sale. Which change keeps those sales in the output?

    Checkpoint 6 of 9· Exam question

    A campaigns table has a VARIANT column details containing {"channels": ["email", "sms", "push"]} for each campaign row. A data engineer needs one output row per channel value, alongside the campaign id, so downstream reporting can aggregate spend by channel. Which query accomplishes this?

    Checkpoint 7 of 9· Exam question

    An orders table stores a VARIANT column payload shaped like {"customer": {"name": "..."}, "items": [{"sku": "...", "extras": ["gift_wrap", "insurance"]}]}. A report needs one row per extra, with the parent item's sku and the extra string, for every order. Which approach correctly produces that result?

    Sources31

    4.Building OBJECT values from columns and whole rows

    Going from structured to semi-structured data starts with OBJECT_CONSTRUCT. Typical uses are packing a table's rows into JSON documents for an API, a downstream consumer or a VARIANT landing table. The basic form takes alternating keys and values: OBJECT_CONSTRUCT('a', 1, 'b', 'BBBB'). Each key is a VARCHAR, and a value can be any data type, including a scalar subquery or an expression such as EXTRACT(epoch_seconds, created_date). Pass another OBJECT_CONSTRUCT as a value to nest objects.

    The wildcard form, OBJECT_CONSTRUCT(*), turns each whole row into an object, using column names as keys. For demo_table_1, it produces {"CREATED_DATE": "2024-01-19", "PROVINCE": "Alberta"}. The keys are upper case because unquoted column names are stored that way. With FROM VALUES, where there are no column names, the keys become COLUMN1, COLUMN2 and so on. In a join you can qualify the wildcard as mytable.* to include only one table's columns.

    Two keywords narrow the wildcard. ILIKE keeps the columns that match one pattern, as in OBJECT_CONSTRUCT(* ILIKE 'prov%'). EXCLUDE drops one or more named columns, as in (* EXCLUDE col1) or (* EXCLUDE (col1, col2)). You cannot use ILIKE and EXCLUDE in the same call. Both work only in a SELECT list or a GROUP BY clause. An object constant written in braces, such as {* EXCLUDE province}, gives the same result as the function call.

    Turning each row into an object while leaving out one columnsql
    SELECT OBJECT_CONSTRUCT(* EXCLUDE province) AS oc
      FROM demo_table_1
      ORDER BY oc['PROVINCE'];

    NULL handling changes the shape of the output. A nullable column turns into a missing key rather than a key holding null. A consumer that expects every key on every record will break on sparse rows. If you need the key kept, pass a JSON null with PARSE_JSON('NULL'), or use OBJECT_CONSTRUCT_KEEP_NULL. The string 'null' is a different thing again: it is kept as the text "null". Key order is not guaranteed either, so nothing downstream should depend on keys appearing in column order.

    Checkpoint 8 of 9· Fill the gap

    Every row of demo_table_1 has to become a JSON object with all its columns except province. Which keyword completes the wildcard call?

    SELECT OBJECT_CONSTRUCT(*  ?  province) AS oc
      FROM demo_table_1
      ORDER BY oc['PROVINCE'];

    Sources4

    5.Aggregating rows into arrays with ARRAY_AGG

    ARRAY_AGG is the inverse of FLATTEN. It collects one value from each row in a group into a single ARRAY. With GROUP BY o_orderstatus, each status gets one row holding an array of its clerks. ARRAYAGG is an alias. When the input is empty, the function returns an empty array, not NULL. Combining it with OBJECT_CONSTRUCT is how you build nested documents. For example, ARRAY_AGG(OBJECT_CONSTRUCT(*)) grouped by a parent key gives one row per parent, with its child rows as an array of objects.

    Element order inside the array is not guaranteed unless you specify it. WITHIN GROUP (ORDER BY ...) sets the order of elements inside each array. An ORDER BY at the end of the query only sorts the output rows. A query can use both, as below. Do not put a number in WITHIN GROUP's ORDER BY: it is read as a constant, not as the position of a select-list column.

    WITHIN GROUP orders the clerks inside each array; the outer ORDER BY orders the result rowssql
    SELECT
        o_orderstatus,
        ARRAYAGG(o_clerk) WITHIN GROUP (ORDER BY o_totalprice DESC)
      FROM orders
      WHERE o_totalprice > 450000
      GROUP BY o_orderstatus
      ORDER BY o_orderstatus DESC;

    A few rules catch people out:

    • DISTINCT removes duplicates. If you also use WITHIN GROUP, both must refer to the same column, so ARRAY_AGG(DISTINCT O_ORDERKEY) WITHIN GROUP (ORDER BY O_ORDERSTATUS) fails to compile.
    • NULL values are left out of the array. Counting elements does not count rows that had NULLs.
    • One call can return at most 128 MB. A huge group belongs in several arrays, or should not be aggregated this way.
    • LIMIT is not supported inside the function. When ARRAY_AGG runs as a window function with ORDER BY in the OVER clause, the array follows that order, and DISTINCT and WITHIN GROUP are not allowed.

    Checkpoint 9 of 9· Fill the gap

    Downstream consumers need each status's clerk array listed from the highest order price to the lowest. The outer ORDER BY only sorts the result rows. Which keyword makes the ordering apply to the elements inside each array?

    SELECT
        o_orderstatus,
        ARRAYAGG(o_clerk)  ?  GROUP (ORDER BY o_totalprice DESC)
      FROM orders
      WHERE o_totalprice > 450000
      GROUP BY o_orderstatus
      ORDER BY o_orderstatus DESC;

    Sources5

    Sources

    (5)

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

    1. 1.
      “Regardless of which notation you use, the column name is case-insensitive but element names are case-sensitive.”
      ↩︎ Traversing a VARIANT with colon, dot and bracket paths
      “then you must enclose the name in double quotes”
      ↩︎ Traversing a VARIANT with colon, dot and bracket paths
      “Insert a colon : between the VARIANT column name and any first-level element: <column>:<level1_element>.”
      ↩︎ Traversing a VARIANT with colon, dot and bracket paths
      “Operators : and subsequent . and [] always return VARIANT values containing strings.”
      ↩︎ Casting path results to typed columns, and GET_PATH
      “Unlike the path syntax, these functions can handle irregular paths or path elements.”
      ↩︎ Casting path results to typed columns, and GET_PATH
      “GET_PATH is equivalent to a chain of GET functions.”
      ↩︎ Casting path results to typed columns, and GET_PATH
      “The function returns a row for each object, and the LATERAL modifier joins the data with any information outside of the object.”
      ↩︎ Exploding arrays into rows with FLATTEN and LATERAL FLATTEN
      “Operators : and subsequent . and [] always return VARIANT values containing strings.”
      ↩︎ Key concept
      “extracts the VARIANT value of the element in the path provided as the second argument”
      ↩︎ Exam trap 1
    2. 2.
      “to convert a value from the VARIANT data type, cast the VARIANT value to the target data type.”
      ↩︎ Casting path results to typed columns, and GET_PATH
      “VARIANT data stores both the value and the data type of the value.”
      ↩︎ Casting path results to typed columns, and GET_PATH
    3. 3.
      “FLATTEN can be used to convert semi-structured data to a relational representation.”
      ↩︎ Exploding arrays into rows with FLATTEN and LATERAL FLATTEN
      “the values in this input row are replicated to match the number of rows produced by FLATTEN”
      ↩︎ Exploding arrays into rows with FLATTEN and LATERAL FLATTEN
      “If TRUE, exactly one row is generated for zero-row expansions (with NULL in the KEY, INDEX, and VALUE columns).”
      ↩︎ Exploding arrays into rows with FLATTEN and LATERAL FLATTEN
      “If FALSE, only the element referenced by PATH is expanded. If TRUE, the expansion is performed for all sub-elements recursively.”
      ↩︎ Exploding arrays into rows with FLATTEN and LATERAL FLATTEN
      “use LATERAL so that each subsequent FLATTEN can reference the output of the previous one”
      ↩︎ Exploding arrays into rows with FLATTEN and LATERAL FLATTEN
      “use LATERAL so that each subsequent FLATTEN can reference the output of the previous one”
      ↩︎ Exam trap 2
      “use LATERAL so that each subsequent FLATTEN can reference the output of the previous one.”
      ↩︎ Checkpoint
    4. 4.
      “the OBJECT value is constructed from the specified data using the attribute names as keys”
      ↩︎ Building OBJECT values from columns and whole rows
      “The ILIKE and EXCLUDE keywords can’t be combined in a single function call.”
      ↩︎ Building OBJECT values from columns and whole rows
      “The constructed object does not necessarily preserve the original order of the key-value pairs.”
      ↩︎ Building OBJECT values from columns and whole rows
      “attribute names are not specified, so Snowflake uses COLUMN1, COLUMN2, and so on”
      ↩︎ Building OBJECT values from columns and whole rows
      “a string that isn’t NULL as the key and a JSON null as the value”
      ↩︎ Exam trap 4
      “If the key or value is NULL — that is, SQL NULL — the key-value pair is omitted from the resulting object.”
      ↩︎ Prediction
    5. 5.
      “Returns the input values, pivoted into an array. If the input is empty, the function returns an empty array.”
      ↩︎ Aggregating rows into arrays with ARRAY_AGG
      “If you specify DISTINCT and WITHIN GROUP, both must refer to the same column.”
      ↩︎ Aggregating rows into arrays with ARRAY_AGG
      “The maximum amount of data that ARRAY_AGG can return for a single call is 128 MB.”
      ↩︎ Aggregating rows into arrays with ARRAY_AGG
      “NULL values are omitted from the output.”
      ↩︎ Aggregating rows into arrays with ARRAY_AGG
      “If you do not specify WITHIN GROUP(ORDER BY), the order of elements within each array is unpredictable.”
      ↩︎ Exam trap 3

    Ready to test yourself?

    Practise the 13 questions on this subdomain.

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