CertSafari
    Snowflake SnowPro Advanced: Data Analyst (DAA-C01)· Lessons

    Domain 2 · Lesson 9/19

    Cleaning data in Snowflake: duplicates, NULLs, type conversion and safe rollback

    Given a dataset, clean the data.

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

    What you will be able to do

    • Remove duplicates by key with QUALIFY ROW_NUMBER() and rebuild a clean table
    • Fill NULLs with COALESCE without distorting aggregates such as AVG
    • Convert text to native types with TO_DATE and turn bad values into NULL with TRY_TO_DATE
    • Extract and convert values from VARIANT paths during cleaning
    • Protect a cleanup with a clone, Time Travel and UNDROP, and know how DATA_RETENTION_TIME_IN_DAYS limits recovery

    1.Removing duplicates by key with QUALIFY

    Duplicate rows show up whenever the same file or event stream is loaded twice. Snowflake will not stop them, even if a primary key is declared, as explained in Declared vs enforced constraints. Finding and removing them is the cleaning job's responsibility. The DUPLICATE_COUNT DMF tells you that a key column has repeats. Getting rid of them means picking one survivor per key.

    The standard pattern numbers the rows inside each key and keeps the first. ROW_NUMBER() partitions by the column that defines "the same record" and orders each partition so the row you want comes first. QUALIFY then filters on that number directly, with no nested subquery; the clause itself is covered in WHERE vs HAVING vs QUALIFY. In the sample below, p is the key and o decides which row wins.

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

    For repeated loads, the key is the business identifier (event_id) and the ordering is load time descending (ORDER BY loaded_at DESC), so row 1 is the most recent copy. Put the query inside CREATE TABLE events_clean AS SELECT ... and you have rebuilt a deduplicated table in one statement, without a self-join. Each part of the window matters. Partition by loaded_at instead and you group rows by arrival time, not by event. Drop DESC and you keep the oldest copy.

    The other common shapes fail for structural reasons. GROUP BY event_id returns one row per group, but you want the whole winning row, and getting the other columns back usually means joining to the original table. SELECT DISTINCT * only merges rows that are identical in every column, so two loads of one event with different loaded_at values both survive. A final ORDER BY ... LIMIT caps the size of the whole result, not the number of rows per key.

    A rebuilt table should be verified by a measurement, not by eye. A data metric function (DMF) measures one attribute of a column, such as how many NULLs or repeats it holds, and returns a number without judging it. An expectation, written EXPECTATION ( VALUE = 0 ), compares that number to a rule and reports pass or fail. The DMF together with its column and expectation is a binding, and for a freshly deduplicated key the rule is zero repeats.

    Four measures look related but answer different questions. DUPLICATE_COUNT counts values that have duplicates and includes NULL, so repeated NULL keys are caught. DUPLICATE_PERCENT is a percentage of non-NULL rows only, so repeated NULL keys never raise it. UNIQUE_COUNT counts the unique non-NULL values in the column, which says nothing about repeats. ROW_COUNT counts the records in the table or view and takes no column at all. Only the first of the four can confirm a key with no repeats of any kind.

    Checkpoint 1 of 8· Check yourself

    A table that was loaded twice is rebuilt as events_clean with QUALIFY ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY loaded_at DESC) = 1. You want a check on events_clean that confirms no event_id value repeats, NULL keys included. Which binding does that?

    Checkpoint 2 of 8· Exam question

    An analyst loads the same events repeatedly into customer_events. Rows sharing an event_id are duplicates, and only the most recently loaded row per event_id must land in a new table, without a self-join. Which statement does this?

    Sources1234

    2.Filling NULLs without distorting aggregates

    A NULL means "no value recorded". Most aggregate functions skip NULLs, so whether you fill them changes the answer. COALESCE returns the first non-NULL argument, so COALESCE(discount_pct, 0) replaces every missing discount with zero. That is right when a missing value really means zero and wrong when it means unknown.

    AVG averages only the non-NULL records. A NULL is not quietly treated as zero, and a single NULL does not turn the result into NULL. AVG returns NULL only when every value in the group is NULL. So to get "the average among rows where a discount was recorded", plain AVG(discount_pct) is already the right answer. Wrapping the column in COALESCE(..., 0) adds a zero for each missing row, which makes the denominator larger and pulls the average down.

    Rows with NULLs in several columns follow different rules. COUNT(x, y) skips any row where either column is NULL, and SUM(x + y) skips rows where the expression evaluates to NULL. GROUP BY keeps those rows and gives NULL its own group. When a profile count looks wrong, check which of these rules applied. If you fill NULLs with COALESCE, pass arguments of the same type: Snowflake implicitly converts mixed arguments, and the conversion fails when a value cannot be converted.

    Checkpoint 3 of 8· Check yourself

    In discount_pct, NULL means 'not recorded'. A pipeline loads COALESCE(discount_pct, 0) into the reporting table. On that table, discount_pct has a SNOWFLAKE.CORE.NULL_COUNT check with EXPECTATION ( VALUE = 0 ). What is the result?

    Checkpoint 4 of 8· Exam question

    A sales table stores NULL in discount_pct when no discount was recorded. The analyst needs the average discount among rows where one was recorded, but a teammate suggests wrapping the column in COALESCE(discount_pct, 0) before calling AVG. What would that change do?

    Sources56

    3.Converting text to native types with TO_ and TRY_ functions

    Staging tables often load every column as VARCHAR so that no file is ever rejected. The cleaning step then has to move the values into native types such as DATE and NUMBER so they sort, compare and aggregate correctly. Relying on implicit conversion is fragile. AVG on a VARCHAR column implicitly casts to floating point, and if any value cannot be cast an error is returned. COALESCE('foo', 1) fails the same way. One bad string out of a million stops the whole statement.

    TO_DATE(order_date, 'YYYY-MM-DD') converts explicitly, with a format that says how to read the string. Without a format, the session's DATE_INPUT_FORMAT applies, and its default is AUTO. TO_DATE is strict: given 'TBD' or '31/02/2026', it raises an error and the INSERT fails. **TRY_TO_DATE** is the error-handling version of the same function. It takes the same arguments and returns a DATE, but returns NULL when the conversion cannot be performed. A cast with ::DATE gives no such protection.

    For mixed-quality staging data, TRY_TO_DATE(order_date, 'YYYY-MM-DD') loads every good value and leaves NULL wherever the input was unusable. Afterwards, rows where the source string was not NULL but the converted date is NULL are exactly the ones to review. Stripping out one known bad token first, for example turning 'TBD' into NULL, does not make strict TO_DATE safe. The next unexpected value, such as '31/02/2026', still fails the statement. To size the problem before converting, the INVALID_TIMESTAMP_STRING_COUNT and INVALID_NUMERIC_TYPE_CAST_COUNT DMFs count the strings that will not convert.

    A third DMF, INVALID_ISO8601_FORMAT_COUNT, counts the non-NULL strings in a column that are not laid out as an ISO 8601 date or timestamp. It inspects only the shape of the text, never whether the value is a real date. 2026-13-45 has a valid ISO 8601 layout, so that DMF does not count it, yet no month 13 exists and it cannot be parsed, so INVALID_TIMESTAMP_STRING_COUNT does. A column can therefore show zero layout problems and still hold values that make a strict conversion fail.

    Checkpoint 5 of 8· Check yourself

    Profiling a VARCHAR staging column order_date shows INVALID_ISO8601_FORMAT_COUNT = 0 and INVALID_TIMESTAMP_STRING_COUNT = 3. The load step runs INSERT ... SELECT TO_DATE(order_date, 'YYYY-MM-DD'). What happens?

    Checkpoint 6 of 8· Exam question

    Daily CSV files land in an all-VARCHAR staging table stg_orders. The order_date column holds values such as '2026-03-14', but also 'TBD' and '31/02/2026'. The analyst must fill a DATE column, turning unparseable values into NULL for later review without failing the INSERT. Which expression should be used?

    Sources783

    4.Cleaning values inside semi-structured data

    JSON, Avro, ORC and Parquet data usually lands in a VARIANT column, and cleaning it starts with reaching the right element. Use dot notation, src:salesperson.name, or bracket notation, src['salesperson']['name']. The column name is case-insensitive, but element names are case-sensitive: src:salesperson.name and SRC:salesperson.name are the same path, while SRC:Salesperson.Name is a different one. A key with a misspelled case is a quiet data quality bug. An element name that is not a valid SQL identifier, such as one containing a space, must be wrapped in double quotes: src:"company name".

    The examples here query a table named car_sales with a single VARIANT column named src. Each row holds one JSON document like the record below. salesperson is a nested object. customer and vehicle are arrays, marked by square brackets, and an array can hold more than one element; the extras array inside the vehicle holds two strings in this record.

    One car_sales record as loaded into the src columnjson
    {
        "date" : "2017-04-28",
        "dealership" : "Valley View Auto Sales",
        "salesperson" : {
          "id": "55",
          "name": "Frank Beasley"
        },
        "customer" : [
          {"name": "Joyce Ridgely", "phone": "16504378889", "address": "San Francisco, CA"}
        ],
        "vehicle" : [
          {"make": "Honda", "model": "Civic", "year": "2017", "price": "20275", "extras":["ext warranty", "paint protection"]}
        ]
    }
    Traversing a path inside a VARIANT columnsql
    SELECT src:salesperson.name
        FROM car_sales
        ORDER BY 1;

    The values that come back are still JSON, and they are not always the type the business means. In the car_sales sample, "price": "20275" and "year": "2017" are stored as strings. Before you sum prices or compare years, convert the extracted value to a native NUMBER or DATE with the TO_ and TRY_ functions from the previous section, so a malformed element becomes NULL rather than an error. Arrays such as vehicle and extras hold several elements per row. Expand them with LATERAL FLATTEN to find bad or duplicate elements, deduplicate them with the QUALIFY pattern above, and then rebuild clean rows.

    Checkpoint 7 of 8· Check yourself

    Every car_sales row stores the salesperson under the lowercase JSON key "salesperson" with a lowercase "name" inside it. Which rewrite of src:salesperson.name is guaranteed to reach the same element?

    Sources9

    5.Cleaning safely with zero-copy clones and Time Travel

    DELETEs, UPDATEs and CREATE OR REPLACE rebuilds are destructive, so make them reversible before you run them. The cheapest safeguard is a zero-copy clone. When it is created, the clone shares the source's existing micro-partitions instead of copying them, and storage diverges only as either side changes. Clone the table, run the cleanup on the clone, compare, then swap. The clone also inherits the source's DMF bindings, so the same quality checks run against your trial version.

    Time Travel keeps the previous state of changed or deleted data for the retention period, so a cleanup that went wrong can be inspected and undone. Within that period you can:

    • query data as it was before the change, with AT | BEFORE in a SELECT
    • clone a table, schema or database as it was at or before a point in the past
    • restore a dropped table, schema or database with UNDROP

    The AT | BEFORE clause takes TIMESTAMP, OFFSET (seconds back from now) or STATEMENT (a query ID). BEFORE(STATEMENT => ...) points to the state just before your bad DELETE. Historical queries return data in the table's current schema.

    Cloning an object as it existed at a past timestampsql
    CREATE SCHEMA S2 CLONE S1 AT(TIMESTAMP => '2025-04-01 12:00:00');

    How far back you can go is set by the **DATA_RETENTION_TIME_IN_DAYS** object parameter. Each change gets its own window: the end of Time Travel is the time of the change plus the retention period. After that, the old version moves into Fail-safe for 7 days, and only Snowflake can recover it.

    Time Travel retention by edition and object type
    Edition and objectRetention you can set
    Standard Edition, any object0 or the default of 1 day
    Enterprise and higher, permanent databases, schemas and tables0 up to 90 days
    Enterprise and higher, transient or temporary objects0 or the default of 1 day

    A retention of 0 turns Time Travel off for that object. If a table with 0 retention is dropped, it cannot be restored. One exception: an account-level MIN_DATA_RETENTION_TIME_IN_DAYS takes precedence when it is higher. Check the setting with the retention_time column of SHOW TABLES before relying on it. Keep at least 1 day on any table you are about to clean.

    Checkpoint 8 of 8· Check yourself

    On an Enterprise account with no MIN_DATA_RETENTION_TIME_IN_DAYS set, a permanent table was given DATA_RETENTION_TIME_IN_DAYS = 0 to save storage. During a cleanup, someone drops it by mistake. What can the team do?

    Sources101112

    Sources

    (12)

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

    1. 1.
      “The QUALIFY clause simplifies queries that require filtering on the result of window functions.”
      ↩︎ Removing duplicates by key with QUALIFY
    2. 2.
      “GROUP BY produces one output row per group, while PARTITION BY produces one output row per input row.”
      ↩︎ Removing duplicates by key with QUALIFY
      “GROUP BY produces one output row per group, while PARTITION BY produces one output row per input row.”
      ↩︎ Exam trap 3
    3. 3.
      “Determine the number of duplicate values in a column, including NULL values.”
      ↩︎ Removing duplicates by key with QUALIFY
      “Determine what percentage of non-NULL rows have a value that occurs more than once.”
      ↩︎ Removing duplicates by key with QUALIFY
      “Determine the number of unique, non-NULL values in a column.”
      ↩︎ Removing duplicates by key with QUALIFY
      “Determine how many records are in the table or view.”
      ↩︎ Removing duplicates by key with QUALIFY
      “Determine how many non-NULL values in a string column are not in ISO 8601 layout.”
      ↩︎ Converting text to native types with TO_ and TRY_ functions
      “2026-13-45 has a valid ISO 8601 layout but can’t be parsed.”
      ↩︎ Converting text to native types with TO_ and TRY_ functions
      “Determine how many NULL values are in a column.”
      ↩︎ Checkpoint
      “INVALID_ISO8601_FORMAT_COUNT checks only the layout of a value, and INVALID_TIMESTAMP_STRING_COUNT checks whether the value can be parsed as a timestamp.”
      ↩︎ Checkpoint
    4. 4.
      “A DMF measures an attribute of your data such as how many NULL values exist in a column”
      ↩︎ Removing duplicates by key with QUALIFY
      “An expectation is combined with a DMF to create a data quality check.”
      ↩︎ Removing duplicates by key with QUALIFY
    5. 5.
      “Returns the first non-NULL expression among its arguments, or NULL if all its arguments are NULL.”
      ↩︎ Filling NULLs without distorting aggregates
      “We recommend passing in arguments of the same type or explicitly converting arguments if needed.”
      ↩︎ Filling NULLs without distorting aggregates
    6. 6.
      “If all of the values passed to the aggregate function are NULL, then the aggregate function returns NULL.”
      ↩︎ Filling NULLs without distorting aggregates
      “In these instances, the aggregate function ignores a row if any individual column is NULL.”
      ↩︎ Filling NULLs without distorting aggregates
      “This behavior differs from the behavior of GROUP BY, which does not discard rows when some columns are NULL”
      ↩︎ Filling NULLs without distorting aggregates
      “In both the numerator and the denominator, only the two non-NULL values are used.”
      ↩︎ Prediction
    7. 7.
      “When passed a VARCHAR expression, this function implicitly casts the input to floating point values.”
      ↩︎ Converting text to native types with TO_ and TRY_ functions
      “If the cast cannot be performed, an error is returned.”
      ↩︎ Converting text to native types with TO_ and TRY_ functions
      “Returns the average of non-NULL records.”
      ↩︎ Exam trap 1
    8. 8.
      “A special version of the TO_DATE function that performs the same operation”
      ↩︎ Converting text to native types with TO_ and TRY_ functions
      “if the conversion cannot be performed, it returns a NULL value instead of raising an error”
      ↩︎ Converting text to native types with TO_ and TRY_ functions
      “The default is the current value of the DATE_INPUT_FORMAT session parameter (default AUTO).”
      ↩︎ Converting text to native types with TO_ and TRY_ functions
    9. 9.
      “the column name is case-insensitive but element names are case-sensitive.”
      ↩︎ Cleaning values inside semi-structured data
      “then you must enclose the name in double quotes”
      ↩︎ Cleaning values inside semi-structured data
      “the first two paths are equivalent, but the third is not”
      ↩︎ Cleaning values inside semi-structured data
      “a table named car_sales that contains a single VARIANT column named src”
      ↩︎ Cleaning values inside semi-structured data
    10. 10.
      “At clone time, the source and clone share existing micro-partitions through zero-copy cloning.”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
    11. 11.
      “CLONE: The cloned object inherits DMF bindings from the source.”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
    12. 12.
      “Create clones of entire tables, schemas, and databases at or before specific points in the past.”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “TIMESTAMP OFFSET (time difference in seconds from the present time) STATEMENT (query ID for statement)”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “UNDROP <object> command for tables, schemas, databases, accounts, external volumes, and tags.”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “When querying historical data in a table or non-materialized view, the current table or view schema is used.”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “The standard retention period is 1 day (24 hours) and is automatically enabled for all Snowflake accounts”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “For permanent databases, schemas, and tables, the retention period can be set to any value from 0 up to 90 days.”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “End of Time Travel = time of the change + data retention period”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “During that time, only Snowflake can recover it.”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “When an object with no retention period is dropped, you will not be able to restore the object.”
      ↩︎ Cleaning safely with zero-copy clones and Time Travel
      “When an object with no retention period is dropped, you will not be able to restore the object.”
      ↩︎ Exam trap 2

    Ready to test yourself?

    Practise the 17 questions on this subdomain.

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