What you will be able to do
- Predict how aggregate functions treat NULLs and empty input
- Tell an aggregate from its window-function counterpart and define partitions, ordering and frames
- Choose between RANK, DENSE_RANK and ROW_NUMBER when values tie
- Filter on window results with QUALIFY instead of a wrapping subquery
- Restructure transformation SQL so it does less blocking work
1.Aggregate functions: many rows in, one row out
Most transformations end by summarising, and Snowflake gives you two tools for that: aggregate functions and window functions. An aggregate takes zero, one or more rows and returns a single output. A scalar function such as COS returns one output per input row. Over a three-row table with x = 10, 20 and 30, COS(x) returns three rows and SUM(x) returns one row: 60. An aggregate returns exactly one row even when no rows go in, and that row is usually NULL.
NULLs are where aggregate results surprise people. AVG skips them, so the average of 1, 5 and NULL is 3, because the NULL is dropped from both the sum and the count. If every input is NULL, the result is NULL.
SELECT COUNT(x, y) FROM test_null_aggregate_functions;
+-------------+
| COUNT(X, Y) |
|-------------|
| 1 |
+-------------+Expressions behave the same way. SUM(x + y) over that table returns 3, because x + y is NULL wherever either column is NULL, and those rows are dropped. GROUP BY x, y works differently: it keeps all four combinations as groups, including (NULL, NULL).
The aggregate catalogue goes well beyond SUM, AVG, COUNT, MIN and MAX. ARRAY_AGG and OBJECT_AGG build semi-structured values from rows, the reverse of flattening. APPROX_COUNT_DISTINCT, an alias for HLL, estimates cardinality with HyperLogLog. LISTAGG, MEDIAN and MODE cover other common summaries.
Checkpoint 1 of 8· Check yourself
The table test_null_aggregate_functions holds four (x, y) rows: (1, 2), (3, NULL), (NULL, 6) and (NULL, NULL). Which statement about querying it is correct?
x + y is NULL in every row where either column is NULL, so SUM ignores those rows and adds only 1 + 2 = 3. GROUP BY does not drop rows with NULLs, so all four combinations become groups, including (NULL, NULL).
“This behavior differs from the behavior of GROUP BY, which does not discard rows when some columns are NULL:”Source: docs.snowflake.com
Sources1
2.Window functions: partitions, ordering and frames
A window function computes over a group of related rows but keeps every input row. Many aggregates, including SUM, COUNT and AVG, have a window form with the same name. The OVER clause is what turns them into window functions.
| Aspect | Aggregate: AVG(...) with GROUP BY | Window: AVG(...) OVER (...) |
|---|---|---|
| Input | A group of rows | Each row within a partition |
| Output | One row per group | One row per input row |
| Other columns | Only grouped or aggregated columns | Any column of the row |
OVER has three optional parts. PARTITION BY splits rows into groups such as product, city or year, and the function restarts in each group. Leave it out and all rows form one partition, and OVER() with nothing inside is valid. ORDER BY sorts rows within each partition. It is separate from the query's final ORDER BY and does not accept ordinals, so OVER (PARTITION BY 1 ORDER BY 2) sorts by the constant 2, not the second column. Ranking functions such as RANK and NTILE require it.
The window frame picks which rows around the current row go into each calculation. ROWS counts physical rows. RANGE selects rows logically by the value in the ORDER BY column. A RANGE BETWEEN frame with explicit offsets allows only one ORDER BY expression, and it must be numeric, a DATE or a TIMESTAMP. For a timestamp, the offset is an interval such as INTERVAL '3 days'.
SELECT menu_category, menu_price_usd, menu_cogs_usd,
AVG(menu_cogs_usd) OVER(PARTITION BY menu_category
ORDER BY menu_price_usd, menu_cogs_usd ROWS BETWEEN CURRENT ROW and 2 FOLLOWING) avg_cogs
FROM menu_items
ORDER BY menu_category, menu_price_usd, menu_cogs_usd
LIMIT 15;Frames shrink at partition boundaries. The last Beverage row has no following rows, so its moving average is just its own menu_cogs_usd value, 0.65. Without the frame and ORDER BY, AVG(menu_cogs_usd) OVER(PARTITION BY menu_category) puts the same category average on every row of that category.
Checkpoint 2 of 8· Fill the gap
This query should average each item's cost over the current row and the next two physical rows in its category. Which keyword completes the window frame?
SELECT menu_category, menu_price_usd, menu_cogs_usd,
AVG(menu_cogs_usd) OVER(PARTITION BY menu_category
ORDER BY menu_price_usd, menu_cogs_usd ? BETWEEN CURRENT ROW and 2 FOLLOWING) avg_cogs
FROM menu_items
ORDER BY menu_category, menu_price_usd, menu_cogs_usd
LIMIT 15;ROWS counts physical rows, so the frame is the current row plus the two that follow it. RANGE picks rows by their ORDER BY value, not by position. A RANGE BETWEEN frame with explicit offsets also allows only one ORDER BY expression, and this window sorts by two columns.
Source: docs.snowflake.comCheckpoint 3 of 8· Check yourself
An analyst writes SELECT menu_category, AVG(menu_cogs_usd) OVER() FROM menu_items with no GROUP BY. What does the query return?
An empty OVER() is valid. Without PARTITION BY, all rows form one partition. A window function still returns one row per input row, so every row gets the same average over the whole table.
“The PARTITION BY clause is optional; you can analyze a set of rows as a single partition.”Source: docs.snowflake.com
3.Ranking with ties: RANK versus DENSE_RANK
Ranking functions give each row its position within an ordered partition, and the difference between them shows when values tie. RANK and DENSE_RANK both give tied rows the same rank. RANK then skips as many ranks as there were extra tied rows. DENSE_RANK goes on to the next number with no gap. ROW_NUMBER gives each row in a partition its own sequential number, which makes it the usual choice when you need exactly one row per group.
| Bushels | RANK() | DENSE_RANK() |
|---|---|---|
| 130 | 1 | 1 |
| 120 | 2 | 2 |
| 110 | 3 | 3 |
| 110 | 3 | 3 |
| 100 | 5 | 4 |
Neither function needs PARTITION BY to handle ties. Without it, every row is ranked as one group, as with all farmers in the country. With PARTITION BY state, ranking starts again at 1 in each state. Use DENSE_RANK for a leaderboard whose ranks must run without gaps, and RANK when the ranks should show how many rows come ahead.
Checkpoint 4 of 8· Check yourself
A national corn leaderboard must rank every farmer in the country as one group by bushels, with tied farmers sharing a rank. Which approach does this?
PARTITION BY is optional. If you leave it out, all rows form one partition, which is what a nationwide ranking needs, and RANK still gives tied rows the same rank. PARTITION BY state would restart the ranking at 1 in each state. ROW_NUMBER would give tied farmers different numbers.
“The PARTITION BY clause is optional; you can analyze a set of rows as a single partition.”Source: docs.snowflake.com
Checkpoint 5 of 8· Exam question
A leaderboard query ranks sales reps by total revenue using RANK() OVER (ORDER BY revenue DESC). Two reps are tied for second place with identical revenue. The next distinct revenue value should receive rank 4, not rank 3. Which function behavior explains why RANK produces this outcome, and how would DENSE_RANK differ?
Correct answer: A — RANK assigns the same rank to tied rows and then skips ranks equal to the number of ties, so the next value gets rank 4; DENSE_RANK would instead give it rank 3 with no gap.
- A. RANK gives tied rows the same rank and then leaves a gap in the sequence equal to the count of ties, so two reps tied at rank 2 push the next rep to rank 4, while DENSE_RANK compresses that gap and assigns rank 3.
- B. RANK does not break ties arbitrarily; rows with identical ORDER BY values always receive the identical rank, which is precisely why the two tied reps both land on rank 2 in this scenario.
- C. RANK orders strictly by the ORDER BY expression supplied in the OVER clause, in this case revenue, and has no dependency on the physical storage order of rows in the underlying table.
- D. PARTITION BY is optional and only controls how the row set is divided into groups before ranking; RANK still correctly detects and numbers ties within a single partition, or across the whole result set, without it.
4.Filtering on window results with QUALIFY
QUALIFY filters rows on the result of a window function. It does for window functions what HAVING does for aggregates. The reason it exists is evaluation order. A SELECT is evaluated as FROM, WHERE, GROUP BY, HAVING, WINDOW, QUALIFY, DISTINCT, ORDER BY, LIMIT. WHERE runs before any window value exists, so the only other option is to compute the window in a subquery and filter outside it.
SELECT *
FROM (
SELECT i, p, o, ROW_NUMBER() OVER (PARTITION BY p ORDER BY o) AS row_num
FROM qt)
WHERE row_num = 1;The standard way to keep the latest row per key is ROW_NUMBER ordered newest first, kept where it equals 1. The full row survives and nothing gets merged by aggregation. QUALIFY can also refer to a window function by the alias it has in the SELECT list, such as QUALIFY row_num = 1. The query must contain at least one window function, in the SELECT list or in the QUALIFY predicate.
SELECT customer_id, customer_name, region, segment, updated_at
FROM dim_customers
QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) = 1;The common alternatives answer different questions. GROUP BY customer_id with MAX(updated_at) returns only the latest timestamp. That is enough when one value per key is all you need, but getting the rest of the row means joining back. A window COUNT(*) OVER (PARTITION BY customer_id) = 1 finds customers with only one update, not each customer's latest row. DISTINCT with a final ORDER BY picks no row at all, because both run after the rows have been chosen.
Checkpoint 6 of 8· Check yourself
dim_customers holds several versions of each customer. You need one complete row per customer_id, the most recently updated one, with region and segment intact. Which query does that?
ROW_NUMBER is a window function, so every input row is kept and gets a number. QUALIFY runs after window functions are computed, so it can keep the full newest row. WHERE runs before any window value exists. GROUP BY with MAX collapses each group to one row and returns only the timestamp. COUNT(*) = 1 finds customers that have only one version.
“For a window function, the input is each row within a partition, and the output is one row per input row.”Source: docs.snowflake.com
Checkpoint 7 of 8· Exam question
A CUSTOMER_EVENTS table logs multiple status updates per customer with an updated_at timestamp. A report needs exactly one row per customer, the row with the most recent updated_at, without collapsing any other columns through aggregation. Which pattern is the standard way to write this in Snowflake?
Correct answer: A — Use ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) in a QUALIFY clause filtering for row_number = 1, skipping a wrapping subquery.
- A. ROW_NUMBER assigns a rank within each customer's partition ordered by recency, and QUALIFY filters directly on that window function result in the same query, which is the standard latest-row-per-group pattern.
- B. The MAX-and-self-join approach works but requires an extra join step and can return duplicate rows if two events share the exact same maximum timestamp for a customer, unlike a direct QUALIFY filter.
- C. Filtering on a COUNT window function only isolates customers with exactly one event total; it does nothing to identify the most recent row for customers who have multiple status updates.
- D. DISTINCT on
customer_idalone is not valid alongside other selected columns and does not guarantee which row's values are kept, so it cannot reliably select the most recent event.
5.Applying SQL for query optimization in transformations
Much of a transformation's cost comes from blocking operators: window functions, GROUP BY, DISTINCT, and ORDER BY in subqueries. Each must see all of its input before it produces any output. A window function has to process its whole partition first. When several blocking steps are stacked, each waits for the one before it, which reduces parallelism and increases memory pressure.
Several SQL habits follow from this:
- Filter early, with WHERE clauses as close to the base tables as possible, so later steps handle fewer rows.
- Deduplicate once, upstream, and drop DISTINCT clauses that repeat work already done.
- Use QUALIFY with ROW_NUMBER to deduplicate instead of DISTINCT, because it states which duplicate is kept.
- Keep array work in a higher-order function when the result stays an array, instead of flattening to rows and aggregating back.
Correlated window functions are a specific pitfall. A query that flattens JSON with a lateral join and puts ROW_NUMBER() inside the lateral subquery, ordered by the flattened column, fails to compile: the window function contains a correlation. Columns from outer query blocks cannot be used inside a window function's PARTITION BY or ORDER BY. The fix is to compute the value in the lateral subquery and move the window function out to the outer query.
SELECT
fields.*,
ROW_NUMBER() OVER(ORDER BY completed_on DESC) rn
FROM
data,
LATERAL FLATTEN(d) AS f,
LATERAL (SELECT
f.value:completed_on AS completed_on
)fields;Checkpoint 8 of 8· Check yourself
While flattening a JSON array, an engineer puts ROW_NUMBER() OVER(ORDER BY f.value:completed_on DESC) inside a LATERAL subquery that follows LATERAL FLATTEN(d) AS f. Compilation fails with "Window function ... contains a correlation." Which change fixes it?
A window function's PARTITION BY or ORDER BY cannot use columns from an outer query block, and f.value is correlated inside the lateral subquery. If you compute completed_on in the subquery and run ROW_NUMBER in the outer query, the column is no longer correlated, so the query compiles.
“To solve this problem, don’t use correlated columns inside window functions. Move the window function to the outer query where the correlation no longer exists.”Source: docs.snowflake.com
Sources
(8)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“An aggregate function always returns exactly one row, even when the input contains zero rows.”
↩︎ Aggregate functions: many rows in, one row out“In both the numerator and the denominator, only the two non-NULL values are used.”
↩︎ Aggregate functions: many rows in, one row out“This behavior differs from the behavior of GROUP BY, which does not discard rows when some columns are NULL”
↩︎ Aggregate functions: many rows in, one row out“In these instances, the aggregate function ignores a row if any individual column is NULL.”
↩︎ Prediction“This behavior differs from the behavior of GROUP BY, which does not discard rows when some columns are NULL:”
↩︎ Checkpoint - 2.
“For a window function, the input is each row within a partition, and the output is one row per input row.”
↩︎ Window functions: partitions, ordering and frames“only the current row and the two rows that follow it (within the partition) are considered”
↩︎ Window functions: partitions, ordering and frames“For a window function, the input is each row within a partition, and the output is one row per input row.”
↩︎ Checkpoint - 3.
“An empty OVER clause has no partitions and an implied default window frame.”
↩︎ Window functions: partitions, ordering and frames“This ORDER BY clause is distinct from the ORDER BY clause that controls the order of all the rows”
↩︎ Window functions: partitions, ordering and frames“which defines either a physical number of rows (ROWS) or a logically computed set of rows (RANGE)”
↩︎ Window functions: partitions, ordering and frames“ranking window functions such as RANK and NTILE require their input data to be in a meaningful order”
↩︎ Ranking with ties: RANK versus DENSE_RANK“Move the window function to the outer query where the correlation no longer exists.”
↩︎ Applying SQL for query optimization in transformations“The PARTITION BY clause is optional; you can analyze a set of rows as a single partition.”
↩︎ Exam trap 2“The PARTITION BY clause is optional; you can analyze a set of rows as a single partition.”
↩︎ Checkpoint“The PARTITION BY clause is optional; you can analyze a set of rows as a single partition.”
↩︎ Checkpoint“To solve this problem, don’t use correlated columns inside window functions. Move the window function to the outer query where the correlation no longer exists.”
↩︎ Checkpoint - 4.
“if the first three rows return 1, RANK skips 2 and 3 and assigns 4 to the next row in the group.”
↩︎ Ranking with ties: RANK versus DENSE_RANK - 5.
“QUALIFY does with window functions what HAVING does with aggregate functions and GROUP BY clauses.”
↩︎ Filtering on window results with QUALIFY“The QUALIFY clause simplifies queries that require filtering on the result of window functions. Without QUALIFY, filtering requires nesting.”
↩︎ Filtering on window results with QUALIFY“Expressions in the SELECT list, including window functions, can be referred to by the column alias defined in the SELECT list.”
↩︎ Filtering on window results with QUALIFY“FROM WHERE GROUP BY HAVING WINDOW QUALIFY DISTINCT ORDER BY LIMIT”
↩︎ Exam trap 3 - 6.
“Use QUALIFY when you need the entire row for each key.”
↩︎ Filtering on window results with QUALIFY“When a query combines multiple blocking operators, each one must wait for the previous to finish.”
↩︎ Applying SQL for query optimization in transformations“Window functions (the entire partition must be processed before producing output)”
↩︎ Applying SQL for query optimization in transformations“Deduplicate early. Remove duplicate rows upstream to avoid repeated DISTINCT work downstream.”
↩︎ Applying SQL for query optimization in transformations“The QUALIFY version is explicit about which duplicate to keep.”
↩︎ Applying SQL for query optimization in transformations - 7.
“Snowflake higher-order functions provide a concise, readable, and efficient way to perform data manipulation and advanced analysis.”
↩︎ Applying SQL for query optimization in transformations
Also cited
“Tie values result in the same rank value, but unlike RANK, they do not result in gaps in the sequence.”
↩︎ Exam trap 1