What you will be able to do
- Pick the function category a scenario needs by counting the rows that go in and come out of it
- Predict how NULLs affect scalar functions, AVG, SUM, COUNT(*) and COUNT(col)
- Filter window function results with QUALIFY instead of WHERE
- Call a table function such as FLATTEN or GENERATOR in the FROM clause
- Spot a scenario that no built-in function covers, where a UDF is the answer
Key concept
Function category by row shape — A Snowflake function's category tells you how many rows it takes in and how many it gives back. Scalar functions give one value per row. Aggregates turn many rows into one. Window functions give a value on every row, worked out across related rows. Table functions return a set of rows from the FROM clause.
1.Five function categories and how to spot them
Snowflake groups its built-in functions by the shape of their input and output. A scenario question usually reveals that shape before it names any function. A scalar function returns one value per invocation, which in practice means one value per row. Run COS(x) against a three-row table and you get three rows back. An aggregate function takes any number of rows and returns a single output. Run SUM(x) against the same table and you get one row.
SELECT SUM(x)
FROM simple;
+--------+
| SUM(X) |
|--------|
| 60 |
+--------+You always get that single row, even from an empty input. Over zero rows, an aggregate still returns exactly one row. The value in it is usually NULL, but some aggregates return 0 or an empty string instead.
Three more categories complete the set. Window functions compute a value for every row from a group of related rows, such as running totals, moving averages and rankings, so the number of rows doesn't change. Table functions return a set of rows for each input row and are called from FROM. System functions do one of two things. Control functions act on the system, for example by aborting a query. Information functions report on it, for example the clustering depth of a table or an EXPLAIN plan.
| Scenario signal | Category | Examples |
|---|---|---|
| One value out for each row in | Scalar | COS, ST_DISTANCE |
| Many rows in, one result per group | Aggregate | SUM, AVG, COUNT, MEDIAN |
| A value on every row, computed across related rows | Window | ROW_NUMBER, RANK, LAG, LEAD |
| Zero, one or many rows out, used as a row source in FROM | Table | FLATTEN, GENERATOR, RESULT_SCAN |
| Act on the system or ask it for information | System | SYSTEM$TYPEOF |
Many system functions start with SYSTEM$. The prefix is part of the function's name, so leave it out and the call fails.
SELECT SYSTEM$TYPEOF('a');Checkpoint 1 of 5· Check yourself
A nightly job runs SELECT SUM(amount) over a table that currently has no rows. What does the query return?
An aggregate always produces one output row, even from an empty input. The value in that row is typically NULL.
“An aggregate function always returns exactly one row, even when the input contains zero rows.”Source: docs.snowflake.com
2.How NULL moves through functions and aggregates
Aggregates skip NULLs. They don't treat them as zero. AVG over 1, 5 and NULL is 3, because the NULL row is left out of both the sum and the count. If every input is NULL, the aggregate returns NULL. So SUM over a column that holds only NULLs gives NULL, not 0, and a dashboard tile that expects a number shows a blank.
COUNT comes in forms that answer different questions. COUNT(col) counts the non-NULL values in a column. COUNT(*) counts every record, NULLs included. With more than one column, as in COUNT(x, y), a row is skipped if any of those columns is NULL.
CREATE OR REPLACE TABLE test_null_aggregate_functions (x INT, y INT);
INSERT INTO test_null_aggregate_functions (x, y) VALUES
(1, 2), -- No NULLs.
(3, NULL), -- One but not all columns are NULL.
(NULL, 6), -- One but not all columns are NULL.
(NULL, NULL); -- All columns are NULL.| Expression | Result | Reason |
|---|---|---|
| COUNT(*) | 4 | Counts every record |
| COUNT(x) | 2 | Counts only non-NULL values of x |
| COUNT(x, y) | 1 | Skips any row with a NULL in either column |
| SUM(x + y) | 3 | x + y is NULL on three rows, and SUM ignores them |
Scalar functions pass NULL through instead of dropping the row. In SUM(x + y), the expression x + y is NULL on every row that contains a NULL, so SUM never sees those rows. Snowflake's own functions behave the same way. For example, ST_DISTANCE returns NULL if either input point is NULL.
SELECT ST_DISTANCE(ST_MAKEPOINT(0, 0), ST_MAKEPOINT(NULL, NULL)) AS null_input;If the business says a missing value means zero, replace it before you aggregate. AVG(COALESCE(amount, 0)) brings the pending rows back into the count with a value of zero, while plain AVG(amount) leaves them out. To count only the rows that have a value, use COUNT(amount). COUNT(*) would include the pending rows.
Checkpoint 2 of 5· Check yourself
A table has four rows, and every one of them has a NULL in at least one column. Which expression still returns 4?
An unqualified, unfiltered COUNT(*) returns the total number of records, NULLs included. COUNT on named columns skips rows with NULLs.
“If you specify an unqualified and unfiltered wildcard (*), the function returns the total number of records, including records with NULL values.”Source: docs.snowflake.com
3.Window functions and filtering their results with QUALIFY
A window function returns a value on every row, computed from that row's window: the other rows in the same partition. PARTITION BY splits the rows into separate windows, and ORDER BY inside OVER sets the order within each window. That order is separate from the ORDER BY that sorts the final result. The ranking functions ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD and FIRST_VALUE work this way. Many aggregates have a window form as well: COUNT, SUM and AVG appear in both lists, and adding an OVER clause turns one row per group into one value per row.
Filtering on a window result needs its own clause because of the order in which a query runs: FROM, WHERE, GROUP BY, HAVING, WINDOW, QUALIFY, DISTINCT, ORDER BY, LIMIT. WHERE runs before any window function is computed, so a row number doesn't exist yet when WHERE runs. QUALIFY runs after window functions, and it does for window functions what HAVING does for aggregates.
SELECT <column_list>
FROM <data_source>
[GROUP BY ...]
[HAVING ...]
QUALIFY <predicate>
[ ... ]To keep the latest reading for each sensor in a single query block, number the rows within each sensor from newest to oldest and keep row 1: QUALIFY ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY reading_ts DESC) = 1. GROUP BY with HAVING doesn't solve the same problem. An aggregate collapses each group to one output, so you get the newest timestamp but lose the rest of that reading's row.
WHERE is evaluated before the WINDOW step, so no window result exists yet. QUALIFY is evaluated after window functions are computed.
Checkpoint 3 of 5· Fill the gap
Fill in the clause that keeps only the first row of each partition.
? ROW_NUMBER() OVER (PARTITION BY p ORDER BY o) = 1;Only QUALIFY is evaluated after window functions, so it is the clause that can filter on ROW_NUMBER.
Source: docs.snowflake.com4.Table functions in FROM: TABLE(), FLATTEN and GENERATOR
A table function returns a set of rows for each input row: zero, one or more, each with one or more columns. Because it produces rows, it goes in the FROM clause, and you wrap the call in TABLE() so the compiler treats it as a source of rows. Arguments must be scalar expressions, but they can come from a table listed earlier in FROM. In the example below, each date feeds the function, and each date comes back as two city rows.
SELECT
doi.event_date as "Date",
record_temperatures.city,
record_temperatures.temperature
FROM dates_of_interest AS doi,
TABLE(record_high_temperatures_for_date(doi.event_date)) AS record_temperatures
ORDER BY doi.event_date, city;FLATTEN is the table function you'll meet most often. LATERAL FLATTEN turns an array or object inside a VARIANT into one row per element. LATERAL lets FLATTEN read a column from the table listed just before it, so each element row keeps its parent row's columns. Each element is in the alias's value column, which you navigate with a path and cast.
SELECT
m.value:key:CUSTOM_AI_FUNCTION_NAME::STRING AS func_name,
m.value:key:metric::STRING AS metric_type,
SUM(m.value:value::NUMBER) AS token_number
FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_AI_FUNCTIONS_USAGE_HISTORY c,
LATERAL FLATTEN(input => c.METRICS) mScalar functions can't do this. A conversion such as PARSE_JSON, or a function that measures an array, returns one value per input row, however many elements the array holds. Use the right table function, too: FLATTEN is the built-in listed for semi-structured queries, while SPLIT_TO_TABLE belongs to the data conversion group.
GENERATOR, SEQ, UNIFORM and RANDOM create synthetic rows, and GENERATOR is called the same way: as a table function in FROM that produces rows from nothing. RESULT_SCAN is another useful one, because it lets you run SQL on the output of an earlier statement such as SHOW.
Checkpoint 4 of 5· Check yourself
You want to call GENERATOR or FLATTEN as a source of rows in a SELECT. Which form is correct?
Table functions are used in the FROM clause, and the call is wrapped in TABLE() so the compiler recognizes it as a source of rows.
“Snowflake requires that the table function call be wrapped by the TABLE() keyword.”Source: docs.snowflake.com
Sources8
5.When no built-in function fits: UDFs
A user-defined function is the right answer when no built-in function does the job, or when the same calculation, standard across your organization, gets copied into many queries. UDFs and UDTFs come in the same shapes as the built-in categories. A UDF returns one value per row, a user-defined aggregate function (UDAF) works across rows, and a UDTF returns a table for each input row. Once created, a UDF is called just like a built-in function.
CREATE OR REPLACE FUNCTION addone(i INT)
RETURNS INT
LANGUAGE PYTHON
RUNTIME_VERSION = '3.12'
HANDLER = 'addone_py'
AS $$
def addone_py(i):
return i+1
$$;Checkpoint 5 of 5· Match them up
Match each user-defined function variation to what it does.
Tap a term, then the definition that fits it.
The variations mirror the built-in categories: scalar, aggregate and table.
“Returns a tabular value for each input row.”Source: docs.snowflake.com
Sources9
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“A scalar function is a function that returns one value per invocation”
↩︎ Five function categories and how to spot them - 2.
“An aggregate function always returns exactly one row, even when the input contains zero rows.”
↩︎ Five function categories and how to spot them“In both the numerator and the denominator, only the two non-NULL values are used.”
↩︎ How NULL moves through functions and aggregates“This behavior differs from the behavior of GROUP BY, which does not discard rows when some columns are NULL”
↩︎ How NULL moves through functions and aggregates“An aggregate function takes multiple rows (actually, zero, one, or more rows) as input and produces a single output.”
↩︎ Key concept“If all of the values passed to the aggregate function are NULL, then the aggregate function returns NULL.”
↩︎ Exam trap 2 - 3.
“Control functions that allow you to execute actions in the system (for example, aborting a query).”
↩︎ Five function categories and how to spot them“For the system functions that use this prefix, you must specify the prefix when calling the function.”
↩︎ Five function categories and how to spot them - 4.
“Returns either the number of non-NULL records for the specified columns, or the total number of records.”
↩︎ How NULL moves through functions and aggregates“Aggregate functions (General) , Window functions”
↩︎ Window functions and filtering their results with QUALIFY“Returns either the number of non-NULL records for the specified columns, or the total number of records.”
↩︎ Exam trap 1“If you specify an unqualified and unfiltered wildcard (*), the function returns the total number of records, including records with NULL values.”
↩︎ Checkpoint - 5.
“Returns NULL if one or more input points are NULL.”
↩︎ How NULL moves through functions and aggregates - 6.
“Window functions are analytic functions that you can use for various calculations such as running totals, moving averages, and rankings.”
↩︎ Window functions and filtering their results with QUALIFY - 7.
“QUALIFY does with window functions what HAVING does with aggregate functions and GROUP BY clauses.”
↩︎ Window functions and filtering their results with QUALIFY“FROM WHERE GROUP BY HAVING WINDOW QUALIFY DISTINCT ORDER BY LIMIT”
↩︎ Window functions and filtering their results with QUALIFY“In the execution order of a query, QUALIFY is therefore evaluated after window functions are computed.”
↩︎ Exam trap 3 - 8.
“A table function returns a set of rows for each input row.”
↩︎ Table functions in FROM: TABLE(), FLATTEN and GENERATOR“Snowflake requires that the table function call be wrapped by the TABLE() keyword.”
↩︎ Table functions in FROM: TABLE(), FLATTEN and GENERATOR“Semi-structured Queries | FLATTEN”
↩︎ Table functions in FROM: TABLE(), FLATTEN and GENERATOR“Can be used to perform SQL operations on the output from another SQL operation (e.g. SHOW).”
↩︎ Table functions in FROM: TABLE(), FLATTEN and GENERATOR - 9.
“to perform operations that are not available through the built-in system-defined functions provided by Snowflake”
↩︎ When no built-in function fits: UDFs“encapsulate calculations that are standard for your organization”
↩︎ When no built-in function fits: UDFs“A sharable UDF can be used with the Snowflake Secure Data Sharing feature.”
↩︎ When no built-in function fits: UDFs“Returns a tabular value for each input row.”
↩︎ Checkpoint