2: Data Preparation and Feature Engineering

    Prepare and clean data in Snowflake.

    Data preparation in Snowflake is the discipline of expressing every cleaning operation as set-based SQL or Snowpark DataFrame operations that compile to SQL and execute on a warehouse.

    The contrast that matters for the exam is not pandas-versus-Snowpark in the abstract; it is whether a pipeline pulls rows into a Python process or pushes a logical plan to the cluster.

    A candidate who answers a four-terabyte deduplication scenario with df.toPandas().drop_duplicates() has demonstrated the wrong mental model regardless of the pandas detail that follows.

    How it works

    The decision of whether to write SQL, Snowpark Python, or Snowpark pandas (the Modin-based API) depends on three factors: where the rest of the pipeline lives, whether the operation requires imperative branching, and which team owns the code.

    • SQL is the most direct path for stored procedures, dbt models, and pure transformation jobs.
    • Snowpark Python is preferred when the cleaning code shares a module with downstream model training because both compile against the same snowflake.snowpark.DataFrame object.
    • Snowpark pandas suits teams porting existing pandas notebooks; it accepts the pandas API but delegates evaluation to Snowpark internally.

    Identifying critical data and pruning irrelevant fields

    Profiling for relevance precedes cleaning.

    The cost driver in Snowflake is bytes scanned from micro-partitions, so dropping unused columns at the start of a pipeline reduces both warehouse seconds and downstream memory pressure.

    The reliable first step is to inspect INFORMATION_SCHEMA.COLUMNS and the table's column-level statistics via SHOW COLUMNS or DESCRIBE TABLE, then build the working DataFrame by explicit column projection rather than SELECT *.

    This pattern is also defensive: if upstream schema evolution adds a wide VARIANT column, an explicit projection does not change scan volume.

    USE DATABASE ML_LAB;
    USE SCHEMA RETAIL;
    
    SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COMMENT
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = 'RETAIL'
     AND TABLE_NAME = 'CUSTOMER_RAW'
    ORDER BY ORDINAL_POSITION;
    

    Critical-data identification at practitioner depth also relies on a hit-rate measurement:

    • count how often each column is non-null and non-default,
    • divide by the row count,
    • discard columns where the hit rate is below the threshold the downstream model can tolerate.

    A feature that is non-null for 0.4% of rows is rarely worth carrying through the pipeline; an imputer cannot fabricate signal that is not there.

    Aggregations and joins

    Aggregation work in Snowflake exposes the standard SQL set: SUM, COUNT, AVG, MIN, MAX, STDDEV, VARIANCE, MEDIAN, plus the approximation family discussed in the next section.

    Aggregations that fan out across groups should prefer GROUP BY ALL, which infers grouping keys from non-aggregated select-list columns and keeps the query shorter when the projection is stable.

    Aggregations consumed downstream by a model should always be materialized with explicit column aliases; ambiguous output names cause silent breakage when the Feature Store ingests the result.

    Comparison

    Joins for feature assembly fall into four classes the exam expects you to distinguish precisely.

    • Inner joins return only matching rows from both sides.
    • Outer joins (LEFT, RIGHT, FULL) preserve unmatched rows from one or both sides with NULL fill.
    • Anti joins (WHERE NOT EXISTS or LEFT JOIN ... WHERE right.key IS NULL) return rows from the left side that have no match on the right; the Snowflake-supported MINUS set operator is a related construct on whole rowsets.
    • Semi joins (WHERE EXISTS or IN (SELECT ...)) return rows from the left side that have at least one match on the right, without duplicating left rows when the right side has multiple matches; this is the correct construct for filtering features by a label set without inflating cardinality.
    -- Semi join: keep customers who appear in the label set, no row inflation
    SELECT C.*
    FROM CUSTOMER_FEATURES C
    WHERE EXISTS (
     SELECT 1 FROM CHURN_LABELS L WHERE L.CUSTOMER_ID = C.CUSTOMER_ID
    );
    
    -- Anti join: keep customers who are not in the label set
    SELECT C.*
    FROM CUSTOMER_FEATURES C
    LEFT JOIN CHURN_LABELS L
     ON L.CUSTOMER_ID = C.CUSTOMER_ID
    WHERE L.CUSTOMER_ID IS NULL;
    

    Removing duplicates

    Three deduplication patterns appear in real Snowflake pipelines, and the exam distinguishes them on correctness rather than performance. SELECT DISTINCT removes exact row duplicates and is appropriate only when every column in the row participates in the identity. GROUP BY with aggregates collapses duplicates by key while letting you choose how to combine the remaining columns (sum, first non-null, max timestamp). The pattern most commonly tested is QUALIFY ROW_NUMBER() OVER (PARTITION BY key ORDER BY tiebreaker) = 1, which keeps one row per natural key based on a deterministic tiebreaker.

    This third pattern is the only correct choice when duplicates differ on non-key columns (event timestamps, partial updates) and you need to keep the most recent record.

    SELECT *
    FROM CUSTOMER_RAW
    QUALIFY ROW_NUMBER() OVER (
     PARTITION BY CUSTOMER_ID
     ORDER BY EVENT_TIMESTAMP DESC, INGESTION_FILE_ROW_NUMBER DESC
    ) = 1;
    

    The Snowpark Python equivalent uses drop_duplicates for naive deduplication or composes a window with row_number() for tiebreaker logic.

    from snowflake.snowpark import Session, Window
    from snowflake.snowpark.functions import col, row_number
    
    session = Session.builder.configs(connection_params).create()
    
    raw = session.table("ML_LAB.RETAIL.CUSTOMER_RAW")
    
    dedup_window = Window.partition_by("CUSTOMER_ID").order_by(col("EVENT_TIMESTAMP").desc())
    
    clean = (
     raw
     .with_column("RN", row_number().over(dedup_window))
     .filter(col("RN") == 1)
     .drop("RN")
    )
    

    💡 Exam Trap: drop_duplicates in Snowpark, like SELECT DISTINCT in SQL, does not let you pick which row to keep when non-key columns differ. If the source has (CUSTOMER_ID, EMAIL_v1) and (CUSTOMER_ID, EMAIL_v2), both rows survive drop_duplicates(["CUSTOMER_ID", "EMAIL"]). Only the windowed ROW_NUMBER pattern produces a deterministic single-row-per-key result.

    Handling missing values

    Snowflake exposes a layered set of null-handling primitives, and the exam tests the distinctions.

    • IS NULL and IS NOT NULL are the only predicates that interact with NULL correctly.
    • Equality (= NULL) always returns NULL and therefore fails any filter.
    • COALESCE returns the first non-null argument from a variadic list and is the preferred form for multi-source fallback (try column A, fall back to column B, fall back to a literal).
    • NVL is a two-argument shorthand kept for portability.
    • IFNULL is identical in behavior to NVL.
    • ZEROIFNULL and NULLIFZERO are convenience wrappers for the common arithmetic case where zero and NULL must be distinguished or unified.

    Imputation strategy choice depends on column semantics.

    Numeric columns with missing-at-random gaps tolerate mean or median imputation; the Snowpark ML SimpleImputer exposes both.

    Categorical columns with a meaningful absence (no shipping address recorded) often deserve an explicit UNKNOWN sentinel rather than the mode.

    Timestamp columns rarely tolerate imputation at all; a missing event timestamp usually indicates the row should be filtered or routed to a quarantine table, because filling a fake date corrupts time-series features.

    from snowflake.ml.modeling.impute import SimpleImputer
    
    imputer = SimpleImputer(
     input_cols=["ANNUAL_INCOME", "CREDIT_SCORE"],
     output_cols=["ANNUAL_INCOME_IMPUTED", "CREDIT_SCORE_IMPUTED"],
     strategy="median",
    )
    
    imputer.fit(train_df)
    train_imputed = imputer.transform(train_df)
    test_imputed = imputer.transform(test_df)
    

    ⚠️ Anti-Pattern: Imputing across the entire training set before splitting into train and validation folds. The fold split must happen first, then the imputer fits on the training fold only and transforms both folds. Fitting on the full set leaks validation distribution information into the imputed values and biases evaluation metrics.

    Data type casting

    The casting choice in Snowflake is between CAST (and its :: shorthand) and TRY_CAST.

    The first raises a runtime error on conversion failure; the second returns NULL.

    For exploratory work on dirty data, TRY_CAST is the safe primitive because it surfaces conversion failures as NULLs that can be counted with SUM(CASE WHEN ... IS NULL THEN 1 ELSE 0 END), while CAST aborts the query at the first bad row and tells you nothing about the rest.

    Production loaders typically run TRY_CAST to a staging column, count failures, and only promote to CAST once the quarantine path is in place.

    Key points

    Type families to recognize: numeric (NUMBER, DECIMAL, INTEGER, FLOAT) text (VARCHAR, TEXT, STRING as aliases) boolean (BOOLEAN) temporal (DATE, TIME, TIMESTAMP_NTZ, TIMESTAMP_LTZ, TIMESTAMP_TZ) semi-structured (VARIANT, OBJECT, ARRAY) geospatial (GEOGRAPHY, GEOMETRY)

    The three TIMESTAMP variants differ in their treatment of time zones:

    • NTZ stores no zone
    • LTZ stores UTC and renders in session time zone
    • TZ stores the original zone with the value

    A model trained on TIMESTAMP_NTZ features that ingests TIMESTAMP_LTZ at scoring time will produce silently shifted feature values.

    SELECT
     TRY_CAST(BIRTH_DATE_STR AS DATE) AS BIRTH_DATE,
     TRY_CAST(SIGNUP_TIMESTAMP_STR AS TIMESTAMP_NTZ) AS SIGNUP_TS,
     TRY_CAST(LIFETIME_VALUE_STR AS NUMBER(12,2)) AS LTV,
     SUM(IFF(TRY_CAST(LIFETIME_VALUE_STR AS NUMBER(12,2)) IS NULL, 1, 0))
     OVER () AS BAD_LTV_COUNT
    FROM CUSTOMER_RAW;
    

    💡 Exam Trap: Implicit casts in Snowflake follow documented coercion rules and behave differently for string and numeric inputs. CAST('3.7' AS INTEGER) rounds to 4, while CAST(3.7 AS INTEGER) truncates to 3. The exam may present a question where the only correct answer is TRY_CAST to NUMBER(p,s) followed by an explicit ROUND or FLOOR, because the implicit behavior is inconsistent across input types.

    Sampling data

    Snowflake exposes sampling via the SAMPLE clause (alias TABLESAMPLE) with two distinct methods.

    • BERNOULLI (alias ROW) evaluates each row independently against the requested probability; the result is statistically uniform but reads every micro-partition.
    • SYSTEM (alias BLOCK) samples whole micro-partitions; the result is much faster but introduces clustering bias if the table is clustered on a column correlated with the sampled feature.

    The REPEATABLE keyword with a seed value makes the sample deterministic across runs, which the Feature Store requires for reproducible training datasets.

    -- Row-level Bernoulli sample, 10 percent, repeatable seed
    SELECT * FROM TRANSACTIONS SAMPLE BERNOULLI (10) REPEATABLE (42);
    
    -- Block sample, 10 percent, repeatable seed
    SELECT * FROM TRANSACTIONS SAMPLE SYSTEM (10) REPEATABLE (42);
    
    -- Bernoulli fixed row count
    SELECT * FROM TRANSACTIONS SAMPLE BERNOULLI (1000 ROWS);
    

    Stratified sampling is not a single keyword; it is composed with QUALIFY and ROW_NUMBER per stratum, or by sampling each stratum independently and unioning the results. For a churn dataset where positives are rare, the correct pattern samples 100% of positives and a Bernoulli fraction of negatives, then weights or downsamples to the target ratio.

    📊 Limit: The fixed-row-count form (SAMPLE (n ROWS)) is supported only for BERNOULLI, not for SYSTEM. SYSTEM accepts only a probability.

    ⚠️ Anti-Pattern: Using SYSTEM sampling on a small or highly clustered table for statistical estimation. The result can omit entire ranges of the clustering key. SYSTEM is appropriate only when the table is large, well-distributed, and the use case tolerates partition-level bias (debugging queries on petabyte tables, for example).

    Decision rule: Choose BERNOULLI when you need statistical fidelity and the sample feeds a model. Choose SYSTEM when you need a fast partition-level peek at a multi-terabyte table and partition-level bias is acceptable.

    🎯 Scenario: A team has a 12 TB TRANSACTIONS table clustered on TRANSACTION_DATE. They run SAMPLE SYSTEM (1) to get a quick feature distribution and observe that 80% of sampled rows fall in a single month. The diagnosis: SYSTEM sampled whole micro-partitions, and because the table is date-clustered, each micro-partition skews to one month. The fix is to switch to SAMPLE BERNOULLI (1) REPEATABLE (n) for statistical work, accepting the longer scan, and to reserve SYSTEM for sanity-check inspections where the date bias is irrelevant.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Snowflake - SnowPro Advanced Data Scientist learning hub.