What you will be able to do
- Query nested JSON in a VARIANT column with path notation, casting and LATERAL FLATTEN
- Choose between a stored procedure, a scalar UDF and a UDTF for a piece of processing logic
- Describe how an external function reaches a remote service, and what that means for performance
- Decide when to make a UDF or procedure secure, and what it costs in performance
1.Turning staged JSON into rows with path notation and FLATTEN
JSON, Avro, ORC and Parquet usually land in a staging table with a single VARIANT column. The VARIANT holds nested OBJECTs and ARRAYs as they arrive, so a source that keeps adding fields does not force a schema change at load time. The transformation work starts when you read that column back out as typed, relational rows.
Path notation reaches into the VARIANT. Dot notation looks like src:salesperson.name. Bracket notation looks like src['salesperson']['name']. The column name is case-insensitive, but element names are case-sensitive, so SRC:salesperson.name works and SRC:Salesperson.Name returns nothing. An element name that is not a valid SQL identifier, such as one containing a space or starting with a digit, must go in double quotes: src:"company name".
A path returns a VARIANT, not a typed value. That is why salesperson names come back wrapped in quotes. Cast with :: to get a real type: value:name::string. This matters most when a view sits on top of a staging table. A view that exposes raw path expressions gives every consumer VARIANT columns. A view that casts each path gives them ordinary strings and numbers to join, filter and aggregate on.
FLATTEN turns arrays into rows. It is a table function that produces a lateral view of a VARIANT, OBJECT or ARRAY: one output row per element. The LATERAL keyword joins each output row back to the source row it came from. To reach an array nested inside another array, chain a second FLATTEN onto the first one's value column. By default, input rows with nothing to expand are dropped. OUTER => TRUE keeps them as a single row with NULLs, which stops a staging transform from silently losing records that have an empty array.
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";Checkpoint 1 of 5· Check yourself
A staging table stores raw JSON in a VARIANT column named src. Each document has a key "customer" (all lowercase) that holds an object with a "name" key. A transform view selects SRC:Customer.Name::string and returns only NULLs. What fixes it?
The column name is case-insensitive, so SRC and src are the same column. Element names inside the VARIANT are case-sensitive, so the path must match the JSON key's case exactly. Casting with :: and double quotes don't change how keys are matched.
“Regardless of which notation you use, the column name is case-insensitive but element names are case-sensitive.”Source: docs.snowflake.com
2.Stored procedures, UDFs and UDTFs
When the logic does not fit in plain SQL, Snowflake gives you three ways to package it. A stored procedure performs operations. A scalar UDF calculates one value per input row. A UDTF (user-defined table function) returns a set of rows. The choice depends on where you need to call the logic and what it has to change.
| Property | UDF | Stored procedure |
|---|---|---|
| How it is called | Inside an expression, e.g. SELECT MyFunction_1(column_1) FROM table1 | As its own statement: CALL MyStoredProcedure_1(argument_1) |
| Calls per statement | A single SQL statement can call multiple UDFs | A single SQL statement can call only one stored procedure |
| SQL it can run | Queries only, not DML or DDL | Database operations such as SELECT, UPDATE and CREATE |
| Return value | Always returns a value | Optional; implicitly returns NULL if none is returned |
These differences settle most design questions. A cleansing rule applied to every row, such as normalising a phone number, belongs in a UDF. It can then sit in a SELECT, in a view, or in a dynamic table definition. Logic that creates tables, merges a stream into a target, or runs several statements in sequence needs a stored procedure, usually called from a task. You cannot write SELECT my_stored_procedure(). If you need a procedure's tabular output, call it in the FROM clause, read it with RESULT_SCAN, or write it to a table.
A UDTF returns a table for each input. It is called in the FROM clause with the TABLE keyword. Its RETURNS TABLE(...) clause sets the output column names and types, which must match the SELECT in the body. A SQL UDTF often does the same job as a view, but it also takes parameters. Two performance points matter. When reading staged files, UDTFs can process files in parallel, while scalar UDFs process them one at a time. Inside a dynamic table, a UDTF is allowed only in a lateral join. Handler language also limits sharing: SQL and JavaScript UDFs can be used with Secure Data Sharing, but Java, Python and Scala UDFs cannot.
create or replace function orders_for_product(PROD_ID varchar)
returns table (Product_ID varchar, Quantity_Sold numeric(11, 2))
as
$$
select product_ID, quantity_sold
from orders
where product_ID = PROD_ID
$$
;
select product_id, quantity_sold
from table(orders_for_product('compostable bags'))
order by product_id;Checkpoint 2 of 5· Check yourself
A team wants to replace a scheduled task pipeline with dynamic tables. The pipeline has three pieces of custom logic: a scalar UDF that normalises phone numbers in the SELECT list, a SQL UDTF called through a lateral join, and a stored procedure that MERGEs the cleaned rows into a target table. Which piece stops that step from becoming a dynamic table?
A scalar UDF can sit in any SELECT, including a dynamic table definition, and a UDTF is allowed there inside a lateral join. A stored procedure is called as its own statement and dynamic tables cannot use one, so the MERGE stays a procedure called from a task.
“Need stored procedures or external functions in the definition.”Source: docs.snowflake.com
3.External functions: calling a remote service from SQL
An external function is a UDF with no code of its own. It calls a remote service that runs outside Snowflake, for example an AWS Lambda function or an Azure Function. Snowflake never calls that service directly. It sends an HTTP POST with the rows as JSON to a cloud provider's HTTPS proxy service, such as Amazon API Gateway or Azure API Management, which relays the request. The authentication details for that proxy live in an API integration, created with CREATE API INTEGRATION. To SQL users, the result looks like any other UDF: it takes parameters, returns a value (which can be a VARIANT holding JSON), and can appear in a SELECT, a WHERE clause or a view.
The reason to use one is reach. The remote service can be written in languages that ordinary UDFs do not support, such as Go or C#. It can also use third-party libraries such as commercial machine-learning scoring libraries, and the same service can be shared with systems outside Snowflake. The proxy can also add security and handle subscription billing for a paid remote service.
The cost is a network round trip for every batch of rows. Snowflake splits large inputs into batches, which allows parallel calls. If a call times out, the retry happens at the batch level. A synchronous service blocks until it answers. An asynchronous service replies with HTTP 202 and is polled with GET requests, which helps when processing would exceed the proxy's own timeout. Either way, a query is aborted if results are not back within Snowflake's 10-minute timeout, which you cannot change. The function only scales as far as the remote service does. Its calls are also why dynamic table definitions cannot contain external functions. A pipeline that needs one runs it from a task instead.
Checkpoint 3 of 5· Check yourself
Every 15 minutes, new orders in a staging table must be scored by a fraud model. The model runs as an AWS Lambda function that Snowflake reaches through an external function. Which design can run this scoring step?
Fifteen minutes is well within what a dynamic table's target lag allows, so freshness is not the problem. The problem is that a dynamic table definition cannot contain an external function, whatever target lag you set. A step that needs a remote service call stays on streams and tasks.
“Need stored procedures or external functions in the definition.”Source: docs.snowflake.com
4.Secure UDFs and procedures: privacy at a performance cost
SECURE does two separate things. First, it hides the definition. Only roles that own the function or procedure can see its body, list of imports, handler name and packages, whether through SHOW FUNCTIONS, DESCRIBE FUNCTION, the Information Schema, Query Profile or GET_DDL. Everyone else still sees the parameter types, return type, handler language, null handling and volatility. Second, it hides the data. The optimizer turns off optimizations such as filter pushdown, which could reorder filters so that a user's own predicate runs before the function's protective filter. That reordering could let a user infer rows they are not allowed to see. Queries that use secure functions also do not report how much data was scanned. For Java, Python and Scala handlers, secure functions run in separate sandboxes that share no resources.
The price is speed. Pushdown makes queries faster by filtering out unneeded rows as early as possible, and a secure UDF gives that up. So make a function secure only when it exists to protect data. A helper that just simplifies queries should stay a regular UDF. Protection also has to be consistent: if only secure UDFs may access a table, any view on that table should probably be secure as well. Secure views hide view definitions in the same way, and the trade-off is the same. Because some optimizer rewrites are switched off, a secure view can run slower than the equivalent standard view.
Checkpoint 4 of 5· Check yourself
To be safe, an architect proposes adding SECURE to every view and helper function in the reporting schema. Most of these objects only simplify queries for analysts, and none of them protect sensitive data. What is the main drawback of this default?
SECURE hides the definition and turns off optimizations like pushdown, so the object can run slower. That price is worth paying only when the object exists to protect data, not for convenience helpers. Both standard and materialized views can be secure, and secure views help with data sharing rather than block it.
“Secure views have advantages over standard views, including improved data privacy and data sharing; however, they also have some performance impacts to take into consideration.”Source: docs.snowflake.com
Checkpoint 5 of 5· Exam question
A data governance team wants to expose a view of a PII-containing table to a broad set of analyst roles, but they are worried that a clever analyst could reverse-engineer the masking logic in the view's SQL definition by studying the query optimizer's behavior. Which view property directly addresses this concern?
Correct answer: A — Declaring the view as SECURE, which hides the view definition from unauthorized users and disables optimizations that could otherwise leak information through the plan.
- A. Correct - a secure view withholds its underlying query text from users who only have privileges on the view, and Snowflake skips certain query optimizations for secure views specifically because those optimizations could otherwise expose details about the underlying data through query plans.
- B. Incorrect - materialization affects storage and performance, not whether the view's definition or masking logic is protected from inspection by analysts.
- C. Incorrect - clustering keys are a performance tuning mechanism for materialized views and tables; they have no bearing on whether a view's definition is concealed.
- D. Incorrect - the scope of the granting role object does not change whether the view's SQL text is visible to a user who has been granted SELECT on it.
Practise it for real
Turn nested JSON in a single VARIANT column into typed relational rows, the core move of a staging-to-curated transform.
1.Create the car_sales table with one VARIANT column, src, and load the two sample records with PARSE_JSON, as in the Snowflake semi-structured querying example.
Why: This reproduces a typical staging table: raw documents with nested OBJECTs and ARRAYs in one column.
You should see: A table with two rows, each holding a dealership, salesperson, customer array and vehicle array.
2.Run SELECT src:salesperson.name FROM car_sales, then the same query with src:Salesperson.Name.
Why: Shows that element names are case-sensitive and that paths return VARIANT values.
You should see: The first query returns the quoted names "Frank Beasley" and "Greg Northrup"; the second returns NULLs.
3.Flatten the customer array with LATERAL FLATTEN(INPUT => SRC:customer) and select value:name::string and value:address::string.
Why: FLATTEN produces one row per array element, and the cast turns VARIANT into plain strings.
You should see: Two rows, Joyce Ridgely and Bradley Greenbloom, with their cities, without quotes.
4.Run the chained query that flattens SRC:vehicle and then vm.value:extras.
Why: Nested arrays need a second FLATTEN that reads from the first one's value column.
You should see: Five rows: two extras for the Honda Civic and three for the Toyota Camry.
Stuck? Get a nudge
If the nested query returns nothing, check that the second FLATTEN reads vm.value:extras and not SRC:extras. The extras array lives inside each vehicle, not at the top level.
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“FLATTEN is a table function that produces a lateral view of a VARIANT, OBJECT, or ARRAY column.”
↩︎ Turning staged JSON into rows with path notation and FLATTEN“the LATERAL modifier joins the data with any information outside of the object.”
↩︎ Turning staged JSON into rows with path notation and FLATTEN“Cast the VARIANT output to string values”
↩︎ Turning staged JSON into rows with path notation and FLATTEN“then you must enclose the name in double quotes”
↩︎ Turning staged JSON into rows with path notation and FLATTEN“the column name is case-insensitive but element names are case-sensitive.”
↩︎ Exam trap 2“Regardless of which notation you use, the column name is case-insensitive but element names are case-sensitive.”
↩︎ Checkpoint - 2.
“If TRUE, exactly one row is generated for zero-row expansions”
↩︎ Turning staged JSON into rows with path notation and FLATTEN - 3.
“A single SQL statement can call only one stored procedure.”
↩︎ Stored procedures, UDFs and UDTFs“You can call a stored procedure that returns tabular data in the FROM clause of a SELECT statement.”
↩︎ Stored procedures, UDFs and UDTFs“In a UDF, you can use SQL to execute queries only (not DML or DDL statements).”
↩︎ Exam trap 1 - 4.
“UDTFs can process multiple files in parallel; however, UDFs currently process files serially.”
↩︎ Stored procedures, UDFs and UDTFs - 5.
“When calling a UDTF, you must include the UDTF name and arguments inside parentheses following the TABLE keyword.”
↩︎ Stored procedures, UDFs and UDTFs - 6.
“Use UDTFs outside of lateral joins.”
↩︎ Stored procedures, UDFs and UDTFs“Need stored procedures or external functions in the definition.”
↩︎ Checkpoint“Need stored procedures or external functions in the definition.”
↩︎ Checkpoint - 7.
“An API integration stores information, such as security information, that is needed to work with a proxy service or remote service.”
↩︎ External functions: calling a remote service from SQL“Batches typically allow more parallelism and faster queries.”
↩︎ External functions: calling a remote service from SQL“remote services can interface with commercially available third-party libraries, such as machine-learning scoring libraries.”
↩︎ External functions: calling a remote service from SQL - 8.
“Currently, Snowflake’s timeout is 10 minutes (600 seconds) and is not user-configurable.”
↩︎ External functions: calling a remote service from SQL - 9.
“When you specify that the UDF or procedure is secure, these details are visible only to authorized users”
↩︎ Secure UDFs and procedures: privacy at a performance cost“Snowflake does not expose the amount of data scanned (either in terms of bytes or micro-partitions) or the total amount of data.”
↩︎ Secure UDFs and procedures: privacy at a performance cost“making the functions and procedures secure ensures that they are executed in separate sandboxes, such that no resources are shared between them.”
↩︎ Secure UDFs and procedures: privacy at a performance cost“any views that you allow to access the same table probably also should be secure.”
↩︎ Secure UDFs and procedures: privacy at a performance cost“the Snowflake query optimizer, when evaluating secure UDFs, bypasses the optimizations used for regular UDFs.”
↩︎ Exam trap 3“Unauthorized users will still be able to see information that includes its:”
↩︎ Prediction - 10.
“Pushdown improves performance by filtering out unneeded rows as early as possible during query processing.”
↩︎ Secure UDFs and procedures: privacy at a performance cost - 11.
“they also have some performance impacts to take into consideration.”
↩︎ Secure UDFs and procedures: privacy at a performance cost“Secure views have advantages over standard views, including improved data privacy and data sharing; however, they also have some performance impacts to take into consideration.”
↩︎ Checkpoint