Module 18 · Lesson 9 of 10Detailed study · about 38 min

Snowflake Data Metric Functions, expectations and quality alerts

Set up system and custom Data Metric Functions, verify failures and recovery, and monitor scheduled results.

Before you beginSet up the Maple Market governance lab

Separate the measure, rule, schedule and release decision

A manual query found a missing sales amount. The next report needs a repeated check. A Data Metric Function (DMF) measures a property of data. A system DMF such as NULL_COUNT is built in. A custom DMF lets you define a business rule, such as counting amounts less than or equal to zero. The metric produces a number. The expectation compares the number with an acceptable value.

Scheduling controls when Snowflake evaluates the associated metrics. Results are recorded asynchronously. An expectation violation can be recorded and sent as a notification after configuration. A violation does not undo a transaction or block a table load. Use the release gate for prevention and scheduled monitoring for detection.

Quality monitoring and the correction loop Keep detection separate from publication.
  1. Private incoming tableMeasure to Scheduled measurement
  2. Scheduled measurementEvaluate VALUE to Expectation and notification
  3. Expectation and notificationInvestigate a failed check to Owner investigates
  4. Owner investigatesValidate the repair to Separate publish gate
Private incoming table
Contains loaded rows.
Scheduled measurement
Count NULLs or nonpositive amounts.
Expectation and notification
Compare with a threshold and report a violation.
Owner investigates
Correct the source and recheck the batch.
Separate publish gate
Only validated rows reach reports.

Create one custom DMF and bind three measurements

Use a non-trial Enterprise Edition or higher account for Data Quality Monitoring. Seed the broken incoming dataset in the validation lesson and stop before correcting it. The administrator grants EXECUTE DATA METRIC FUNCTION on the account to the lab owner. Use a dedicated account because this is an account privilege. The lab owner owns the table and needs CREATE DATA METRIC FUNCTION on the QUALITY schema. The role that manually calls a custom DMF needs USAGE on it and SELECT on the source.

INPUT_ROWS TABLE declares which input shape the custom DMF accepts. Its SQL returns one deterministic number. ON (AMOUNT) binds the actual column to that argument. The expression VALUE = 0 tells Snowflake what number passes. FRESHNESS(LOADED_AT) measures age in seconds from the latest input timestamp. Scheduled evaluation uses the scheduled time for the freshness comparison. The five-minute table schedule applies to all three associations. Schedule changes may take time to settle. Automated measurements consume Snowflake serverless compute.

Give the lab owner the execution privilege

SQL · runnable example
USE ROLE ACCOUNTADMIN;
GRANT EXECUTE DATA METRIC FUNCTION ON ACCOUNT TO ROLE M18_OWNER;

Create, attach and schedule the measurements

SQL · runnable example
USE ROLE M18_OWNER;
CREATE DATA METRIC FUNCTION LS_M18_GOV_LAB.QUALITY.COUNT_NONPOSITIVE(
  INPUT_ROWS TABLE (AMOUNT NUMBER)
) RETURNS NUMBER AS $$
  SELECT COUNT(*) FROM INPUT_ROWS WHERE AMOUNT <= 0
$$;

ALTER TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES
  SET DATA_METRIC_SCHEDULE = '5 MINUTE';
ALTER TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES
  ADD DATA METRIC FUNCTION SNOWFLAKE.CORE.NULL_COUNT ON (AMOUNT)
    EXPECTATION MISSING_AMOUNT_ZERO (VALUE = 0);
ALTER TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES
  ADD DATA METRIC FUNCTION LS_M18_GOV_LAB.QUALITY.COUNT_NONPOSITIVE ON (AMOUNT)
    EXPECTATION NONPOSITIVE_ZERO (VALUE = 0);
ALTER TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES
  ADD DATA METRIC FUNCTION SNOWFLAKE.CORE.FRESHNESS ON (LOADED_AT)
    EXPECTATION LOADED_WITHIN_30_MINUTES (VALUE >= 0 AND VALUE <= 1800);

