What are best practices for implementing Data Quality checks using SQL in Microsoft Databricks?

Mphela Legodi 0 Reputation points
2026-11-30T10:12:14.7566667+00:00

I am developing Data Quality controls and would like to understand the recommended approach for implementing SQL-based Data Quality checks in Microsoft Databricks.

For example, when validating completeness, uniqueness, validity and consistency, what is the best way to structure the SQL checks so that they are reusable and maintainable?

I would also like to understand whether there are recommended Microsoft or Databricks features that can be used alongside SQL for monitoring Data Quality over time.

Azure Databricks
Azure Databricks

An Apache Spark-based analytics platform optimized for Azure.

0 comments No comments

1 answer

Sort by: Oldest
  1. AI answer

    2026-11-30T10:13:10.49+00:00

    Implement SQL-based controls as named Lakeflow Spark Declarative Pipelines expectations, using row-level expectations for completeness and validity and separate validation materialized views for uniqueness and cross-table consistency.

    1. Structure checks by scope

    Lakeflow expectations are named Boolean SQL expressions attached to streaming tables, materialized views, or temporary views. Each name must be unique within its dataset and should describe the tested condition. Expectations cannot contain subqueries referencing other tables, so divide controls into:

    • Row-level controls: null checks, ranges, formats, allowed values, and relationships between columns in the same row.
    • Dataset-level controls: uniqueness, row counts, reconciliation, and cross-table completeness. Calculate these in a validation materialized view, then apply an expectation to its result. ^1^

    For example:

    CREATE OR REFRESH STREAMING TABLE orders_validated (
      CONSTRAINT complete_order_id
        EXPECT (order_id IS NOT NULL) ON VIOLATION FAIL UPDATE,
      CONSTRAINT valid_amount
        EXPECT (amount >= 0) ON VIOLATION DROP ROW,
      CONSTRAINT valid_status
        EXPECT (status IN ('NEW', 'PAID', 'CANCELLED')),
      CONSTRAINT consistent_dates
        EXPECT (order_date <= ship_date OR ship_date IS NULL)
    )
    AS SELECT * FROM STREAM(orders_raw);
    

    This maps common dimensions as follows:

    Dimension SQL pattern
    Completeness column IS NOT NULL, or an aggregate/left-join validation for missing records
    Validity Ranges, allowed-value lists, date rules, or CASE expressions
    Consistency Relationships such as start_date <= end_date; use a validation view for cross-table rules
    Uniqueness GROUP BY business_key and test that COUNT(*) = 1

    Uniqueness is an aggregate property rather than a per-row expression:

    CREATE OR REFRESH MATERIALIZED VIEW order_key_tests (
      CONSTRAINT unique_order_id
        EXPECT (num_entries = 1) ON VIOLATION FAIL UPDATE
    )
    AS
    SELECT order_id, COUNT(*) AS num_entries
    FROM orders_validated
    GROUP BY order_id;
    

    Databricks documents the same validation-table pattern for primary-key uniqueness, missing-record detection, and row-count reconciliation. ^2^

    2. Choose the violation policy deliberately

    Use the response that matches the business impact:

    • Warn — EXPECT: retain invalid rows and record metrics. Suitable during profiling or where no data may be discarded.
    • Drop — ON VIOLATION DROP ROW: exclude bad rows from the target and record the dropped count.
    • Fail — ON VIOLATION FAIL UPDATE: stop and roll back the affected update when invalid data is unacceptable.
    • Quarantine: route invalid rows into a separate table when they must be investigated or reprocessed rather than silently dropped. ^3^

    A failed validation flow does not necessarily gate unrelated flows in the same pipeline. If downstream processing must run only after validation succeeds, put validation and downstream processing in separate pipelines and make the downstream Lakeflow Job task depend on the validation task. ^2^

    3. Make rules reusable and maintainable

    Use these conventions:

    1. Give every rule a stable name such as completeness_customer_id or validity_order_status.
    2. Keep pipeline transformations separate from rule definitions.
    3. Classify rules with metadata such as domain, quality dimension, severity, owner, and effective date.
    4. Version SQL and pipeline configuration in Git and deploy through automated CI/CD. ^4^
    5. Parameterize catalog or schema names rather than hardcoding environment-specific identifiers. ^3^

    A central Delta rules table is recommended for portable expectations, but SQL pipelines cannot dynamically load expectation definitions from a file or table. If fully metadata-driven reuse is required, retain the rules as SQL Boolean strings in a Delta table and use the Lakeflow Python API to load and apply them as a dictionary. Pure SQL implementations should generate/version SQL declarations or maintain shared SQL templates instead. ^2^

    4. Monitor quality over time

    Use two complementary mechanisms:

    • Pipeline event log: expectations emit pass/fail metrics that can be queried by dataset and rule, then displayed in SQL dashboards. The event log also contains pipeline progress, errors, and lineage. Access normally requires the pipeline run-as user or sufficient privileges. ^5^
    • Unity Catalog Data Quality Monitoring: use anomaly detection for freshness and completeness, and profiling for null rates, distributions, drift, historical statistics, and custom metrics. It monitors tables without modifying them or adding overhead to the jobs that populate them, but it uses billable serverless compute. ^6^

    For production, prioritize monitors on business-critical gold tables, use time-series monitoring where temporal columns exist, snapshot monitoring otherwise, and create alerts for quality violations, anomalies, and freshness SLA breaches. ^7^


    References

    1. Manage data quality with pipeline expectations
    2. Expectation recommendations and advanced patterns
    3. Best practices for Lakeflow pipelines
    4. Architecture best practices for Azure Databricks
    5. Queries data quality or expectations metrics for the last pipeline update, aggregating passed and failed records per dataset and expectation, using the event_lo...
    6. Data quality monitoring
    7. Phase 9: Design observability strategy
    AI-generated content may be incorrect. Read our transparency notes for more information.

    Was this answer helpful?

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.