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

    Domain 3 · Lesson 15/19

    Diagnostic analysis in Snowflake: trends, CORR, anomaly detection and Top Insights

    Perform diagnostic analyses.

    22 min read
    8% of exam
    5 sources
    Published 20 Oct 2026
    Docs as of 4 Oct 2026

    What you will be able to do

    • Downsample raw events with DATE_TRUNC so a trend or a break in it becomes visible
    • Measure the linear relationship between two metrics with CORR and say what the coefficient cannot tell you
    • Train a SNOWFLAKE.ML.ANOMALY_DETECTION model, call DETECT_ANOMALIES and read IS_ANOMALY against the bounds
    • Decide which related data to bring in, such as exogenous variables or extra columns, to explain an anomaly
    • Build a control/test label for SNOWFLAKE.ML.TOP_INSIGHTS, read CONTRIBUTION, RELATIVE_CONTRIBUTION and GROWTH_RATE, and size the warehouse for the run

    Key concept

    Baseline comparison — Diagnostic analysis explains a change by holding the data up against a baseline. Anomaly detection compares actual values with a forecast built from history. Top Insights compares a test group (the period or population being explained) with a control group (the reference), segment by segment.

    Diagnosis starts by asking whether something changed, and you can't answer that from raw events. A sensor that reports every second, or a point-of-sale table with hundreds of millions of orders, gives you a series so dense that the trend disappears into noise. Downsampling rolls fine-grained records up to a coarser period, such as an hour, a day or a week, and computes one aggregate per period. The result is smaller, cheaper to query, and much easier to read.

    DATE_TRUNC('day', order_ts) cuts a timestamp down to the start of its day, so every order from that day lands in one group. Add GROUP BY on the truncated value plus the dimensions you want to keep, then aggregate the measure with AVG or SUM. In the Tasty Bytes example below, the dimensions are truck and location. Run without its date filter and LIMIT, the same query turns 248 million order rows into roughly half a million daily rows. TIME_SLICE does the same job with fixed-width buckets, such as 1-minute or 15-minute slices, that DATE_TRUNC can't express.

    Rolling orders up to one row per day, truck and location with DATE_TRUNCsql
    SELECT DATE_TRUNC('day', order_ts)::date sliced_ts, truck_id, location_id, AVG(order_amount)::NUMBER(4,2) as avg_amount
      FROM order_header
      WHERE EXTRACT(YEAR FROM order_ts)='2022'
      GROUP BY date_trunc('day', order_ts), truck_id, location_id
      ORDER BY 1, 2, 3 LIMIT 25;

    Downsampling also gets data ready for the ML functions later in this lesson. Their training data has to sit on a regular time grid, and truncating timestamps removes irregular arrival times. It also lines up two series with different granularities: a sensor that reports every 15 seconds and one that reports every 30 seconds can both be averaged into 1-minute buckets. Once the series is on a daily grid, a moving average or a LAG-based day-over-day delta shows where the trend bends. Those are window-function techniques covered in Window functions, frames and ranking.

    Checkpoint 1 of 9· Fill the gap

    This query should cut 248 million Tasty Bytes orders down to one average order amount per truck, per location, per business day. Which date part belongs in the blank?

    SELECT DATE_TRUNC( ? , order_ts)::date sliced_ts, truck_id, location_id, AVG(order_amount)::NUMBER(4,2) as avg_amount
      FROM order_header
      WHERE EXTRACT(YEAR FROM order_ts)='2022'
      GROUP BY date_trunc('day', order_ts), truck_id, location_id
      ORDER BY 1, 2, 3 LIMIT 25;

    Sources1

    2.Flagging outliers with SNOWFLAKE.ML.ANOMALY_DETECTION

    An anomaly is a point outside the range the model expected, so the model has to build an expectation first. For the period you're checking, SNOWFLAKE.ML.ANOMALY_DETECTION forecasts what the series should have done, then compares each actual value with that forecast. The prediction interval around the forecast is the boundary. Any value outside it gets IS_ANOMALY = True. Uses include pinpointing the day a logging pipeline started failing, or the days compute costs ran higher than expected.

    The model follows the train-then-call pattern described in Train-then-call model objects (CREATE SNOWFLAKE.ML.…): a CREATE statement trains and stores a schema-level object, and a method call applies it. You pass training data as a reference (TABLE(...), SYSTEM$REFERENCE or a query reference) and name the timestamp and target columns. The data needs a timestamp column and a target column. If you have no labels, pass LABEL_COLNAME => '' to train unsupervised.

    Training an unsupervised anomaly detection model on a sensor viewsql
    CREATE OR REPLACE SNOWFLAKE.ML.ANOMALY_DETECTION sensor_model(
      INPUT_DATA => SYSTEM$REFERENCE('VIEW', 'sensor_data_view'),
      TIMESTAMP_COLNAME => 'timestamp',
      TARGET_COLNAME => 'temperature',
      LABEL_COLNAME => '');

    DETECT_ANOMALIES returns one row per test timestamp. To read a row, compare the actual value Y with LOWER_BOUND and UPPER_BOUND. FORECAST is the expected value, and PERCENTILE and DISTANCE show how far into the tail the point sits. In the sensor test below, 36.0422 exceeds an upper bound of 36.0368, so it's flagged. The next reading is slightly higher at 36.1519, but it isn't flagged, because the forecast moved up and its upper bound rose to 37.79. A fixed threshold would have flagged both readings.

    Reading DETECT_ANOMALIES output: the flag depends on each row's own bounds
    TSYFORECASTLOWER_BOUNDUPPER_BOUNDIS_ANOMALY
    2024-03-01 00:00:3036.042230.8125.5836.04True
    2024-03-01 00:00:3136.151932.5627.3337.79False
    2024-03-01 00:00:3236.152432.2126.9837.43False

    You set sensitivity when you call the model, not when you train it. You pass a CONFIG_OBJECT with a prediction_interval between 0 and 1. The default of 0.99 marks roughly 1% of observations as anomalies. A higher value marks fewer, and a lower value marks more.

    Calling a labeled model with a stricter prediction intervalsql
    CALL model_trained_with_labeled_data!DETECT_ANOMALIES(
      INPUT_DATA => TABLE(view_with_data_to_analyze),
      TIMESTAMP_COLNAME => 'date',
      TARGET_COLNAME => 'sales',
      CONFIG_OBJECT => {'prediction_interval':0.995}
    );

    Training data decides how good the result is, and a few rules catch people out. The model can only flag anomalies in the test data, never in its own training rows, and every test timestamp must come after the training data without a huge gap. A spike left in the training data inflates the forecast and widens the interval. In the jacket example, one 30-unit sales day was enough to hide a real anomaly. To avoid this, train on a period free of outliers, or add a Boolean label column that marks known anomalies (supervised training). Data volume matters too: 2 rows train a model, 2–11 rows per series give only a naive forecast (the last value repeated), 12 rows give non-naive results, and 60 rows are needed for non-linear results.

    A trained model is frozen. You can't append new history to it, it has no versions, and to update it you drop it and train a new one. Plan a retraining cadence (daily, weekly or monthly) that matches how often new data arrives. That way the baseline keeps up with the trend and doesn't flag ordinary growth as an anomaly.

    Checkpoint 2 of 9· Check yourself

    An analyst needs to find which days in 2023 had anomalous jacket sales. 2023 includes a known one-day spike from a promotion. Which plan gives a usable answer?

    Checkpoint 3 of 9· Check yourself

    New sales history arrives every week, and the anomaly detection model has started flagging ordinary growth as anomalous. How do you bring its baseline up to date?

    Sources2

    A flagged point tells you when something happened, not why. To find the cause you have to bring in data the target column doesn't contain. Start from the business question and choose the event tables, dimensions and external datasets that could plausibly move the metric. That selection step is profiling, covered in Profiling the elements a business goal needs. For an anomaly, the useful candidates are things that change over time: promotions, outages, weather, and calendar events.

    Anomaly detection can use this context directly as exogenous variables. Add the extra columns to the training view and to the test view, and the model picks them up without any further argument. They can be numerical or categorical, high-cardinality categories work because the algorithm doesn't one-hot encode them, and rows with NULL exogenous values are kept. There's one catch. If you train with exogenous columns, you have to supply those columns for the test timestamps too. A weather feature only helps if the weather for the period you're scoring is already in Snowflake.

    Sometimes you want context, not a feature: what was the other series doing just before the spike? An ASOF JOIN pairs each flagged timestamp with the latest earlier row from another time series, such as the deployment log entry or the price change that came right before the anomaly. That gives you a short list of candidate causes to check.

    Checkpoint 4 of 9· Check yourself

    To explain a Saturday spike in daily orders, you retrain the anomaly detection model with two added columns: rainfall (numeric) and campaign_id (a category with thousands of values). What else must be true before DETECT_ANOMALIES can score the new week?

    Sources2

    4.Measuring relationships between metrics with CORR

    Once you have candidate drivers, CORR(y, x) measures how closely two metrics move together in a straight line. It returns a coefficient between −1 and 1, computed as COVAR_POP(y, x) / (STDDEV_POP(x) * STDDEV_POP(y)). It works as an aggregate with GROUP BY, or as a window function with PARTITION BY. In window form, ORDER BY inside the OVER clause and explicit frames aren't supported, so it can't produce a rolling correlation.

    CORR per group: group 1 has no complete pair, so it returns NULLsql
    SELECT k, CORR(v, v2) FROM aggr GROUP BY k;
    
    +---+--------------+
    | K |  CORR(V, V2) |
    |---+--------------|
    | 1 |         NULL |
    | 2 | 0.9988445981 |
    +---+--------------+

    Only non-null pairs count. In the example, group 2 has four rows, but the row with a NULL v2 is dropped, so 0.9988 comes from three pairs. Group 1's only row has a NULL, so its result is NULL rather than zero. Before you trust a coefficient, check how many complete pairs produced it. A strong-looking value built from three points is fragile.

    The formula itself shows two limits. First, covariance and standard deviation are symmetric in x and y, so swapping the arguments gives the same number. A high correlation between ad spend and sales can't tell you which one drives the other, or whether a third factor such as a holiday drives both. Second, the formula uses means and squared deviations, so one extreme point can pull the coefficient a long way. Outliers have an outsized effect on statistics like this. Exclude the anomalies you've already flagged before you calculate correlation on the rest of the series.

    Checkpoint 5 of 9· Check yourself

    Over the past year, CORR(daily_sales, ad_spend) comes out at 0.92. Anomaly detection has already flagged three days in that year, including one promotion day when both metrics spiked. Before you report the relationship, what should you do?

    Sources32

    5.Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS

    Revenue fell 12% this month, but which customers, regions or products drove the drop? SNOWFLAKE.ML.TOP_INSIGHTS answers this through key driver analysis. A decision tree splits the data into segments that behave differently with respect to the metric, then compares each segment's value in a control group with its value in a test group. It returns the significant, distinct segments and leaves out redundant ones. It's most useful when there are too many dimensions to search by hand.

    The comparison is defined entirely by one Boolean label column. Rows labeled FALSE are the control, or baseline. Rows labeled TRUE are the test group, the data you're trying to explain. For a time-series question, derive the label from the date: this month TRUE, the previous month FALSE. For a vertical or demographic question, derive it from a population attribute, for example dim_country <> 'USA', to see which user segments explain the difference between non-US and US growth. The label is only ever this TRUE/FALSE split. It isn't a segment name, a revenue quartile or an outlier flag, because segments come from the other columns.

    A view that labels the latest month as test (TRUE) and earlier rows as control (FALSE)sql
    CREATE VIEW input_table_time_series_label (
      ds, metric, dim_country, dim_vertical, label ) AS
      SELECT
        ds,
        metric,
        dim_country,
        dim_vertical,
        ds >= dateadd(month, -1, current_date) AS label
      FROM input_table;

    Unlike anomaly detection, a Top Insights instance holds no state. You create it once with no arguments, and you need the CREATE SNOWFLAKE.ML.TOP_INSIGHTS privilege on the schema to do so. Then you call GET_DRIVERS with the input reference, the label column and the metric column. The metric is a single FLOAT column. Every other column in the input is treated as a dimension, so use the view to drop columns that shouldn't be considered.

    Creating a Top Insights instance and calling GET_DRIVERSsql
    CREATE OR REPLACE SNOWFLAKE.ML.TOP_INSIGHTS my_insights_model();
    
    CALL my_insights_model!GET_DRIVERS(
      INPUT_DATA => TABLE(input_view),
      LABEL_COLNAME => 'label',
      METRIC_COLNAME => 'metric'
    );

    Data type decides dimension type, and you don't specify it anywhere else. Numeric columns are continuous, which suits temperature or attendance, and the tree splits them into ranges. Strings and Booleans are categorical. An ID stored as a number therefore comes back as a range unless you cast it to a string in the input query. Results can also include negated conditions such as "not COUNTRY = usa". For a categorical column with more than 25 values, only the 25 most influential values become segments.

    Each output row describes one segment in its CONTRIBUTOR array. Rows are ordered by CONTRIBUTION, and an Overall row always comes first. METRIC_CONTROL and METRIC_TEST are the segment's totals in each group. CONTRIBUTION is the segment's absolute impact on the change, in metric units. RELATIVE_CONTRIBUTION is that impact as a share of the overall change, so Overall is always 1. GROWTH_RATE is the segment's own change divided by its own control value. All three can be negative, and they don't have to share a sign with each other.

    Reading GET_DRIVERS output from the time-series example
    CONTRIBUTORMETRIC_CONTROLMETRIC_TESTCONTRIBUTIONRELATIVE_CONTRIBUTIONGROWTH_RATE
    ["Overall"]1284451584563001110.234
    ["COUNTRY = usa"]116238154574383361.2770.330
    ["COUNTRY = usa","VERTICAL = tech"]1543503-1040-0.035-0.674
    ["not COUNTRY = usa"]122073882-8325-0.277-0.682

    The two contribution columns answer different questions. The US segment's relative contribution of 1.277 means it added more than the whole net change, and the non-US segments' losses offset the difference. US tech shrank by 67% on its own base, but at −1,040 units it barely affects the total. The reverse is also possible. When the overall change is small, a segment that moves only a few units can still have a large RELATIVE_CONTRIBUTION, because it accounts for a big share of a small change. Use CONTRIBUTION to rank by magnitude and RELATIVE_CONTRIBUTION to see share.

    Size the warehouse for memory, not speed. Runtime grows with the number of rows, the number of dimensions and their cardinality, and all the data must fit in memory. Above about 1,000,000 rows and 1,000 columns, a run can exhaust memory. Moving to a bigger standard warehouse usually doesn't help. Use a Snowpark-optimized warehouse, which has more memory than a standard warehouse of the same size. Instances store no data, so their storage cost is negligible.

    Checkpoint 6 of 9· Fill the gap

    You want GET_DRIVERS to explain what changed in the most recent month compared with all earlier months. Which operator belongs in the blank so the label column marks the right rows as the test group?

    CREATE VIEW input_table_time_series_label (
      ds, metric, dim_country, dim_vertical, label ) AS
      SELECT
        ds,
        metric,
        dim_country,
        dim_vertical,
        ds  ?  dateadd(month, -1, current_date) AS label
      FROM input_table;

    Checkpoint 7 of 9· Exam question

    Revenue per order fell 12% in March compared with February. An analyst wants Snowflake to rank which customer segments contributed most to the change using SNOWFLAKE.ML.TOP_INSIGHTS. How should the LABEL_COLNAME column be populated in the input data?

    Checkpoint 8 of 9· Exam question

    An analyst runs GET_DRIVERS on a table where store_id is stored as a NUMBER. The output never lists individual stores as contributors, only numeric ranges. What change makes TOP_INSIGHTS treat each store as a distinct segment?

    Checkpoint 9 of 9· Exam question

    A TOP_INSIGHTS result shows a segment with a large RELATIVE_CONTRIBUTION but a small CONTRIBUTION. Which interpretation is correct? Select TWO of the five that apply to reading the output.(Select 2)

    0 of 2 selected

    Sources45

    Practise it for real

    Train a small anomaly detection model on synthetic sensor data, score three later readings, and see how the prediction interval changes what gets flagged.

    1. 1.Create sensor_data_30_rows, load 30 one-second readings for DEVICE3 with GENERATOR and UNIFORM, and create sensor_data_view on top of it.

      Why: Using a view as the training input lets you retrain later on different row counts without changing the source table.

      You should see: A table with 30 rows timestamped 2024-03-01 00:00:00 to 00:00:29, with temperatures between about 30.2 and 36.3.

    2. 2.Run CREATE OR REPLACE SNOWFLAKE.ML.ANOMALY_DETECTION sensor_model with INPUT_DATA => SYSTEM$REFERENCE('VIEW', 'sensor_data_view'), TIMESTAMP_COLNAME => 'timestamp', TARGET_COLNAME => 'temperature', LABEL_COLNAME => ''.

      Why: Creating the object trains the model. The empty label column name makes training unsupervised.

      You should see: A status row reading 'Instance SENSOR_MODEL successfully created.'

    3. 3.Create sensor_data_device3 with three readings at 00:00:30, 00:00:31 and 00:00:32, then CALL sensor_model!DETECT_ANOMALIES with SYSTEM$REFERENCE('TABLE', 'sensor_data_device3').

      Why: Test timestamps must come right after the training data.

      You should see: Three rows with FORECAST, LOWER_BOUND, UPPER_BOUND and IS_ANOMALY. Because the data is random, your flags may differ from the documented output.

    4. 4.Call DETECT_ANOMALIES again on the same data with CONFIG_OBJECT => {'prediction_interval':0.9999}, then with {'prediction_interval':0.9}.

      Why: Sensitivity is set at call time, so no retraining is needed.

      You should see: The bounds widen at 0.9999, so the same or fewer rows are flagged, and narrow at 0.9, so the same or more are flagged.

    Stuck? Get a nudge

    If a reading is flagged in one run but not the other, compare its Y with the UPPER_BOUND for that specific row. The flag depends only on that comparison.

    Sources

    (5)

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

    1. 1.
      “you can roll up these records to a coarser granularity, effectively producing a smaller sample.”
      ↩︎ Downsampling events with DATE_TRUNC to show the trend
      “the query downsamples the original 248M rows to about 500,000 rows.”
      ↩︎ Downsampling events with DATE_TRUNC to show the trend
      “For machine-learning purposes, the timestamps in your time series must represent fixed time intervals.”
      ↩︎ Downsampling events with DATE_TRUNC to show the trend
    2. 2.
      “An anomaly detection model produces a forecast for the same time period as the data you’re checking for anomalies”
      ↩︎ Flagging outliers with SNOWFLAKE.ML.ANOMALY_DETECTION
      “The anomaly detection model identifies any data that falls outside of the prediction interval as an anomaly.”
      ↩︎ Flagging outliers with SNOWFLAKE.ML.ANOMALY_DETECTION
      “You need at least 2 data points to train a model, at least 12 for non-naive results, and at least 60 for non-linear results.”
      ↩︎ Flagging outliers with SNOWFLAKE.ML.ANOMALY_DETECTION
      “Ensure that the training data covers a typical period free of actual outliers, or label known outliers in a Boolean column.”
      ↩︎ Flagging outliers with SNOWFLAKE.ML.ANOMALY_DETECTION
      “Anomaly detection models, once trained, are immutable. You cannot update existing models with new data; you must train an entirely new model.”
      ↩︎ Flagging outliers with SNOWFLAKE.ML.ANOMALY_DETECTION
      “Appropriate exogenous variables could include weather data (temperature, rainfall), company-specific information (historic and planned company holidays, advertisement campaigns, event schedules)”
      ↩︎ Collecting the related data that explains an anomaly
      “you must provide values for those variables at timestamps in the future when detecting anomalies”
      ↩︎ Collecting the related data that explains an anomaly
      “The anomaly detection model detects and uses the additional columns automatically.”
      ↩︎ Collecting the related data that explains an anomaly
      “can have an outsized impact on statistics and models derived from your data”
      ↩︎ Measuring relationships between metrics with CORR
      “To mark fewer observations as anomalies, specify a higher value for prediction_interval.”
      ↩︎ Exam trap 1
      “This feature only detects anomalies in the test data; it cannot detect anomalies in the training data.”
      ↩︎ Exam trap 2
      “Anomaly detection models, once trained, are immutable. You cannot update existing models with new data; you must train an entirely new model.”
      ↩︎ Exam trap 3
      “To mark fewer observations as anomalies, specify a higher value for prediction_interval.”
      ↩︎ Prediction
      “This feature only detects anomalies in the test data; it cannot detect anomalies in the training data.”
      ↩︎ Checkpoint
      “If your model incorporates exogenous variables, you must provide values for those variables at timestamps in the future when detecting anomalies.”
      ↩︎ Checkpoint
      “Outliers, which are data points that deviate from the expected range, can have an outsized impact on statistics and models derived from your data.”
      ↩︎ Checkpoint
    3. 3.
      “Returns the correlation coefficient for non-null pairs in a group.”
      ↩︎ Measuring relationships between metrics with CORR
      “COVAR_POP(y, x) / (STDDEV_POP(x) * STDDEV_POP(y))”
      ↩︎ Measuring relationships between metrics with CORR
    4. 4.
      “a Boolean label column that distinguishes rows that are part of the control group (labeled FALSE) from rows in the test group (labeled TRUE)”
      ↩︎ Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS
      “to understand which user segments are responsible for differences in new user growth between the United States and EMEA countries”
      ↩︎ Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS
      “To use a numeric value as a categorical dimension, cast it to a string.”
      ↩︎ Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS
      “The impact of the segment as a proportion of the overall change in the metric between test and control.”
      ↩︎ Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS
      “The contribution, relative contribution, and growth rate may be negative, indicating that a segment has a negative impact.”
      ↩︎ Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS
      “The output is ordered by CONTRIBUTION, with the Overall segment always at the top.”
      ↩︎ Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS
      “Datasets that surpass about 1,000,000 rows and 1,000 columns may exhaust memory.”
      ↩︎ Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS
      “The control group consists of the data points the model will use as a baseline.”
      ↩︎ Key concept
      “Snowflake recommends using a Snowpark-optimized warehouse rather than a larger standard warehouse.”
      ↩︎ Exam trap 4
    5. 5.
      “For categorical dimensions having more than 25 values, Top Insights uses only the top 25 most influential values to create segments.”
      ↩︎ Explaining a metric change by segment with SNOWFLAKE.ML.TOP_INSIGHTS

    Ready to test yourself?

    Practise the 29 questions on this subdomain.

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