Read both known failures before and after the source repair

Run the on-demand evaluation as M18_OWNER before the source repair. NULL_COUNT counts the missing amount. The custom check counts the negative amount; NULL does not satisfy AMOUNT <= 0. Both values should be 1. Both expectations fail because the contract permits zero defects.

After applying the repair in the data quality lesson, run the same evaluation. Both drop to zero and pass. Freshness is time-dependent. A recent seeded batch should pass and a late one can still fail after the amounts are fixed. On-demand evaluation reads current values and does not by itself record scheduled history. Check the latest measurement separately.

Expected value checks before and after repair
ExpectationBroken valueBroken violated?Repaired valueRepaired violated?
MISSING_AMOUNT_ZERO1TRUE0FALSE
NONPOSITIVE_ZERO1TRUE0FALSE
SQL · runnable example
SELECT METRIC_NAME, EXPECTATION_NAME, VALUE, EXPECTATION_VIOLATED
FROM TABLE(SYSTEM$EVALUATE_DATA_QUALITY_EXPECTATIONS(
  REF_ENTITY_NAME => 'LS_M18_GOV_LAB.QUALITY.INCOMING_SALES'))
ORDER BY METRIC_NAME;

Interpret scheduled results and check missing measurements

Use the owner’s monitored object access and the Snowflake DATA_QUALITY_MONITORING_LOOKUP application role, which normally comes through PUBLIC. If your account restricts it, request the role from an authorized administrator. The history below may be empty before the first run. The timestamp distinguishes an old failing sample from the latest successful sample. A NULL violation status can mean evaluation failed. Treat it as unknown until diagnosed.

An old or suspended association cannot prove freshness. Check SHOW PARAMETERS LIKE 'DATA_METRIC_SCHEDULE' IN TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES and DATA_METRIC_FUNCTION_REFERENCES in Information Schema for active associations. Then use the actual validation SQL and the reject log to find and resolve the individual rows. Create an owner for response and an escalation time based on the report deadline.

Simulated measurement history
MEASUREMENT_TIMEMETRIC_NAMEVALUEEXPECTATION_VIOLATED
09:00NULL_COUNT1TRUE
09:05NULL_COUNT0FALSE
SQL · runnable example
SELECT MEASUREMENT_TIME, METRIC_NAME, VALUE, EXPECTATION_VIOLATED
FROM TABLE(SNOWFLAKE.LOCAL.DATA_QUALITY_MONITORING_EXPECTATION_STATUS(
  REF_ENTITY_NAME => 'LS_M18_GOV_LAB.QUALITY.INCOMING_SALES',
  REF_ENTITY_DOMAIN => 'TABLE'))
WHERE MEASUREMENT_TIME >= DATEADD('hour', -2, CURRENT_TIMESTAMP())
ORDER BY MEASUREMENT_TIME DESC, METRIC_NAME;

Route optional alerts and stop lab monitoring

Snowflake supports notifications for violated expectations and detected anomalies. An expectation checks an explicit rule. An anomaly is an unusual measurement relative to history. In a production account, agree who receives the message, how often the team should be notified and which metadata may be sent. Verify delivery on an approved sandbox destination before trusting it.

Optional template only. The administrator verifies the recipient and grants MANAGE DATA QUALITY ON ACCOUNT to the database owner for configuring notifications. The owner fills in the authorized email. No email integration is needed for the direct recipient example. The cooldown reduces repeat notifications and metadata is disabled in this example. If there is no approved destination, use the history view as the response queue.

SQL · configuration template
ALTER DATABASE LS_M18_GOV_LAB SET DATA_QUALITY_MONITORING_SETTINGS = $$
notification:
  enabled: true
  email_recipients: ['<approved_verified_test_email>']
  cooldown_hours: 4
  metadata_included: false
