---
title: "Data quality (advanced)"
description: Validate your data and control its quality
keywords: ["dlthub", "data quality", "contracts", "check", "metrics"]
---
# Data quality (advanced)

:::warning
This feature is in public preview
:::

This page covers more in-depth details about [dltHub data quality](https://dlthub.com/products/data-quality) features, such as metrics and checks. It shows the full flexibility available for advanced use cases. It can also serve as an FAQ and helper for debugging.

Note that these APIs are more likely to change than the basics page.

## Anatomy of a check: result, decision, outcome

In its simplest form, a check is a function that returns an **outcome** that indicates success or failure. Under the hood, it involves a **result** that is computed from the data and converted to the outcome by a **decision**.

For example, the check `is_in("payment_method", ["card", "cash", "voucher"])` succeeds if all values are valid. But the same question allows a more granular answer: count the rows with a valid value (the **result**), compare their share with `0.95` (the **decision**), and call the check a success if the share is higher (the **outcome**). The result, the decision and the outcome are separate things, and built-in checks keep them separate:

- The **result** is computed from metrics. For `is_in` it is the number of failing rows, the sum of the `invalid_count` and `null_count` metrics. For `freshness("updated_at", ...)` it is the age of the latest timestamp, computed from the `maximum` metric. The result is stored in `check_value`.
- The **decision** is `check_value <= threshold`. A check on rows tolerates no failing rows, so its `threshold` is 0. `freshness` takes `max_age` as its threshold.
- The **outcome** is stored in `outcome` as `pass` or `fail`.

dlt stores all three, together with the metrics that the result was computed from. This is what makes a check more useful than a boolean. When `payment_method__is_in` fails, you see that 3 of 120 rows failed and not only that something is wrong. You can track the result over time and see whether it grows or shrinks between loads. And because the result is kept apart from the decision, you can apply different thresholds in different environments, and the history of a check survives when you change its threshold.

Built-in checks are of two kinds, depending on the granularity of the result:

- A **row check** has a result for each row: the row passes or fails. Its metrics count the failing rows, and the check passes when there are none. Because the result exists per row, dlt can also select [the rows that failed](./index.md#find-the-rows-that-failed). `is_not_null`, `is_unique`, `is_primary_key`, `is_in`, `case` and `references` are row checks.
- A **value check** decides on the value of a metric with a rule of its own, and has no failing rows to show. `freshness` is a value check: it compares the age of the latest value with `max_age`.

Built-in row checks always use a threshold of 0. A check with any other decision, such as the 95% rule above, is a value check that you can [write yourself](#custom-checks-and-metrics).

:::important
The kind of a check relates to its result and not to its **input data**. A row check can involve several tables as input: `references` counts the rows of one table that have no match in another one.
:::

## How metrics and checks are computed

`dq.run()` does not run one query per check. It first resolves everything that a run must compute into **measures**, and then combines the measures of a table into as few queries as the destination allows. A measure is the SQL that computes one metric on one table of one destination. dlt builds measures with sqlglot, in the dialect of the destination.

### Three kinds of measure

How a metric is computed depends on what it needs from the table:

| Measure   | How dlt computes it                                                       | Metrics                                                                                             |
| --------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Aggregate | All aggregates of a table share one query, which scans the table once     | `null_count`, `row_count`, `mean`, `maximum`, `invalid_count`, `failed_rows` and most other metrics |
| Grouped   | dlt groups the rows by a key. All metrics on the same key share one query | The table `unique_count`, and distinct counts on some destinations                                  |
| Query     | The metric gets a query of its own                                        | `mode`, `unmatched_count`                                                                           |

Row checks do not add queries. Their metrics count the failing rows with an aggregate over a row condition, so `is_not_null("email")` becomes one more column in the aggregate query of the table: the number of rows where `email` is null.

Uniqueness is the interesting case. The obvious way to find duplicates is a window function that numbers the copies of each key, and a window over a full table is the most expensive part of a uniqueness check. `is_unique` and `is_primary_key` avoid it: they do not look at individual rows at all, and subtract the number of distinct keys from the number of rows. As a result, checks use no window functions in `dq.run()`. Only `CheckSuite.get_failures()` needs one, because it has to select the extra copies of a key.

### Each metric is computed once

Before dlt builds the queries of a table, it collects the metrics of that table from three places: the metrics that you declared with `with_metrics`, the metrics that you passed to the run, and the metrics of all checks of the table. Two metrics with the same level, column and qualified name are the same metric and are computed once.

For example, `is_not_null(col)` and `is_primary_key(col)` share one `null_count(col)`, and if you also declare `null_count(col)` yourself, it is still computed and stored once. This is why you do not pay for declaring a metric that a check already needs, and why a check result can point to the metric values it was evaluated on.

`row_count` of a table is computed when the table has a row check, because the share of failing rows needs it, or when you declare it.

### What differs between destinations

Destinations disagree on how to count distinct values, how to compute an exact percentile and which subqueries they accept. dlt picks the form that is correct on each of them and, where there is a choice, the cheapest one.

**Distinct counts** are behind `unique_count`, `duplicate_count`, `is_unique` and `is_primary_key`:

- For a single column, dlt adds `COUNT(DISTINCT col)` to the shared aggregate query. Databricks is the exception: grouping the rows by the key is cheaper there, so dlt runs one grouped query for all metrics on that key.
- For a key of several columns, duckdb, Postgres, Snowflake and ClickHouse count the distinct keys in the shared aggregate query. On other destinations, dlt groups the rows by the key.
- On ClickHouse, counting distinct keys of several columns needs memory for all keys of the table.

**Exact percentiles** are behind `median` and `quantile`. dlt does not fall back to approximate percentiles, so the function depends on the destination:

| Destination                         | Function                               | Query                                           |
| ----------------------------------- | -------------------------------------- | ----------------------------------------------- |
| duckdb, Snowflake, Postgres, Dremio | `PERCENTILE_CONT ... WITHIN GROUP`     | The shared aggregate query                      |
| Redshift                            | `PERCENTILE_CONT ... WITHIN GROUP`     | A query of its own                              |
| Databricks                          | `PERCENTILE`                           | The shared aggregate query                      |
| ClickHouse                          | `quantileExactInclusive`               | The shared aggregate query                      |
| BigQuery, MSSQL, Fabric             | `PERCENTILE_CONT` as a window function | One more query for all percentiles of the table |

On other destinations, `dq.run()` raises an error that lists all metrics that the destination cannot compute.

**References** are behind `references` and `unmatched_count`. dlt looks for each key with `NOT EXISTS` and a correlated subquery. ClickHouse and Redshift do not support that subquery in all places, so dlt uses `NOT IN` over the keys of the other table there.

**Tables without rows** give null for most aggregates. On ClickHouse, `MAX` and `MIN` over no rows return a default value such as 0, so dlt uses their `maxOrNull` and `minOrNull` variants to get null there as well.

**Values in checks**, such as the list of `is_in`, become literals of the column type: timestamps keep their time zone, dates stay dates, and decimals get the precision of the destination. A check therefore compares values in the same way on every destination.

### Tables are computed in parallel

Each table has a resource of its own in the data quality source, and dlt extracts these resources in parallel, at most `extract.workers` at a time (5 by default). Each resource uses its own connection to the destination, so a run with many tables is limited by the destination and not by the pipeline.

A dataset can hold the schemas of several sources. dlt computes each schema on its own, see [several sources in one dataset](./index.md#several-sources-in-one-dataset).

## Run the data quality source with your own pipeline

`dq.run()` computes metrics and checks with a `dlt.source`, `dq.data_quality_source(dataset)`, and loads it with an internal pipeline. The source takes the same arguments as `dq.run()`: `checks=`, `metrics=`, `dataset_metrics=`, `include_metrics`, `include_checks`, `include_registered` and `include_schema_derived_hints`. Load it with your own pipeline to:

- configure the pipeline that loads the results, for example its staging or its progress
- load the results to another destination or dataset
- run data quality apart from the primary `pipeline.run()`, for example on a schedule
- run one data quality pipeline for several pipelines or datasets

The checked pipeline can load the source itself. Create the report of the run from its `LoadInfo`:

```py notype
load_info = pipeline.run(
    dq.data_quality_source(
        pipeline.dataset(),
        checks={"orders": [dq.checks.is_not_null("order_id")]},
        include_schema_derived_hints=True,
    )
)
info = dq.DataQualityInfo.from_load_info(load_info)
info.raise_on_failed_checks()
```

Pass your pipeline to `dq.run()` as `results_pipeline` to load the results with it and get the report in one call:

```py notype
info = dq.run(pipeline, results_pipeline=pipeline)
```

`read_metric()` and `read_check()` read the results stored in the checked dataset. When your pipeline loads the results to another dataset, read them from the `DataQualityInfo` or query the results tables of that dataset.

The source has a resource for each checked table, `_dlt_dq_<schema>__<table>`, and `_dlt_dataset_metrics` for the dataset metrics. The resources run in parallel, as many at a time as `extract.workers` allows (5 by default), and each opens its own connection to the destination. When there is nothing to compute, the source has no resources: `dq.run()` warns and returns an empty report, and your pipeline loads no results.

## Metrics and checks use a special `dlt.Schema`

A `dlt.Pipeline` can load several sources, each with its own `dlt.Schema`, and `pipeline.dataset()` holds all of them. Each schema is checked on its own, see [several sources in one dataset](./index.md#several-sources-in-one-dataset).

Data quality results have a dedicated `_dlt_data_quality` schema with internal tables for metrics and checks results. This schema is not checked. Its tables are not directly visible via the `dlt.Dataset` API. (this may change in the future)

`dq.read_metric()`, `dq.read_metrics()` and `dq.read_check()` read these internal tables, `_dlt_dq_metrics` and `_dlt_checks`. [Results tables](./index.md#results-tables) describes their columns and how a check result points to its metric values.

## Built-in metrics

Built-in metrics are in three modules, one for each level that a metric can describe:

```py notype
from dlt.hub import data_quality as dq

# column-level
dq.metrics.column.maximum("col")
dq.metrics.column.minimum("col")
dq.metrics.column.mean("col")
dq.metrics.column.median("col")
dq.metrics.column.mode("col")
dq.metrics.column.sum("col")
dq.metrics.column.standard_deviation("col")
dq.metrics.column.quantile("col", quantile=0.95)
dq.metrics.column.null_count("col")
dq.metrics.column.null_rate("col")
dq.metrics.column.unique_count("col")
dq.metrics.column.duplicate_count("col")  # extra copies of non-null values
dq.metrics.column.invalid_count("col", valid_values=["a", "b"])  # non-null values not in the list
dq.metrics.column.invalid_count("col", invalid_values=["c"])  # non-null values in the list
dq.metrics.column.average_length("col")
dq.metrics.column.minimum_length("col")
dq.metrics.column.maximum_length("col")

# table-level
dq.metrics.table.row_count()  # Number of rows in table
dq.metrics.table.unique_count()  # Number of distinct / unique rows in table
dq.metrics.table.null_row_count()  # Number of rows where all columns are null
dq.metrics.table.null_count(["col_a", "col_b"])  # rows with a null in any of the columns
dq.metrics.table.duplicate_count(["col_a", "col_b"])  # extra copies of keys without nulls
dq.metrics.table.failed_rows("col_a > 0")  # rows for which the SQL condition is not true
dq.metrics.table.unmatched_count("col_a", "other", "key")  # rows whose key has no match in `other`

# dataset-level
dq.metrics.dataset.total_row_count()  # Total number of rows
dq.metrics.dataset.load_row_count()  # Rows added in latest load
dq.metrics.dataset.latest_loaded_at()  # Timestamp of most recent load
```

A metric with arguments is stored under its qualified name, for example `quantile__0.95` or `duplicate_count__col_a__col_b`. `invalid_count` is stored under a hash of its values, for example `invalid_count__1a2b3c4d`, so changing the values starts a new history.

`duplicate_count` counts extra copies: a value that occurs 3 times adds 2.

`median` and `quantile` compute exact values. A destination without an exact percentile function cannot compute them, see [what differs between destinations](#what-differs-between-destinations).

If you miss a built-in metric, let us know. You can also write [metrics of your own](#custom-checks-and-metrics).

## Custom checks and metrics

Built-in checks and metrics are classes, and you can write your own with the same base classes. Pass them to `dq.run()`: they are computed in the same scan of the table as the registered ones, and their results are stored the same way.

Custom definitions can't be registered with `@with_checks` or `@with_metrics`, because only built-in definitions are stored with the schema.

:::tip
For a simple condition you don't need a class. `dq.checks.case("amount <= 1000", name="amount_at_most_1000")` is a row check on a SQL condition.
:::

### A check on the value of a metric

A check declares the metrics it needs in `metrics()` and decides on their values in `evaluate()`. This check passes when the rate of nulls in a column is not above a threshold. It uses the built-in `null_rate` metric, so the metric is computed once, also when you register it yourself:

```py notype
from typing import Any, Sequence

from dlt.hub import data_quality as dq


class max_null_rate(dq.checks.LazyCheck):
    """Check that the rate of nulls in `{column}` is at most `{threshold}`."""

    def __init__(self, column: str, threshold: float) -> None:
        self._arguments = dict(column=column, threshold=threshold)

    @property
    def qualified_name(self) -> str:
        # without the threshold, the check keeps its history when the threshold changes
        return f"{self.arguments['column']}__max_null_rate"

    def metrics(self) -> Sequence[Any]:
        return (dq.metrics.column.null_rate(self.arguments["column"]),)

    def evaluate(
        self, values: Sequence[Any], ctx: dq.checks.CheckContext
    ) -> dq.checks.CheckEvaluation:
        # a table without rows has no nulls
        null_rate = values[0] or 0.0
        threshold = self.arguments["threshold"]
        outcome = "pass" if null_rate <= threshold else "fail"
        return dq.checks.CheckEvaluation(null_rate, threshold, outcome, "double")
```

`evaluate()` receives the values of the metrics in the order of `metrics()`. `CheckEvaluation` holds the value the check decided on, the threshold, the outcome and the dlt data type of the value. They are stored in `check_value`, `threshold`, `outcome` and `check_data_type`. The docstring of the class is the description of the check.

### A row check with its own metric

A row check is evaluated on metrics that count failing rows, and passes when they count none. Such a metric is a `RowCountMetric`: it returns a condition that is true for the rows it counts. The condition must never be null, so this one skips rows without a value:

```py notype
from sqlglot import exp as sge


class above_count(dq.metrics.RowCountMetric, dq.metrics.ColumnMetricDefinition):
    """Number of values of {column} above {maximum}"""

    def __init__(self, column: str, *, maximum: float) -> None:
        self._column = column
        self._arguments = {"maximum": maximum}

    def build_row_condition(self, ctx: dq.metrics.MeasureContext) -> sge.Expression:
        column = ctx.column(self.column)
        return sge.and_(
            column.is_(sge.null()).not_(),
            column > ctx.literal(self.arguments["maximum"], self.column),
        )


class is_at_most(dq.checks.RowCheck):
    """Check that values of `{column}` are at most `{maximum}`."""

    def __init__(self, column: str, maximum: float) -> None:
        self._arguments = dict(column=column, maximum=maximum)

    def metrics(self) -> Sequence[dq.metrics.RowCountMetric]:
        return (above_count(self.arguments["column"], maximum=self.arguments["maximum"]),)
```

`ctx.column()` returns the column under its normalized name, and `ctx.literal()` a literal of the column data type that the destination accepts. A row check with several metrics sums them, so its metrics must never count the same row twice.

### Run custom checks with the registered ones

```py notype
info = dq.run(
    pipeline,
    checks={"orders": [max_null_rate("amount", 0.1), is_at_most("amount", 1000)]},
    include_schema_derived_hints=True,
)
print(info.asstr(verbosity=1))
```

The checks declared with `@with_checks` and the [checks from schema hints](./index.md#derive-checks-from-schema-hints) run in the same `dq.run`. A check that you pass replaces the declared check, or the check from a hint, with the same qualified name. `include_registered=False` leaves out the declared checks and metrics.

The source takes the same arguments when you load it with your own pipeline:

```py notype
source = dq.data_quality_source(
    pipeline.dataset(),
    checks={"orders": [max_null_rate("amount", 0.1), is_at_most("amount", 1000)]},
    include_schema_derived_hints=True,
)
info = dq.DataQualityInfo.from_load_info(pipeline.run(source))
print(info.asstr(verbosity=1))
```

`CheckSuite` selects the rows that a custom row check counted:

```py notype
suite = dq.CheckSuite(pipeline.dataset(), checks={"orders": [is_at_most("amount", 1000)]})
suite.get_failures("orders", "amount__is_at_most__1000").df()
```

## Derive stateful metrics from the history

Some metrics depend on earlier loads: how many rows did the last load add, and is that number normal for this table? dlt does not compute such a metric, but `dq.read_metric()` returns the history that it needs.

The example below detects an anomaly in the volume of a load. It derives the rows that each load added from the history of `row_count`, and expresses the latest load as a z-score: its distance from the mean of the earlier loads, in standard deviations.

```py notype
def compute_added_rows_z_score(dataset, table):
    history = dq.read_metric(dataset, table=table, metric="row_count").df()
    # the newest run of each load of the data, oldest load first
    per_load = history.drop_duplicates("checked_load_id").iloc[::-1]
    # rows that each load added
    added = per_load["metric_value"].diff().dropna()
    latest, previous = added.iloc[-1], added.iloc[:-1]
    return (latest - previous.mean()) / previous.std()


pipeline.run(shop())
dq.run(pipeline)

z_score = compute_added_rows_z_score(pipeline.dataset(), "orders")
print(f"z-score of the rows added by the last load: {z_score:.1f}")
if abs(z_score) > 3:
    raise RuntimeError("The last load of `orders` does not look like the loads before it")
```

```text
z-score of the rows added by the last load: -27.8
RuntimeError: The last load of `orders` does not look like the loads before it
```

Here the earlier loads added about 100 rows each and the last one added 12. The derived value is not stored. The same pattern works for any stored metric, for example the `mean` of a column.
