What you will be able to do
- Choose between GROUP BY aggregation and an OVER clause based on whether you need one row per group or one row per input row
- Predict how ROWS and RANGE frames, including the implied frame, treat rows that tie on the ORDER BY value
- Pick ROW_NUMBER, RANK or DENSE_RANK for a ranking requirement and filter on the result with QUALIFY
Key concept
Window function — A function with an OVER clause that computes a value for every input row from a related set of rows (its partition and window frame), instead of collapsing the group into one output row the way a GROUP BY aggregate does.
1.GROUP BY aggregates versus OVER windows
Most validation and reporting queries begin with an aggregate: a total, an average, a count per category. In Snowflake the same function name, such as SUM, COUNT or AVG, can do two different jobs, and the OVER clause decides which. Without OVER, the function is an aggregate: a group of rows goes in and one row comes out. With OVER, it becomes a window function, which operates on a group of related rows called a partition and returns one result per input row.
Take a food-truck menu_items table with 60 rows. AVG(menu_cogs_usd) with GROUP BY menu_category returns four rows, one per category: Beverage 0.60, Dessert 1.79, Main 6.11, Snack 3.10. Move the same average into OVER(PARTITION BY menu_category) and the query returns all 60 rows. Every Beverage row carries 0.60, and every Dessert row carries 1.79. The calculation resets whenever the partitioning value changes.
SELECT menu_category,
AVG(menu_cogs_usd) OVER(PARTITION BY menu_category) avg_cogs
FROM menu_items
ORDER BY menu_category
LIMIT 15;That per-row shape is why windows suit analysis. You can put each item's cost beside its category average and compare the two in the same row, which a grouped result can't do because the detail rows are gone. The OVER clause has three optional parts: PARTITION BY, ORDER BY and a window frame. OVER() with nothing inside is valid and treats the whole result as one partition. The two inner clauses are independent, so you can use ORDER BY without PARTITION BY and the reverse.
There are two different ORDER BY clauses to keep apart. The one inside OVER controls only the order in which the window function processes rows. It does not sort the final output, so most analytic queries need both. Ordinal positions also behave differently: in OVER (PARTITION BY 1 ORDER BY 2), the 2 is read as the constant 2, not the second column.
Checkpoint 1 of 6· Fill the gap
You need all 60 menu_items rows back, with each row showing the average cost of goods for its own menu category so you can compare items to their category. Which keyword completes the OVER clause?
SELECT menu_category,
AVG(menu_cogs_usd) OVER( ? BY menu_category) avg_cogs
FROM menu_items
ORDER BY menu_category
LIMIT 15;PARTITION BY splits the rows into one partition per category. The average is calculated for each partition and returned on every input row, starting over when the category changes. GROUP BY is not valid inside OVER, and as an aggregate clause it would return only one row per category. ORDER BY inside OVER sets only the order in which the function processes rows; it does not split the rows by category.
Source: docs.snowflake.comSources1
2.Window frames: ROWS, RANGE and the implied frame
A window frame narrows the partition to a set of rows relative to the current row, and running totals and moving averages are built from it. The frame is declared with ROWS or RANGE plus a start and end boundary. Named boundaries are CURRENT ROW, UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING. Explicit offsets are written as n PRECEDING or n FOLLOWING. A frame only makes sense over ordered rows, so any window with an explicit frame needs an ORDER BY.
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 run out at the edge of a partition. The last Beverage row has no following rows, so its three-row average is just its own cost, 0.65. The ORDER BY also lists menu_cogs_usd after menu_price_usd as a tiebreaker. Several items share a price, and without a second column the order of those rows, and so each frame's contents, could change from one run to the next.
The difference between the two frame types is physical versus logical. ROWS counts actual rows. RANGE takes a logically computed set: every row whose ORDER BY value falls inside the boundary. With RANGE ... CURRENT ROW, all rows that tie with the current value count as the current row. When SUM is called with an ORDER BY and no frame, Snowflake applies RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. On days with several orders, that produces a staircase: one figure repeated across the whole day. To get a total that grows row by row, declare ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW and add a unique tiebreaker to the ORDER BY. Snowflake itself recommends declaring frames explicitly, because implied behaviour is hard to read.
| Requirement | Frame | Effect on tied ORDER BY values |
|---|---|---|
| Running total that grows on every row | ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, plus a tiebreaker | Each tied row is counted separately, in tiebreaker order |
| Cumulative total as of each date | RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (also the implied frame) | Every row on the same date gets the same total |
| Moving window of a fixed row count | ROWS BETWEEN n PRECEDING AND CURRENT ROW | Exactly n earlier rows, whatever their values |
| Window of a value distance, such as 3 days | RANGE BETWEEN INTERVAL '3 days' PRECEDING AND CURRENT ROW | All rows within the distance, however many there are |
RANGE with explicit offsets has stricter rules than ROWS. It allows exactly one ORDER BY expression, and that expression must be a NUMBER, DATE or timestamp type. TIME and VARCHAR are not allowed there. The offset has to match the type: a numeric column takes an unsigned constant, a TIMESTAMP column needs an INTERVAL constant such as INTERVAL '12 hours', and a DATE column accepts either, as long as both ends of the frame use the same one. Only some functions support this form, including SUM, COUNT, AVG, MIN, MAX, FIRST_VALUE and LAST_VALUE, and not their DISTINCT versions.
Checkpoint 2 of 6· Check yourself
For each order row, an analyst wants the sum of every order placed in the 3 days up to and including that order's order_ts (a TIMESTAMP column), however many orders fall in those days. Which window frame meets the requirement?
The requirement is a distance in time, not a number of rows. So it needs a RANGE frame, which takes in every row whose ORDER BY value falls inside the boundary. A ROWS frame would count exactly three earlier rows, whatever their dates. On a TIMESTAMP column the offset must be an INTERVAL constant, so the bare offset 3 is not valid. UNBOUNDED PRECEDING would give a cumulative total from the first order instead of a 3-day window.
“Specifies the type or mode of window frame, which defines either a physical number of rows (ROWS) or a logically computed set of rows (RANGE).”Source: docs.snowflake.com
Checkpoint 3 of 6· Exam question
A dashboard query uses SUM(amount) OVER (ORDER BY sale_date) to build a running total. Several orders share the same sale_date, and every row of that day shows the same cumulative figure instead of growing row by row. Which change produces a true row-by-row running total?
Correct answer: D — Declare ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW and add a unique tiebreaker column to the ORDER BY clause.
- A. Partitioning by sale_date restarts the sum on every date, so the result becomes a per-day total rather than a cumulative total across days.
- B. DISTINCT only removes duplicate output rows after the window is computed; it does not change the frame, and it would drop legitimate orders from the day.
- C. A one-row-back frame yields a sliding two-row sum, not a cumulative total from the first row, so later rows would not accumulate history.
- D. The default frame with ORDER BY is RANGE, which treats rows with the same date as peers. An explicit ROWS frame plus a tiebreaker makes each row accumulate individually.
3.Ranking functions and filtering them with QUALIFY
Ranking functions answer questions like "most recent event per customer" or "second-highest salary". They need input in a meaningful order, so RANK, DENSE_RANK and NTILE all require an ORDER BY inside OVER. Where they differ is in how they handle ties, and that is what you get tested on.
Here is how each function numbers four salaries of 90, 90, 80 and 70, sorted in descending order:
ROW_NUMBERnumbers rows 1, 2, 3, 4. The two 90s get different numbers, so= 2returns a 90 earner, and which one depends on how the tie happens to be ordered.RANKgives tied values the same rank and then skips: 1, 1, 3, 4. Nobody is ranked 2.DENSE_RANKgives tied values the same rank without gaps: 1, 1, 2, 3.= 2returns the 80 earner.
NTILE also needs ordered rows, but it puts each row into one of a set number of buckets. Its result is a bucket number, not a position among distinct values.
The answer comes from the order in which Snowflake evaluates a SELECT: FROM, WHERE, GROUP BY, HAVING, WINDOW, QUALIFY, DISTINCT, ORDER BY, LIMIT. WHERE and HAVING run before window functions are computed, so they can't filter on a window result. QUALIFY runs right after the windows. It filters window results the way HAVING filters aggregates, and it needs at least one window function, either in the SELECT list or in its own predicate. QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY event_ts DESC) = 1 keeps one row per customer in a single SELECT, with no subquery or CTE wrapped around it.
Window functions also can't use correlated columns. If a window inside a LATERAL subquery orders by a column from the outer query block, compilation fails with "contains a correlation". The fix is to move the window function into the outer query, where the column is no longer correlated.
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 4 of 6· Check yourself
Compilation fails with "Window function [ROW_NUMBER() ...] contains a correlation". The ROW_NUMBER() OVER(ORDER BY f.value:completed_on DESC) call sits inside a LATERAL subquery over FLATTEN output. Which change makes the query run and still number the rows by completed_on?
Window functions can't reference columns from an outer query block in their PARTITION BY or ORDER BY. Changing the partitioning, the ranking function or the frame leaves that reference in place. If the subquery projects completed_on and ROW_NUMBER runs in the outer query, the column is no longer correlated and the query compiles.
“Move the window function to the outer query where the correlation no longer exists.”Source: docs.snowflake.com
Checkpoint 5 of 6· Exam question
An analyst queries a customer_events table that holds many rows per customer_id, each with an event_ts column. They must return only the most recent row per customer in one SELECT, without a wrapping subquery or CTE. Which approach meets the requirement?
Correct answer: B — Append QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY event_ts DESC) = 1 so the window result filters the rows.
- A. DISTINCT ON is PostgreSQL syntax and is not supported by Snowflake, so this statement fails to compile; QUALIFY with a ranking function is the Snowflake idiom.
- B. QUALIFY filters on window function results after they are computed, so ranking each customer's events newest-first and keeping row number 1 returns the latest event without nesting.
- C. HAVING filters grouped aggregate results, and a window function is not allowed there; grouping by customer_id would also collapse the detail rows being ranked.
- D. WHERE is evaluated before window functions are computed, so a window function in that clause raises an error instead of filtering the ranked rows.
Checkpoint 6 of 6· Exam question
A salaries table contains four employees earning 90, 90, 80 and 70. The analyst must list every employee who earns the second-highest distinct salary, which is 80, and the ranking must have no gaps after ties. Which filter returns the correct employee?
Correct answer: C — QUALIFY DENSE_RANK() OVER (ORDER BY salary DESC) = 2, because DENSE_RANK gives tied salaries one position and never skips numbers.
- A. RANK leaves a gap after ties, so the two 90 earners both get 1 and the 80 earner gets 3; no row has rank 2 and the query returns nothing.
- B. ROW_NUMBER breaks ties arbitrarily, so row 2 is one of the two 90 earners rather than the 80 earner.
- C. DENSE_RANK gives both 90 earners rank 1 and the 80 earner rank 2 with no gap, so filtering on 2 returns exactly the second-highest distinct salary.
- D. NTILE(2) puts the lower half of the rows into bucket 2, which here returns both the 80 and the 70 earner rather than one salary tier.
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“A window function is an analytic SQL function that operates on a group of related rows known as a partition.”
↩︎ GROUP BY aggregates versus OVER windows“it does not control the output of the entire query.”
↩︎ GROUP BY aggregates versus OVER windows“If multiple rows have the same value for the ORDER BY columns, add additional columns as tiebreakers”
↩︎ Window frames: ROWS, RANGE and the implied frame“Snowflake recommends declaring window frames explicitly.”
↩︎ Window frames: ROWS, RANGE and the implied frame“For a window function, the input is each row within a partition, and the output is one row per input row.”
↩︎ Key concept - 2.
“RANGE BETWEEN window frames with explicit offsets must have only one ORDER BY expression.”
↩︎ Window frames: ROWS, RANGE and the implied frame“ranking window functions such as RANK and NTILE require their input data to be in a meaningful order.”
↩︎ Ranking functions and filtering them with QUALIFY“Using correlated columns inside window functions (such as in the PARTITION BY or ORDER BY clauses) is not supported.”
↩︎ Ranking functions and filtering them with QUALIFY“defines either a physical number of rows (ROWS) or a logically computed set of rows (RANGE)”
↩︎ Exam trap 1“Specifies the type or mode of window frame, which defines either a physical number of rows (ROWS) or a logically computed set of rows (RANGE).”
↩︎ Checkpoint“Move the window function to the outer query where the correlation no longer exists.”
↩︎ Checkpoint - 3.
“If no window frame is specified explicitly, the following implied window frame is used: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW”
↩︎ Window frames: ROWS, RANGE and the implied frame - 4.
“FROM WHERE GROUP BY HAVING WINDOW QUALIFY DISTINCT ORDER BY LIMIT”
↩︎ Ranking functions and filtering them with QUALIFY“QUALIFY does with window functions what HAVING does with aggregate functions and GROUP BY clauses.”
↩︎ Exam trap 3 - 5.
“Tie values result in the same rank value, but unlike RANK, they do not result in gaps in the sequence.”
↩︎ Ranking functions and filtering them with QUALIFY“Tie values result in the same rank value, but unlike RANK, they do not result in gaps in the sequence.”
↩︎ Exam trap 2