CertSafari
    Snowflake SnowPro Core Certification (COF-C03)· Lessons

    Domain 4 · Lesson 16/19

    Aggregate functions, window functions and QUALIFY in Snowflake

    Perform data transformation techniques

    14 min read
    5.25% of exam
    8 sources
    Published 20 Oct 2026
    Docs as of 4 Oct 2026

    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.

    Three of the four rows contain a NULL, so only one is countedsql
    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?

    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.

    The same AVG used two ways
    AspectAggregate: AVG(...) with GROUP BYWindow: AVG(...) OVER (...)
    InputA group of rowsEach row within a partition
    OutputOne row per groupOne row per input row
    Other columnsOnly grouped or aggregated columnsAny 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'.

    A moving average over the current row and the next two rows in each categorysql
    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;

    Checkpoint 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?

    Sources23

    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.

    Corn production ranked by bushels DESC, with a tie at 110
    BushelsRANK()DENSE_RANK()
    13011
    12022
    11033
    11033
    10054

    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?

    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?

    Sources43

    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.

    The nested pattern QUALIFY replacessql
    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.

    One row per customer: the most recently updated onesql
    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?

    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?

    Sources56

    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.

    ROW_NUMBER moved to the outer query, where completed_on is no longer correlatedsql
    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?

    Sources637

    Sources

    (8)

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

    1. 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. 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. 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. 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. 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. 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. 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

    Ready to test yourself?

    Practise the 21 questions on this subdomain.

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