CertSafari
    Snowflake SnowPro Advanced: Data Scientist (DSA-C03)· Lessons

    Domain 2 · Lesson 5/16

    Preparing and cleaning data in Snowflake with SQL and Snowpark

    Prepare and clean data in Snowflake.

    20 min read
    6.75% of exam
    12 sources
    Published 20 Oct 2026
    Docs as of 18 Oct 2026

    What you will be able to do

    • Measure missing values and repeated keys in a table with system data metric functions before writing cleaning code
    • Drop irrelevant columns and cast text columns to proper types without one bad value failing the whole load
    • Keep exactly one chosen row per key with QUALIFY and ROW_NUMBER, and explain why DISTINCT cannot do that
    • Predict which rows an inner, left, right, full or cross join keeps, and stop a one-to-many join from inflating sums
    • Fill NULLs with COALESCE, aggregate with GROUP BY, and draw repeatable row or block samples

    Key concept

    Row grain — Each cleaning step decides how many rows one entity (a customer, an order) ends up with. Joins can multiply rows, GROUP BY and QUALIFY reduce them, and most dirty-data bugs in a training table come from a step that left the data at a different grain than the one you meant.

    1.Measuring data quality before you clean

    Measure the problems before you fix them. You need to know which columns have gaps and which keys repeat, and how much of each. You also need that measurement again on every load, because a staging table that was clean last month can arrive with a batch of blank keys. Running a one-off COUNT in a worksheet tells you about today only.

    Snowflake's system data metric functions (DMFs) do this measuring. They live in the CORE schema of the shared SNOWFLAKE database, and each one measures one quality attribute of a column. SNOWFLAKE.CORE.NULL_COUNT returns the number of NULLs in a column. SNOWFLAKE.CORE.DUPLICATE_COUNT counts the values that occur more than once, NULLs included. You can call a DMF directly by passing it a query that selects one column. You can also attach it to a table or view so that it runs at regular intervals and records a new result each time. That repeated result is what a data steward watching RAW.CLAIMS needs: a missing-value count for claim_amount and a repeated-key count for claim_id on every run.

    System DMFs that size the problems you clean in this lesson
    System DMFWhat it measuresCleaning step it informs
    NULL_COUNTHow many NULL values are in a columnFilling or dropping missing values
    NULL_KEYWORD_COUNTNon-NULL strings that are a text placeholder for a missing valueFinding missing values that NULL_COUNT does not see
    EMPTY_STRING_COUNTHow many empty strings are in a columnDeciding whether '' should become NULL
    DUPLICATE_COUNTDuplicate values in a column, including NULL valuesDeduplicating on a key
    INVALID_NUMERIC_TYPE_CAST_COUNTValues that can’t be cast to a numberChoosing between CAST and TRY_CAST

    You can attach several DMFs to one table, and DUPLICATE_COUNT can check a combination of columns. With more than one column argument it counts rows where that combination repeats. A multi-column check has to be attached to the table, because you can't call it directly. A table's schema can say that a column is allowed to hold NULLs, but only a measurement over its rows says how many NULLs it actually holds.

    Attaching DUPLICATE_COUNT to a table to check duplicates on a pair of columnssql
    ALTER TABLE t
      ADD DATA METRIC FUNCTION SNOWFLAKE.CORE.DUPLICATE_COUNT
        ON (first_name, last_name);

    Checkpoint 1 of 11· Match them up

    A data steward attaches system DMFs to RAW.CLAIMS to size the problems before anyone cleans the table. Match each DMF to the cleaning decision its result informs.

    Tap a term, then the definition that fits it.

    Checkpoint 2 of 11· Exam question

    A data steward wants to quantify data-quality problems in RAW.CLAIMS on an ongoing basis before any cleaning code is written. They need repeated measurements of missing values in claim_amount and of repeated claim_id values. Select TWO actions that achieve this.(Select 2)

    0 of 2 selected

    Sources1234

    2.Dropping fields the model should not see

    Fewer columns means less to clean and less for the model to latch onto by accident. Free-text notes, internal surrogate IDs and audit timestamps rarely belong in a feature table. In SQL, SELECT * EXCLUDE (col_a, col_b) keeps every column except the ones you name. It is the shorter choice when you are dropping three columns from a sixty-column table. An explicit column list wins when you want the feature set fixed, so that a new column added upstream doesn't slip into training.

    In Snowpark for Python, select on a DataFrame does the same job, after session.table or session.sql has built the DataFrame. A DataFrame from session.sql accepts filter and select only when its SQL is a SELECT statement. On something like ls @my_stage, the same calls raise a compilation error. A chain of filter, select and casts compiles into a single query, as explained in Lazy DataFrame evaluation (pushdown). Calling collect or to_pandas partway through the chain breaks that pushdown and pulls the data to the client before the cleaning is finished.

    Checkpoint 3 of 11· Check yourself

    You are building a feature DataFrame in Snowpark for Python and want to call filter and select on it. Which of these chains raises a SQL compilation error?

    Sources56

    3.Casting types without losing the whole load

    Raw tables often store numbers and dates as text, and models need real types. CAST (or ::) converts a value. On a value it cannot convert it raises an error, and the error fails the whole statement, so one 'n/a' in ten million rows stops the load. TRY_CAST does the same conversion but returns NULL for any value it cannot convert. TRY_CAST('05/16' AS TIMESTAMP) gives NULL, while TRY_CAST('05-Mar-2016' AS TIMESTAMP) gives a proper timestamp.

    TRY_CAST has two limits. It accepts string input only, and the target must be VARCHAR, NUMBER, DOUBLE, BOOLEAN, DATE, TIME, a TIMESTAMP variant or an interval. It also turns bad input into new missing values without any warning. Count the bad values first with INVALID_NUMERIC_TYPE_CAST_COUNT. Two hundred bad rows can simply become NULLs, but thirty per cent of a column failing to convert points to a format problem that no cast will fix.

    A VARIANT column holds JSON-like data, such as a customer record with nested elements. FLATTEN turns those nested elements into rows and exposes each one in a column named value, so value['name'] reads the name field of one element. In Snowpark, join_table_function calls a table function such as FLATTEN on a DataFrame. Column.cast takes a type object such as StringType() and behaves like SQL CAST. The example below flattens the customer elements of a VARIANT column, casts each field to a string and renames it with as_.

    Snowpark: casting flattened VARIANT fields to strings and renaming thempython
    df.join_table_function("flatten", col("src")["customer"]).select(col("value")["name"].cast(StringType()).as_("Customer Name"), col("value")["address"].cast(StringType()).as_("Customer Address")).show()

    Checkpoint 4 of 11· Check yourself

    In Snowpark for Python, after FLATTEN you want the VARIANT field value['name'] to become a string column called "Customer Name" in your feature DataFrame. Which column expression does both?

    Sources746

    4.Removing duplicates: identical rows versus one row per key

    There are two kinds of duplicate, and each has its own fix. SELECT DISTINCT (or distinct() on a DataFrame) removes rows that are identical in every selected column. That is the right tool when a file was loaded twice. It does nothing for a snapshot table with several rows per customer_id that differ in updated_at, because those rows are not identical and all of them survive.

    To keep one particular row per key, number the rows inside each key and keep row 1. ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) numbers each customer's rows from newest to oldest, and QUALIFY keeps only the rows numbered 1. QUALIFY filters on window-function results the way HAVING filters on aggregates, so it saves you a nested subquery. The ORDER BY inside the window decides which row is kept. Without it, nothing defines which row comes first.

    QUALIFY with ROW_NUMBER keeps the first row of each partitionsql
    SELECT i, p, o
      FROM qt
      QUALIFY ROW_NUMBER() OVER (PARTITION BY p ORDER BY o) = 1;

    Checkpoint 5 of 11· Check yourself

    A snapshot table CUSTOMER_SNAPSHOTS holds several rows for each customer_id. The rows differ only in updated_at. An engineer runs SELECT DISTINCT * FROM customer_snapshots so that each customer has a single row in the training table. What does the query return?

    Checkpoint 6 of 11· Exam question

    A Snowpark for Python pipeline loads a CUSTOMER_SNAPSHOT DataFrame with several rows per customer_id, each carrying a different updated_at timestamp. The churn model must train on only the most recent row for every customer. Which approach is MOST appropriate?

    Sources589

    5.Joins: which rows survive, and where NULLs and repeats come from

    A join decides which rows reach the next step. Each join type answers one question differently: what happens to a row that has no match on the other side? In the table below, o1 is the left table (the one written before JOIN) and o2 is the right table (the one written after it).

    Join types by the rows they keep
    JoinRows in the resultWhere NULLs come from
    INNER JOIN (the default for bare JOIN)One row for every matching pair; unmatched rows on either side are droppedOnly from NULLs already in the data
    LEFT OUTER JOINInner-join rows plus every unmatched o1 rowColumns from o2 on unmatched o1 rows
    RIGHT OUTER JOINInner-join rows plus every unmatched o2 rowColumns from o1 on unmatched o2 rows
    FULL OUTER JOINInner-join rows plus unmatched rows from both sidesWhichever side had no match
    CROSS JOIN, or a join with no ON clauseEvery o1 row paired with every o2 rowNone added; the row count multiplies

    This repetition, called fan-out, is the usual reason a customer-spend feature comes out about double what finance reports. Every one-side column is repeated once for each match on the many side. One fix is to aggregate PAYMENTS to one row per order_id in a subquery or an intermediate DataFrame, then join. Another is to sum order_total from ORDERS alone at customer level and join the payment aggregates afterwards. Changing the join type makes things worse: an outer join only adds rows for unmatched keys. SUM(DISTINCT order_total) also gives wrong answers, because two different orders that each total 100 merge into a single 100.

    Checkpoint 7 of 11· Match them up

    Match each way of joining CUSTOMERS (left) to ORDERS (right) with the rows it returns to the feature pipeline.

    Tap a term, then the definition that fits it.

    Checkpoint 8 of 11· Exam question

    A feature pipeline joins ORDERS (one row per order) to PAYMENTS (several installment rows per order) and then sums order_total per customer. The resulting customer spend values are roughly double what finance reports. Select TWO changes that fix the problem.(Select 2)

    0 of 2 selected

    Sources10

    6.Filling missing values with COALESCE

    Missing values come from two places: gaps in the source data, and outer joins that fill unmatched columns with NULL. A customer with no support tickets ends up with ticket_count = NULL after a LEFT JOIN, even though the true value is 0. COALESCE(ticket_count, 0) returns its first non-NULL argument, so it restores the 0. With several arguments it works down a chain of fallbacks, for example COALESCE(mobile, home_phone, work_phone). If every argument is NULL, the result is NULL.

    COALESCE converts its arguments to a common type, and that conversion can fail. When one argument is numeric, the result is numeric. COALESCE('17', 1) returns 17, but COALESCE('foo', 1) raises an error because 'foo' cannot become a NUMBER. A numeric value produced by implicit conversion from text comes out as NUMBER(18,5), which can be too small for wide values. Pass arguments of the same type, or cast first, ideally with TRY_CAST so that unparseable strings reach COALESCE as NULL.

    Checkpoint 9 of 11· Check yourself

    Your feature query joins CUSTOMERS LEFT OUTER JOIN TICKET_COUNTS (one row per customer_id that has tickets) and selects COALESCE(ticket_count, 0). Which rows does the COALESCE actually change?

    Sources11

    7.Aggregating with GROUP BY

    GROUP BY reduces many rows to one row per group and computes aggregates such as SUM over each group. Every SELECT item that is not an aggregate has to be a grouping key. GROUP BY ALL uses every non-aggregate item in the SELECT list as a key, so a query with state, city, SUM(...) groups by state and city. If every SELECT item is an aggregate, GROUP BY ALL is the same as having no GROUP BY at all.

    Profit per product: join sales to products, then aggregate sales-level amountssql
    SELECT p.product_ID, SUM((s.retail_price - p.wholesale_price) * s.quantity) AS profit
      FROM products AS p, sales AS s
      WHERE s.product_ID = p.product_ID
      GROUP BY p.product_ID;

    The query is safe from fan-out even though it aggregates after a join. Each products row matches many sales rows, but the sum adds up sales-level quantities, which appear once per sale. The comma in FROM products AS p, sales AS s with the WHERE condition is an inner join.

    Watch for aliases that share a name with a real column. If a SELECT gives ANY_VALUE(employment_state) the alias state and the table also has a state column, GROUP BY state groups by the column, not the alias. The output then shows employment statuses but groups by the geographic state. Give derived columns names that no source column uses.

    Checkpoint 10 of 11· Fill the gap

    This feature query should return one profit row per product. Which grouping key completes it?

    SELECT p.product_ID, SUM((s.retail_price - p.wholesale_price) * s.quantity) AS profit
      FROM products AS p, sales AS s
      WHERE s.product_ID = p.product_ID
      GROUP BY  ? ;

    Sources910

    8.Sampling rows with SAMPLE and TABLESAMPLE

    A sample lets you try cleaning logic, or train a first model, on a slice of a table. SAMPLE and TABLESAMPLE are synonyms, and so are ROW and BERNOULLI, BLOCK and SYSTEM, SEED and REPEATABLE. A sample is either a percentage, SAMPLE (10), or a fixed count, SAMPLE (10 ROWS), with a maximum of 1,000,000 rows. From Snowpark, run the same SQL through session.sql to get a DataFrame.

    Sampling methods compared
    MethodWhat gets pickedFixed-size (n ROWS)SeedWhen it wins
    BERNOULLI / ROW (default)Each row with probability p/100; expect about (p/100)*n rowsSupportedNot with n ROWSUnbiased samples, especially from small tables
    SYSTEM / BLOCKEach block (usually a micro-partition) with probability p/100Not supportedSEED or REPEATABLE makes it deterministicSpeed on very large tables, where its bias is negligible
    LIMIT nThe n rows that are fastest to returnAlways nNot applicablePreviewing rows, never as a random sample

    Repeatability depends on the seed. Without a seed, each run of the same query returns a different sample. With a seed on an unchanged table, the same seed and the same probability return the same rows, but a copy of the table may sample differently. A seed is rejected on fixed-size samples, so SAMPLE ROW (10 ROWS) SEED (99) errors, and it is also rejected on views and subqueries.

    A SAMPLE clause samples only the table it follows. In t1 JOIN t2 SAMPLE (50), every row of t1 is joined to half of t2. To sample the result of a join, put the join in a subquery and sample that, using row-based sampling without a seed. That sample is taken after the full join has run, so it does not make the join any cheaper.

    Sampling about 1% of a join's output by sampling a subquerysql
    SELECT *
      FROM (
           SELECT *
             FROM t1 JOIN t2
               ON t1.a = t2.c
           ) SAMPLE (1);

    Checkpoint 11 of 11· Check yourself

    To make a training experiment reproducible, an engineer needs a query that returns the same sample each time it runs against an unchanged CLAIMS table. Which query does that?

    Sources12

    Sources

    (12)

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

    1. 1.
      “Snowflake provides built-in system data metric functions to measure data quality for tables and views”
      ↩︎ Measuring data quality before you clean
    2. 2.
      “Returns the total number of NULL values for the specified column in a table.”
      ↩︎ Measuring data quality before you clean
      “To learn how to associate the function with a table or view so it runs at regular intervals, see Associate a DMF.”
      ↩︎ Measuring data quality before you clean
    3. 3.
      “Returns the count of column values that have duplicates, including NULL values.”
      ↩︎ Measuring data quality before you clean
      “If you specify more than one column argument, returns the number of rows where the combination of the specified columns is duplicated.”
      ↩︎ Measuring data quality before you clean
    4. 4.
      “Snowflake provides system DMFs in the CORE schema of the shared SNOWFLAKE database.”
      ↩︎ Measuring data quality before you clean
      “INVALID_NUMERIC_TYPE_CAST_COUNT counts values that can’t be cast to a number.”
      ↩︎ Casting types without losing the whole load
    5. 5.
      “As a clause, SELECT defines the set of columns returned by a query.”
      ↩︎ Dropping fields the model should not see
      “DISTINCT eliminates duplicate values from the result set.”
      ↩︎ Removing duplicates: identical rows versus one row per key
      “DISTINCT eliminates duplicate values from the result set.”
      ↩︎ Exam trap 1
      “DISTINCT eliminates duplicate values from the result set.”
      ↩︎ Checkpoint
    6. 6.
      “these methods work only if the underlying SQL statement is a SELECT statement”
      ↩︎ Dropping fields the model should not see
      “A DataFrame represents a relational dataset that is evaluated lazily: it only executes when a specific action is triggered.”
      ↩︎ Dropping fields the model should not see
      “The following code adds to the previous example by casting the values to a specific type and changing the names of the columns”
      ↩︎ Casting types without losing the whole load
      “note that these methods work only if the underlying SQL statement is a SELECT statement.”
      ↩︎ Checkpoint
    7. 7.
      “but returns a NULL value instead of raising an error when the conversion can not be performed”
      ↩︎ Casting types without losing the whole load
      “Only works for string expressions.”
      ↩︎ Casting types without losing the whole load
      “Only works for string expressions.”
      ↩︎ Exam trap 2
    8. 8.
      “The example below uses the ROW_NUMBER() function to return only the first row in each partition.”
      ↩︎ Removing duplicates: identical rows versus one row per key
      “QUALIFY does with window functions what HAVING does with aggregate functions and GROUP BY clauses.”
      ↩︎ Removing duplicates: identical rows versus one row per key
    9. 9.
      “Groups rows with the same group-by-item expressions and computes aggregate functions for the resulting group.”
      ↩︎ Removing duplicates: identical rows versus one row per key
      “Specifies that all items in the SELECT list that do not use aggregate functions should be used for grouping.”
      ↩︎ Aggregating with GROUP BY
      “If a clause contains a name that matches both a column name and an alias, then the clause uses the column name.”
      ↩︎ Aggregating with GROUP BY
      “If a clause contains a name that matches both a column name and an alias, then the clause uses the column name.”
      ↩︎ Exam trap 5
    10. 10.
      “The result of the inner join is augmented with a row for each row of o1 that has no matches in o2.”
      ↩︎ Joins: which rows survive, and where NULLs and repeats come from
      “The result columns referencing o2 contain null.”
      ↩︎ Joins: which rows survive, and where NULLs and repeats come from
      “omitting the ON clause results in a Cartesian product; every row of object_ref1 paired with every row of object_ref2.”
      ↩︎ Joins: which rows survive, and where NULLs and repeats come from
      “You can also use a comma to specify an inner join.”
      ↩︎ Aggregating with GROUP BY
      “For each row of o1, a row is produced for each row of o2 that matches according to the ON condition subclause.”
      ↩︎ Key concept
      “For each row of o1, a row is produced for each row of o2 that matches according to the ON condition subclause.”
      ↩︎ Prediction
      “a row for each row of o1 that has no matches in o2. The result columns referencing o2 contain null.”
      ↩︎ Checkpoint
    11. 11.
      “Returns the first non-NULL expression among its arguments, or NULL if all its arguments are NULL.”
      ↩︎ Filling missing values with COALESCE
      “For example, SELECT COALESCE('foo', 1); returns an error because the VARCHAR value 'foo' can’t be converted to a NUMBER value.”
      ↩︎ Filling missing values with COALESCE
      “When implicit conversion converts a non-numeric value to a numeric value, the result is a value of type NUMBER(18,5).”
      ↩︎ Filling missing values with COALESCE
    12. 12.
      “SAMPLE and TABLESAMPLE are synonymous and can be used interchangeably.”
      ↩︎ Sampling rows with SAMPLE and TABLESAMPLE
      “If no seed is specified, SAMPLE generates different results when the same query is repeated.”
      ↩︎ Sampling rows with SAMPLE and TABLESAMPLE
      “For SYSTEM or BLOCK sampling, the sample might be biased, in particular for small tables.”
      ↩︎ Sampling rows with SAMPLE and TABLESAMPLE
      “Sampling with SEED (seed) isn’t supported on views or subqueries.”
      ↩︎ Sampling rows with SAMPLE and TABLESAMPLE
      “Therefore, sampling doesn’t reduce the number of rows joined and doesn’t reduce the cost of the join.”
      ↩︎ Sampling rows with SAMPLE and TABLESAMPLE
      “When you use the LIMIT clause, Snowflake returns the specified number of rows in the fastest way possible.”
      ↩︎ Sampling rows with SAMPLE and TABLESAMPLE
      “SYSTEM, BLOCK, and SEED (seed) aren’t supported for fixed-size sampling.”
      ↩︎ Exam trap 3
      “The SAMPLE clause applies to only one table, not all preceding tables or the entire expression prior to the SAMPLE clause.”
      ↩︎ Exam trap 4
      “If a table doesn’t change, and the same seed and probability are specified, SAMPLE generates the same result.”
      ↩︎ Checkpoint

    Ready to test yourself?

    Practise the 24 questions on this subdomain.

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