$$;

Remove monitoring from the disposable input

Stop scheduling and drop the associations before dropping the custom metric. If notifications were enabled, disable them through the same database settings before the capstone cleanup. The administrator removes lab-only account privileges when the owner role is retired.

SQL · runnable example
ALTER TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES SET DATA_METRIC_SCHEDULE = '';
ALTER TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES
  DROP DATA METRIC FUNCTION SNOWFLAKE.CORE.NULL_COUNT ON (AMOUNT);
ALTER TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES
  DROP DATA METRIC FUNCTION LS_M18_GOV_LAB.QUALITY.COUNT_NONPOSITIVE ON (AMOUNT);
ALTER TABLE LS_M18_GOV_LAB.QUALITY.INCOMING_SALES
  DROP DATA METRIC FUNCTION SNOWFLAKE.CORE.FRESHNESS ON (LOADED_AT);
DROP FUNCTION LS_M18_GOV_LAB.QUALITY.COUNT_NONPOSITIVE(TABLE(NUMBER));

Interview practice

Explain the decision and the evidence you would use to test it.

What does a Data Metric Function return?

It returns a measurement of the data. NULL_COUNT returns one for this broken input. The expectation separately says any value above zero is a violation.

How would you set up automatic monitoring?

I would bind the right columns, choose a schedule and add a threshold. Then I would verify one passing and one failing run, confirm the monitoring role and check that the intended team gets the alert if configured.

Why can the latest alert stay red after a repair?

It may describe an earlier measurement. I would compare measurement times, evaluate the current table and verify that the next scheduled measurement arrives. I would also check that the gate allows the corrected delivery before claiming the report recovered.

Words used in this lesson
Data Metric Function
A measurement defined over table or view data.
DMF
Short for Data Metric Function.
Expectation
A Boolean rule about what value is acceptable.
Measurement time
When the metric was evaluated.

See how it works

Choose a step to explore the idea at your own pace.

Open the interactive explanation
Interactive explainer1 / 1

Snowflake Data Metric Functions, expectations and quality alerts

Private incoming table
Scheduled measurement
Expectation and notification
Owner investigates
Separate publish gate

Quality monitoring and the correction loop

Keep detection separate from publication.

Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.

Read the complete diagram explanation
  1. Quality monitoring and the correction loop

    Keep detection separate from publication.

    Private incoming table → Scheduled measurement → Expectation and notification → Owner investigates → Separate publish gate

Try the SQL or command

Read → predict → run in your learning environment → compare. You can also learn by reading without an account.

New to SQL? Where to run it and how to read it

A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.

  1. No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
  2. For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
  3. Read the entire example, including comments beginning with --. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor.
  4. Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
SELECT / FROM
Choose the values to return / identify their input.
VALUES / COLUMN1
VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
AS / WITH
AS gives a result a readable name. WITH names a temporary query step within one statement.
NULL / ::
NULL means missing or unknown. The :: notation converts a value to a named data type.
Session
One connection and its settings. Keep related transaction steps in the same session.
Database.schema.table
A full address for stored data. It is separate from the warehouse that processes queries.

Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →

Help with common practice errors
  • No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
  • Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
  • Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
  • Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.

Before running this lesson

All records are fictional. Outputs are expected or simulated. Live practice needs an authorized scratch account, test roles, an approved warehouse and the editions listed in the lesson.

Check your understanding

Choose an answer, then check your reasoning. This is practice, not a scored test.

Does a NULL_COUNT expectation stop INSERT from loading a NULL?

Try it yourself

The last scheduled measurement is missing. What should an on-call engineer do?

Compare your reasoning

Check the association and schedule, run an on-demand evaluation, compare measurement times and inspect the input. Do not mark the feed healthy from missing evidence.

Connect this lesson to the learning path

Official sources and curriculum

Module 18 · See module scope

By Rohit Ray · Independent educational lesson · Explore this visual lab