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 DMF | What it measures | Cleaning step it informs |
|---|---|---|
| NULL_COUNT | How many NULL values are in a column | Filling or dropping missing values |
| NULL_KEYWORD_COUNT | Non-NULL strings that are a text placeholder for a missing value | Finding missing values that NULL_COUNT does not see |
| EMPTY_STRING_COUNT | How many empty strings are in a column | Deciding whether '' should become NULL |
| DUPLICATE_COUNT | Duplicate values in a column, including NULL values | Deduplicating on a key |
| INVALID_NUMERIC_TYPE_CAST_COUNT | Values that can’t be cast to a number | Choosing 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.
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.
Each system DMF measures one quality attribute of a column. That count tells you which cleaning step to apply and how big the problem is. DUPLICATE_COUNT includes NULLs when it counts repeated key values.
“DISTINCT eliminates duplicate values from the result set.”Source: docs.snowflake.com
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)
Correct answers: C, D — Set a DATA_METRIC_SCHEDULE on the table and associate the system DMF SNOWFLAKE.CORE.NULL_COUNT with claim_amount to track missing values per run.; Associate SNOWFLAKE.CORE.DUPLICATE_COUNT with the claim_id column so that each scheduled evaluation reports how many values of that key occur more than once.
- A. Incorrect.
FRESHNESSreports how recently data in a timestamp column was updated; it says nothing about repeated key values. - B. Incorrect.
IS_NULLABLEis a schema constraint flag, not a count of stored NULLs, so it cannot measure missing data. - C. Correct. System DMFs run on the schedule defined for the table, and
NULL_COUNTreports how many NULLs a column holds at each measurement. - D. Correct.
DUPLICATE_COUNTis the system metric that measures repeated values, which is exactly what a key-uniqueness check needs. - E. Incorrect. A stream captures row changes and action metadata only, and it holds no per-column quality statistics.
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?
A DataFrame built with session.sql accepts transformation methods like filter and select only when its SQL is a SELECT statement. LS is not a SELECT, so filtering on its output fails with a compilation error. The other three chains start from a table or from a SELECT statement, and SELECT * EXCLUDE counts as a SELECT.
“note that these methods work only if the underlying SQL statement is a SELECT statement.”Source: docs.snowflake.com
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_.
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?
Column.cast takes a type object such as StringType() and converts the value. as_ then renames the resulting column. With cast alone, the column keeps its default name. Swapping the two methods passes a type where a name belongs and a name where a type belongs.
“The following code adds to the previous example by casting the values to a specific type and changing the names of the columns”Source: docs.snowflake.com
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.
SELECT i, p, o
FROM qt
QUALIFY ROW_NUMBER() OVER (PARTITION BY p ORDER BY o) = 1;GROUP BY returns one row per group holding only the grouping columns and the aggregates. You get each customer's latest timestamp, but none of the other columns from that row come along. You would have to join back to the snapshot table to recover them.
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?
DISTINCT removes only rows that are identical in every selected column. The updated_at values make each snapshot row unique, so all of them survive. To keep the newest row per customer, use ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) and QUALIFY to keep row 1.
“DISTINCT eliminates duplicate values from the result set.”Source: docs.snowflake.com
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?
Correct answer: A — Add row_number() over a window partitioned by customer_id and ordered by updated_at descending, then keep only the rows numbered 1.
- A. Correct. A ranked window gives a deterministic winner per customer, so the newest snapshot is always the row kept.
- B. Incorrect. When a subset of columns is given,
drop_duplicateskeeps an arbitrary row per key and ignores any earlier sort order, so the newest row is not guaranteed. - C. Incorrect.
distinct()compares entire rows, and snapshots with different timestamps are never identical, so every row survives. - D. Incorrect. The aggregation returns only the grouping key and the maximum timestamp; the other feature columns are dropped unless the result is joined back.
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 | Rows in the result | Where NULLs come from |
|---|---|---|
| INNER JOIN (the default for bare JOIN) | One row for every matching pair; unmatched rows on either side are dropped | Only from NULLs already in the data |
| LEFT OUTER JOIN | Inner-join rows plus every unmatched o1 row | Columns from o2 on unmatched o1 rows |
| RIGHT OUTER JOIN | Inner-join rows plus every unmatched o2 row | Columns from o1 on unmatched o2 rows |
| FULL OUTER JOIN | Inner-join rows plus unmatched rows from both sides | Whichever side had no match |
| CROSS JOIN, or a join with no ON clause | Every o1 row paired with every o2 row | None 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.
A bare JOIN is an inner join, so it drops unmatched rows on both sides. LEFT OUTER adds back the unmatched left rows, with NULLs for the right side, and FULL OUTER adds back unmatched rows from both sides. If you leave out the ON clause, every row is paired with every other row.
“The result of the inner join is augmented with a row for each row of o1 that has no matches in o2.”Source: docs.snowflake.com
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)
Correct answers: C, D — Aggregate PAYMENTS to one row per order_id in a subquery or intermediate DataFrame, and only then join that result to ORDERS.; Calculate the order_total sum from ORDERS alone at customer grain, and join the payment-level aggregates to that result afterwards.
- A. Incorrect. A different join type does not change the one-to-many multiplication; matched orders are still repeated once per installment.
- B. Incorrect. Distinct sums remove legitimately equal totals from different orders, which understates spend and hides the real fan-out bug.
- C. Correct. Collapsing the many side to the order grain first removes the row multiplication that was repeating each
order_total. - D. Correct. Summing before the join means installment rows can no longer multiply the order amounts.
- E. Incorrect. Installment rows differ in their payment columns, so
distinct()finds no duplicates and the multiplied totals remain.
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?
A LEFT OUTER JOIN keeps every CUSTOMERS row and puts NULL in the TICKET_COUNTS columns when there is no match. COALESCE(ticket_count, 0) returns its first non-NULL argument, so only those NULLs become 0. Unmatched ticket rows would appear only with a RIGHT or FULL OUTER JOIN, and only an inner join drops unmatched customers.
“a row for each row of o1 that has no matches in o2. The result columns referencing o2 contain null.”Source: docs.snowflake.com
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.
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 ? ;Every SELECT item that is not an aggregate must be a grouping key, so p.product_ID has to appear in GROUP BY to get one row per product. profit is the alias of the SUM aggregate, so it cannot be a grouping key. Grouping by s.quantity or p.wholesale_price would leave p.product_ID ungrouped and change the grain of the result.
Source: docs.snowflake.com8.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.
| Method | What gets picked | Fixed-size (n ROWS) | Seed | When it wins |
|---|---|---|---|---|
| BERNOULLI / ROW (default) | Each row with probability p/100; expect about (p/100)*n rows | Supported | Not with n ROWS | Unbiased samples, especially from small tables |
| SYSTEM / BLOCK | Each block (usually a micro-partition) with probability p/100 | Not supported | SEED or REPEATABLE makes it deterministic | Speed on very large tables, where its bias is negligible |
| LIMIT n | The n rows that are fastest to return | Always n | Not applicable | Previewing 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.
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?
A seed makes a fraction-based SYSTEM/BLOCK sample repeat on an unchanged table. Snowflake rejects a seed on a fixed-size sample and on a subquery, so those two queries fail with an error. Without a seed, SAMPLE (10) returns different rows on each run.
“If a table doesn’t change, and the same seed and probability are specified, SAMPLE generates the same result.”Source: docs.snowflake.com
Sources12
Sources
(12)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Snowflake provides built-in system data metric functions to measure data quality for tables and views”
↩︎ Measuring data quality before you clean - 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.
“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.
“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.
“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.
“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.
“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.
“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.
“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.
“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.
“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.
“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