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

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

[dltHub data quality](https://dlthub.com/products/data-quality) lets you state what you expect from the data that dlt loads, and tells you when the data does not meet these expectations. You declare **checks** in Python, next to the resources that produce the data. dlt runs them on the destination, reports what failed and stores the results with your data, so you can follow how the quality of a dataset changes from load to load.

This page introduces the concepts first. Then it shows how to declare and run checks, how to find the rows behind a failed check, how to track **metrics** over time and how to read the stored results.

## How it works

Data quality in dlt rests on three concepts: metrics, checks and measures.

A **metric** is a property of your data that can be measured and given a name: the number of rows in a table, the share of nulls in a column, the latest value of `updated_at`. A metric describes a column, a table or a whole dataset. dlt computes its value at a point in time and stores it, so the values of one metric form a history that you can plot, compare between loads or alert on.

A **check** is a test that dlt runs against a table. It compares the value of one or more metrics with a **threshold**, and this comparison gives the **outcome** of the check: `pass` or `fail`. For example, `is_not_null("customer_id")` is a statement about the metric "number of nulls in `customer_id`", and it passes when that number is 0. Every check is defined on metrics, so the number behind each outcome is always available and always stored.

A **measure** is the way a metric is computed on a particular table and destination, that is the SQL that dlt generates for it. You never write measures yourself. They are worth knowing about because they explain the cost of a run: dlt combines the measures of a table into as few queries as the destination allows.

The table shows how the three concepts relate for three checks on an `orders` table:

| Check                                  | Metric                             | Measure                                                  | The check passes when                        |
| -------------------------------------- | ---------------------------------- | -------------------------------------------------------- | -------------------------------------------- |
| `is_not_null("customer_id")`           | `null_count` of `customer_id`      | An aggregate over the rows of `orders`                   | No row has a null                            |
| `freshness("updated_at", max_age=...)` | `maximum` of `updated_at`          | An aggregate over the rows of `orders`                   | The latest value is not older than `max_age` |
| `references()`                         | `unmatched_count` of `customer_id` | A query that looks for each `customer_id` in `customers` | Each row has a match                         |

The first two metrics are aggregates over the rows of `orders`, so their measures share a single query. The third one needs the `customers` table and gets a query of its own:

```mermaid
flowchart LR
    subgraph checks["Checks"]
        c1["is_not_null(customer_id)"]
        c2["freshness(updated_at)"]
        c3["references()"]
    end
    subgraph metrics["Metrics"]
        m1["null_count(customer_id)"]
        m2["maximum(updated_at)"]
        m3["unmatched_count(customer_id)"]
    end
    subgraph measures["Measures"]
        q1["one aggregate query on orders"]
        q2["one query on orders and customers"]
    end
    c1 --> m1 --> q1
    c2 --> m2 --> q1
    c3 --> m3 --> q2
```

Built-in checks are of two kinds. A **row check** passes or fails for each row, and passes when no row fails, so dlt can also select [the rows that failed](#find-the-rows-that-failed). A **value check** such as `freshness` decides on the value of a metric and has no failing rows. Each check stores the value it was decided on next to its outcome. [Anatomy of a check](./advanced.md#anatomy-of-a-check-result-decision-outcome) explains how the result, the decision and the outcome relate.

:::info
A **test** verifies that **code** behaves as expected. A **check** verifies that the **data** meets some expectations. Code tests enable you to make changes with confidence and data checks help monitor your live systems.
:::

### When and where checks run

`dq.run()` computes metrics and checks **after the load**. The pipeline extracts, normalizes and loads the data as usual, and the checks then run as queries on the destination, over all rows of each table. No data leaves the destination, so the cost scales with your warehouse and not with the machine that runs the pipeline, and a check sees the full table and not only the latest load.

The other side of this choice is that a failed check cannot keep bad records out of the destination: the data is already there. Checks that run before the load are work in progress. dlt already validates source data during extract and normalize with schema contracts and Pydantic models. [Data quality lifecycle](./lifecycle.md) describes all stages at which you can validate data and what is available at each of them.

### Where results are stored

Results are data. dlt appends the outcome of each check and the value of each metric to two tables in the same dataset, `_dlt_checks` and `_dlt_dq_metrics`. Each run writes one load and nothing is overwritten. As a result, every check and every metric has a history that you can query like any other table, join with your own data or show on a dashboard. See [read stored results](#read-stored-results).

### What dlt does for you

If each check ran a query of its own, a table with twenty checks would be scanned twenty times. dlt plans a run so that the destination does as little work as possible:

- **Each metric is computed once per run**, also when several checks use it and when you declared it yourself. `is_not_null(col)` and `is_primary_key(col)` share one `null_count(col)`.
- **Each table is scanned once for all its aggregates.** Only a metric that cannot be written as an aggregate over the table, such as a lookup in another table, gets a query of its own.
- **The SQL is generated for your destination.** Distinct counts, exact percentiles and reference lookups use the form that is correct and cheapest in its dialect.
- **Tables are computed in parallel.**

[How metrics and checks are computed](./advanced.md#how-metrics-and-checks-are-computed) describes the queries in detail.

## Run checks on your data

In this section we take a small `shop` source with two tables, `customers` and `orders`, and make sure that:

- each customer has an email, and no two customers share one
- each order has a customer, and this customer exists in `customers`
- each order uses a known payment method
- new orders arrive each day

### 1. Declare checks on your resources

You declare checks with the `@dq.with_checks` decorator, placed above `@dlt.resource`. The checks themselves come from the `dq.checks` module:

```py notype
from datetime import datetime, timedelta, timezone

import dlt
from dlt.hub import data_quality as dq


@dq.with_checks(
    dq.checks.is_not_null("email"),
    dq.checks.is_unique("email"),
)
@dlt.resource(primary_key="id")
def customers():
    yield [
        {"id": 1, "email": "ann@example.com"},
        {"id": 2, "email": None},
        {"id": 3, "email": "cho@example.com"},
    ]


@dq.with_checks(
    dq.checks.is_not_null("customer_id"),
    dq.checks.is_in("payment_method", ["card", "cash", "voucher"]),
    dq.checks.freshness("updated_at", max_age=timedelta(days=1)),
    dq.checks.references(),
)
@dlt.resource(
    references=[
        {
            "columns": ["customer_id"],
            "referenced_table": "customers",
            "referenced_columns": ["id"],
        }
    ]
)
def orders():
    rows = [
        {"id": 1, "customer_id": 1, "amount": 25.0, "payment_method": "card"},
        {"id": 2, "customer_id": 2, "amount": 80.5, "payment_method": "cash"},
        {"id": 3, "customer_id": 7, "amount": 14.5, "payment_method": "crypto"},
    ]
    updated_at = datetime.now(timezone.utc) - timedelta(hours=2)
    yield [{**row, "updated_at": updated_at} for row in rows]


@dlt.source
def shop():
    return customers, orders
```

Here `customers` gets two checks on the `email` column. `orders` gets four: the customer must be present, the payment method must be one of three known values, the newest order must not be older than one day, and `references()` verifies the reference to `customers` that the resource declares in its `references` hint. The sample data violates three of these checks on purpose.

Checks are stored in the schema of the pipeline, together with the other table hints. They travel with your data: any later run finds them there, also when it starts from another script.

### 2. Load the data and run the checks

Run the pipeline as usual, then pass it to `dq.run`:

```py notype
pipeline = dlt.pipeline("shop", destination="duckdb")
pipeline.run(shop())

info = dq.run(pipeline)
```

`dq.run` reads the checks from the schema, computes them on the destination and stores the results in the dataset. It returns a `DataQualityInfo`, the checks info of this run.

A failed check does not stop your script. `dq.run` reports it in the checks info, and you [decide what a failed check does](#decide-what-a-failed-check-does).

### 3. Read the report

Print the checks info to get the report of the run:

```py notype
print(info)
```

```text
Data quality results of 6 check(s) in dataset shop_dataset, 3 failed
[fail] customers.email__is_not_null: 1 of 3 rows failed
[fail] orders.customer_id__references__customers: 1 of 3 rows failed
[fail] orders.payment_method__is_in: 1 of 3 rows failed
[pass] customers.email__is_unique: 0 of 3 rows failed
[pass] orders.customer_id__is_not_null: 0 of 3 rows failed
[pass] orders.updated_at__freshness: 7199.996722, threshold 86400.0
```

Each line shows the outcome, the table and the name of the check, which is built as `<column>__<check>`. A row check reports how many rows failed. `freshness` reports the age of the latest value in seconds, followed by its threshold.

The report reflects the three problems that we put into the sample data: customer 2 has no email, and order 3 uses the payment method `crypto` and belongs to customer 7, who does not exist in `customers`.

### Decide what a failed check does

`dq.run` does not raise when a check fails. It stores the results, returns the checks info and leaves the decision to you. If the steps that follow must not run on bad data, pass `raise_on_failed_checks=True`:

```py notype
dq.run(pipeline, raise_on_failed_checks=True)
```

```text
dlthub.data_quality._info.DataQualityChecksFailed: 3 data quality check(s) failed on dataset `shop_dataset`:
[fail] customers.email__is_not_null: 1 of 3 rows failed
[fail] orders.customer_id__references__customers: 1 of 3 rows failed
[fail] orders.payment_method__is_in: 1 of 3 rows failed
```

Here `dq.run` raises `DataQualityChecksFailed` and stops the script. The results are stored before the exception is raised, so a failed run is part of the history as well, and the exception carries the checks info of the run in its `info` attribute.

If you want to handle failed checks in code, inspect the checks info:

```py notype
info = dq.run(pipeline)
if info.has_failed_checks:
    print([check["check_qualified_name"] for check in info.failed_checks])
```

```text
['email__is_not_null', 'customer_id__references__customers', 'payment_method__is_in']
```

Here we only print the names of the failed checks, but this is the place where you would send an alert or skip a downstream transformation. You can still stop the script afterwards with `info.raise_on_failed_checks()`, which raises the same exception.

### Use the checks info

`dq.run` returns a `DataQualityInfo`, the checks info of the run. It plays the role that `LoadInfo` plays for `pipeline.run`: it describes what happened in this run only, and you can print it, inspect it in code or raise on it.

| Use                                             | To get                                                                   |
| ----------------------------------------------- | ------------------------------------------------------------------------ |
| `print(info)`                                   | The report: one line for each check, failed checks first                 |
| `info.asstr(verbosity=1)`                       | The report with the description of each check and with the metric values |
| `info.has_failed_checks`                        | `True` when a check failed                                               |
| `info.failed_checks`                            | The results of the failed checks, one dictionary for each check          |
| `info.raise_on_failed_checks()`                 | A `DataQualityChecksFailed` exception if a check failed                  |
| `info.checks`                                   | A `dlt.Relation` with the rows that the run wrote to `_dlt_checks`       |
| `info.metrics`                                  | A `dlt.Relation` with the rows that the run wrote to `_dlt_dq_metrics`   |
| `info.checks_report()`, `info.metrics_report()` | One part of the report                                                   |
| `info.load_info`                                | The `LoadInfo` of the load that wrote the results                        |

Printing the info with `verbosity=1` is the quickest way to understand a failure. The report then includes the description of each check and the values of the metrics that the checks were evaluated on:

```py notype
print(info.asstr(verbosity=1))
```

```text
Data quality results of 6 check(s) in dataset shop_dataset, 3 failed
[fail] customers.email__is_not_null: 1 of 3 rows failed
    Check that `email` has no null values.
...
Metrics:
...
customers.email.null_count = 1
    Number of nulls in email
...
```

Here you can see that `email__is_not_null` failed because the `null_count` metric of `customers.email` is 1.

`info.checks` and `info.metrics` are relations over the rows that the run wrote, so you can read them as a data frame, an Arrow table or a list of tuples:

```py notype
info.checks.df()[["table_name", "check_qualified_name", "outcome", "check_value"]]
```

```text
  table_name                check_qualified_name outcome  check_value
0  customers                  email__is_not_null    fail            1
1  customers                    email__is_unique    pass            0
...
```

### Add checks to an existing resource

You cannot put a decorator on a resource that you did not write, for example a table of the `sql_database` source or an endpoint of `rest_api`. For such resources, call `dq.with_checks` as a function and pass the resource as the first argument:

```py notype
from dlt.sources.sql_database import sql_database

source = sql_database(table_names=["customers", "orders"])
dq.with_checks(
    source.resources["orders"],
    dq.checks.is_not_null("customer_id"),
    dq.checks.is_in("payment_method", ["card", "cash", "voucher"]),
)

pipeline.run(source)
dq.run(pipeline)
```

Here we take the `orders` table from the resources of the source and add two checks to it. `dq.with_checks` modifies the resource in place. When the pipeline runs, the checks are stored in the schema exactly as if you declared them with the decorator.

`with_checks` accepts resources, transformers and transformations. Checks are evaluated on tables, so `with_checks` on a source raises an error.

### Run checks on a dataset

`dq.run` also accepts a `dlt.Dataset`. This lets you run checks independently of the pipeline run that loaded the data: on a schedule, in a notebook, or from a job that has no access to the source:

```py notype
pipeline = dlt.pipeline("shop", destination="duckdb")
dq.run(pipeline.dataset())
```

Here we create the `shop` pipeline again, with the same name, destination and dataset name, only to get its dataset. Nothing is extracted or loaded. dlt restores the schemas of the pipeline from the destination, so the script also works in a job or on a machine that never ran the pipeline. `dq.run` finds the declared checks in the schema of the dataset, so the result is the same as with the pipeline object.

`dlt.attach("shop")` needs the local working folder of the pipeline. Use it only in a script that runs where the pipeline ran, for example later in the same job.

`dq.run` loads the results with an internal pipeline. If you need control over that pipeline, pass your own in `results_pipeline=` or run the data quality source yourself, see [run the data quality source with your own pipeline](./advanced.md#run-the-data-quality-source-with-your-own-pipeline).

:::note
`dq.run_checks()`, `dq.run_metrics()`, `dq.data_quality_checks()` and `dq.data_quality_metrics()` are deprecated. They compute metrics and checks in separate runs. Use `dq.run()` or the `dq.data_quality_source()` source.
:::

## Checks

### Available checks

All built-in checks are in the `dq.checks` module:

| Check                                          | The check passes when                                                                           |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `is_not_null("col")`                           | No row has a null in `col`                                                                      |
| `is_unique("col")`                             | No value of `col` is in more than one row. Nulls are ignored                                    |
| `is_primary_key("col")`                        | `col` has no nulls and no duplicates                                                            |
| `is_primary_key(["col_a", "col_b"])`           | The compound key has no nulls and no duplicates                                                 |
| `is_in("col", ["a", "b"])`                     | Each value of `col` is in the list. Add `None` to the list to accept nulls                      |
| `case("col > 0", name="col_positive")`         | The SQL condition is true for each row                                                          |
| `freshness("col", max_age=timedelta(hours=1))` | The latest value of `col` is not older than `max_age`. See [Freshness check](#freshness-check)  |
| `references()`                                 | Each key of a reference has a match in the other table. See [Reference check](#reference-check) |

`is_in` compares values with the column type, so you can pass dates, timestamps (timezone-aware or naive) and decimals. `case` conditions are SQL in the dialect of the destination. The default name of a `case` check is made of the columns in the condition and a hash of the condition, for example `col__case__1a2b3c4d`. Pass `name` to choose a readable one.

`true_is_success=False` turns `is_in` and `case` around: rows with a listed value fail, and rows for which the condition is true fail.

### Metrics behind the built-in checks

Each built-in check is evaluated on the metrics below. You meet these names in the report with `verbosity=1` and in the stored results:

| Check                                       | Metrics                                                                                       |
| ------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `is_not_null(col)`                          | `null_count(col)`                                                                             |
| `is_unique(col)`                            | `duplicate_count(col)`                                                                        |
| `is_primary_key(col)`                       | `duplicate_count(col)`, `null_count(col)`                                                     |
| `is_primary_key([col_a, col_b])`            | table `duplicate_count([col_a, col_b])`, table `null_count([col_a, col_b])`                   |
| `is_in(col, values)`                        | `invalid_count(col, valid_values=values)`, and `null_count(col)` unless `None` is in `values` |
| `is_in(col, values, true_is_success=False)` | `invalid_count(col, invalid_values=values)`, `null_count(col)`                                |
| `case(condition)`                           | table `failed_rows(condition)`, stored as `failed_rows__<check name>`                         |
| `references(...)`                           | table `unmatched_count(columns, other_table, other_columns)` per checked reference            |
| `freshness(col)`                            | `maximum(col)`. The check passes when the age of the latest value is not above `max_age`      |

The result of a row check is the sum of its metrics. `dq.run` stores each metric in the same load as the check results, and a metric that several checks use is computed and stored once. [Results tables](#results-tables) shows how a check result points to its metric values.

### Reference check

`references` checks the `references` table hints: keys of one table must have a match in another table. Each reference has a cardinality `X_to_Y`, where X is the number of rows of the table that declares it per referenced row and Y the number of referenced rows per row of that table. An end `one` means exactly one, so the rows on the other end must have a match. `zero` (at most one) and `many` (any number) require nothing:

- `many_to_one`, the default: every row of the declaring table has a referenced row. dlt's nested tables relate to their parents this way.
- `one_to_many`: every referenced row has a row in the declaring table.
- `one_to_one`: both.

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


@dq.with_checks(dq.checks.references())
@dlt.resource(
    references=[
        {
            "columns": ["customer_id"],
            "referenced_table": "customers",
            "referenced_columns": ["id"],
            "cardinality": "many_to_one",
        }
    ]
)
def orders():
    yield [{"id": 1, "customer_id": 1}, {"id": 2, "customer_id": 7}]
```

Each direction runs as a check on the table whose rows it checks, and its result is stored there, named `<columns>__references__<other table>`: above, `customer_id__references__customers` on `orders` fails for the order of customer 7. Keys with a null are not checked. The metric `unmatched_count` counts the rows without a match, in a query of its own that reads the other table.

`references()` selects the references declared on the table, and `references(foreign=True)` the references that other tables declare to it. Pass columns to select only references made of them, for example `references(["customer_id"])`. The same reference selected on both tables runs once. Checks that select no reference, or only references that require no match, raise an error. dlt keeps one reference per pair of tables.

### Freshness check

`freshness` checks that the latest value of a `timestamp` or `date` column is not older than `max_age`. Pass `max_age` as a `timedelta` or as a number of seconds. The age is measured at a reference time:

- `reference="load_package_timestamp"` (default): the creation time of the latest load of the schema of the table, `checked_load_id`. Freshness reflects the data as it was when it was loaded, regardless of when you run the check.
- `reference="now"`: the time the check runs.

```py notype
from datetime import timedelta

import dlt
from dlt.hub import data_quality as dq

pipeline = dlt.pipeline("shop", destination="duckdb")
dq.run(
    pipeline,
    checks={
        "orders": [
            dq.checks.freshness("updated_at", max_age=timedelta(days=1)),
            dq.checks.freshness(
                "updated_at", max_age=timedelta(hours=1), reference="now", name="orders_recent"
            ),
        ],
    },
)
```

Here the first check accepts orders that were at most one day old when they were loaded. The second one is stricter and measures against the current time, so it starts to fail when the pipeline stops running. It gets a `name` because two freshness checks on the same column would otherwise share one.

The check stores the age in seconds in `check_value` and `max_age` in seconds in `threshold`:

```text
[fail] orders.orders_recent: 7202.839742, threshold 3600.0
```

An empty table fails the check. Naive timestamps are read as UTC. A freshness check has no result per row, so it can't be used with `CheckSuite.get_failures()`. It needs a `timestamp` or `date` column: on any other column `dq.run` raises before it computes anything.

### Add checks at run time

Not every check belongs to a resource. You may want to try a check before you add it to your code, run stricter checks in one environment, or check a table whose resource you cannot change. For these cases, pass checks to `dq.run` in the `checks=` argument, as a mapping of table names to lists of checks:

```py notype
info = dq.run(
    pipeline,
    checks={
        "orders": [
            dq.checks.case("amount > 0", name="amount_positive"),
            dq.checks.is_unique("id"),
        ],
    },
)
print(info)
```

```text
Data quality results of 8 check(s) in dataset shop_dataset, 3 failed
...
[pass] orders.amount_positive: 0 of 3 rows failed
[pass] orders.customer_id__is_not_null: 0 of 3 rows failed
[pass] orders.id__is_unique: 0 of 3 rows failed
...
```

The two new checks ran together with the six declared ones and appear in the same report. A check that you pass at run time replaces a declared check with the same name. It is not stored in the schema, so the next run without `checks=` does not include it.

The following arguments of `dq.run` select what a run computes:

| Argument                            | Effect                                                                                    |
| ----------------------------------- | ----------------------------------------------------------------------------------------- |
| `checks={...}`                      | Adds checks for this run                                                                  |
| `include_registered=False`          | Leaves out the checks and metrics that you declared with `with_checks` and `with_metrics` |
| `include_metrics=False`             | Leaves out the declared metrics. The metrics that the checks use are still stored         |
| `include_checks=False`              | Runs no checks and computes the declared metrics only                                     |
| `include_schema_derived_hints=True` | Adds the checks [derived from schema hints](#derive-checks-from-schema-hints)             |

For example, you can run a single check and nothing else:

```py notype
dq.run(
    pipeline,
    checks={"orders": [dq.checks.case("amount > 0", name="amount_positive")]},
    include_registered=False,
)
```

When a run has nothing to compute, `dq.run` warns and returns an empty checks info.

### Derive checks from schema hints

Your schema often states already what correct data looks like: primary keys, unique columns, columns that are not nullable, references between tables. Most warehouses do not enforce keys and references, so nothing tells you when the data violates them. Instead of repeating each hint as a check, you can let dlt derive the checks with `include_schema_derived_hints=True`:

```py notype
info = dq.run(pipeline, include_schema_derived_hints=True)
print(info)
```

```text
Data quality results of 8 check(s) in dataset shop_dataset, 3 failed
...
[pass] customers.id__is_not_null: 0 of 3 rows failed
[pass] customers.is_primary_key__id: 0 of 3 rows failed
...
```

Here the `customers` resource declares `primary_key="id"`, so dlt derived `id__is_not_null` and `is_primary_key__id`. The reference on `orders` would give the same check that `references()` declares already, so that check runs once.

dlt derives checks from the following hints:

| Hint             | Check                                                                                     |
| ---------------- | ----------------------------------------------------------------------------------------- |
| `nullable=False` | `is_not_null(col)`                                                                        |
| `unique=True`    | `is_unique(col)`                                                                          |
| `primary_key`    | `is_primary_key(columns)`, and `is_not_null` of each column, which dlt makes not nullable |
| `references`     | `references(columns)`, when the cardinality requires a match                              |

Derived checks run together with the declared checks and the checks that you pass. A declared or passed check replaces the derived check with the same qualified name. dlt skips columns that received no data, and references to tables that are in another schema or received no data. Derived checks are opt-in: `dq.run` does not run them by default.

### Write your own check

Built-in checks are classes, and you can write your own with the same base classes: a check on the value of any metric with your own threshold, or a row check with a metric that you define in SQL. You pass a custom check in `checks=`, like any other check. See [custom checks and metrics](./advanced.md#custom-checks-and-metrics).

## Find the rows that failed

A check result tells you how many rows failed, but not which ones. `dq.run` does not store the rows. To inspect them, use `dq.CheckSuite`. It takes the same check objects and, instead of counting rows, selects the rows that fail or pass a check:

```py notype
suite = dq.CheckSuite(
    pipeline.dataset(),
    checks={
        "orders": [
            dq.checks.is_in("payment_method", ["card", "cash", "voucher"]),
            dq.checks.references(),
        ]
    },
)

failures = suite.get_failures("orders", "payment_method__is_in")
failures.df()[["id", "customer_id", "amount", "payment_method"]]
```

```text
   id  customer_id  amount payment_method
0   3            7    14.5         crypto
```

Here we create a suite with two of the checks from the `orders` resource and ask for the rows that fail the `is_in` check. The answer is order 3 with its `crypto` payment method.

`get_failures` and `get_successes` take the table and the name of the check as the report prints it. Both return a `dlt.Relation`, so the rows stay on the destination until you read them, and you can filter or join them further:

```py notype
# the rows of `orders` without a customer
suite.get_failures("orders", "customer_id__references__customers").df()
# the rows that passed a check
suite.get_successes("orders", "payment_method__is_in").df()
```

For `is_unique` and `is_primary_key`, the first copy of a value passes and the extra copies fail. If the table has `_dlt_load_id` and `_dlt_id`, the first copy is the row that dlt loaded first. To find these rows, `CheckSuite` uses a window function over the table, which `dq.run` avoids.

`CheckSuite` does not write to `_dlt_checks`, so dashboards and `read_check` do not see its results. A value check such as `freshness` has no rows to return. Pick the pattern that matches your goal:

| Pattern                                                  | Stores results | Best for                                            |
| -------------------------------------------------------- | -------------- | --------------------------------------------------- |
| `dq.run(pipeline, checks={...})`                         | Yes            | Scheduled jobs, monitoring history, dashboards      |
| `dq.CheckSuite(dataset, checks={...}).get_failures(...)` | No             | Notebooks, debugging the rows behind a failed check |

## Metrics

Checks tell you whether the data is acceptable. Metrics tell you what the data looks like and how it changes: how many rows a table has, what the mean order amount is, how many distinct customers placed an order. You declare a metric when you want to track a value over time, also when no check depends on it.

Because every check is evaluated on metrics, a run with checks stores metrics already. For example, `is_not_null("email")` stores the `null_count` of `email` on each run. You do not have to declare those metrics again.

### Declare metrics on your resources

You declare metrics with the `@dq.with_metrics` decorator, in the same way as checks. Column and table metrics come from `dq.metrics.column` and `dq.metrics.table`, and both decorators can be used on one resource:

```py notype
@dq.with_metrics(
    dq.metrics.column.mean("amount"),
    dq.metrics.column.maximum("amount"),
    dq.metrics.table.row_count(),
)
@dq.with_checks(
    dq.checks.is_not_null("customer_id"),
)
@dlt.resource
def orders():
    yield from [...]
```

Here we track the mean and the maximum of `amount` and the number of rows of the `orders` table, next to a check on the same resource.

A dataset metric describes all tables of a source, so you declare it on the source. Dataset metrics come from `dq.metrics.dataset`:

```py notype
@dq.with_metrics(dq.metrics.dataset.total_row_count())
@dlt.source
def shop():
    return customers, orders
```

Metrics are computed by the same `dq.run` that runs the checks. The metrics report shows the metrics that you declared together with the metrics of the checks:

```py notype
pipeline.run(shop())
info = dq.run(pipeline)
print(info.metrics_report())
```

```text
total_row_count = 6
customers.row_count = 3
...
orders.amount.maximum = 80.5
orders.amount.mean = 40.0
orders.customer_id.null_count = 0
...
```

Here `total_row_count`, `orders.amount.maximum` and `orders.amount.mean` are the declared metrics. `orders.customer_id.null_count` was not declared: it is there because the `is_not_null("customer_id")` check needs it.

For resources that you did not write, call `dq.with_metrics` as a function and pass the resource as the first argument, as you do with [checks](#add-checks-to-an-existing-resource):

```py notype
from dlt.sources.sql_database import sql_database

source = sql_database(table_names=["customers", "orders"])
dq.with_metrics(
    source.resources["orders"],
    dq.metrics.column.mean("amount"),
    dq.metrics.table.row_count(),
)
```

### Available metrics

Built-in metrics are grouped by the level that they describe:

| Level   | Module               | Examples                                                                                      |
| ------- | -------------------- | --------------------------------------------------------------------------------------------- |
| Column  | `dq.metrics.column`  | `mean`, `minimum`, `maximum`, `median`, `quantile`, `null_count`, `null_rate`, `unique_count` |
| Table   | `dq.metrics.table`   | `row_count`, `unique_count`, `duplicate_count`, `null_row_count`                              |
| Dataset | `dq.metrics.dataset` | `total_row_count`, `load_row_count`, `latest_loaded_at`                                       |

[Built-in metrics](./advanced.md#built-in-metrics) lists all of them with their arguments. If none fits, you can [write a metric of your own](./advanced.md#custom-checks-and-metrics).

A metric with arguments is stored under its qualified name, for example `quantile__0.95` or `duplicate_count__col_a__col_b`, so that several variants of a metric on the same column keep separate histories.

### Add metrics at run time

As with checks, you can pass metrics to `dq.run` without declaring them. `metrics=` takes column and table metrics as a mapping of table names to lists of metrics, and `dataset_metrics=` takes a list of dataset metrics:

```py notype
info = dq.run(
    pipeline,
    metrics={"orders": [dq.metrics.column.quantile("amount", quantile=0.95)]},
    dataset_metrics=[dq.metrics.dataset.latest_loaded_at()],
    include_checks=False,
)
print(info.metrics_report())
```

```text
latest_loaded_at = 2026-11-26 22:33:39.061873+00:00
total_row_count = 6
orders.row_count = 3
orders.amount.maximum = 80.5
orders.amount.mean = 40.0
orders.amount.quantile__0.95 = 74.94999999999999
```

Here we add the 95th percentile of `amount` and the time of the latest load to the declared metrics. We also pass `include_checks=False`, so this run computes metrics only and the metrics of the checks are not in the report.

A metric that you pass replaces the declared metric with the same qualified name.

## Read stored results

Each `dq.run` appends its results to the dataset and nothing is overwritten, so the dataset holds the full history of your checks and metrics. You read it with `dq.read_check`, `dq.read_metric` and `dq.read_metrics`. All three return a `dlt.Relation` with the newest results first.

### Read the results of the last run

When you have the `DataQualityInfo` of a run, `info.checks` and `info.metrics` give you its results. In a later job you do not have that object. Each run writes its results as one load of the `_dlt_data_quality` schema, so you can ask the dataset for the latest load of this schema and pass its id to the readers:

```py notype
dataset = pipeline.dataset()
last_load_id = dataset.latest_load_id(schema_name="_dlt_data_quality")

checks = dq.read_check(dataset, load_ids=[last_load_id]).df()
checks[["table_name", "check_qualified_name", "outcome", "check_value", "threshold"]]
```

```text
  table_name                check_qualified_name outcome  check_value threshold
0  customers                  email__is_not_null    fail            1         0
1  customers                    email__is_unique    pass            0         0
...
```

Here `checks` holds one row for each check of the last run. A downstream job can act on these rows, for example stop when a check failed:

```py notype
failed = checks[checks["outcome"] == "fail"]["check_qualified_name"].tolist()
if failed:
    raise RuntimeError(f"data quality checks failed: {failed}")
```

`read_metrics` returns all metric values of the run in the same way:

```py notype
metrics = dq.read_metrics(dataset, load_ids=[last_load_id]).df()
metrics[["level", "table_name", "column_name", "metric_name", "metric_value"]]
```

### Read the history of a check

Without `load_ids`, `read_check` returns the results of all runs. Pass `table` to read the checks of one table, then select the check that you are interested in:

```py notype
history = dq.read_check(dataset, table="orders").df()
history = history[history["check_qualified_name"] == "payment_method__is_in"]
history[["_dlt_load_id", "loaded_at", "outcome", "check_value", "success_rate"]]
```

```text
         _dlt_load_id                        loaded_at outcome check_value  success_rate
2  1795732420.2367115 2026-11-26 22:33:40.449044+00:00    fail           1      0.666667
6  1795732419.1150498 2026-11-26 22:33:39.324829+00:00    fail           1      0.666667
```

Here each row is the result of `payment_method__is_in` in one run, and the first row is the most recent one. To read all checks of one column, select the names that start with `<column>__`.

### Read the history of a metric

`read_metric` returns the values of one metric: a metric that you declared with `with_metrics`, a metric of a check or a metric that you passed to `dq.run`. Pass the table, the column and the name of the metric:

```py notype
mean_amount = dq.read_metric(
    dataset, table="orders", column="amount", metric="mean"
).df()
mean_amount[["_dlt_load_id", "metric_name", "metric_value"]]
```

```text
         _dlt_load_id metric_name  metric_value
0  1795732420.2367115        mean          40.0
1  1795732419.8061068        mean          40.0
```

The first row is the most recent value, so `mean_amount["metric_value"].iloc[0]` is the current mean. For a table metric, leave out `column`. For a dataset metric, leave out `table` and `column`:

```py notype
dq.read_metric(dataset, table="orders", metric="row_count").fetchall()
dq.read_metric(dataset, metric="total_row_count").arrow()
```

`read_metric` accepts the qualified name of a metric, or a name that only one qualified name starts with. For example `invalid_count` finds the `invalid_count__2f351bc0` of an `is_in` check. If a column has several quantiles, use the qualified name, for example `quantile__0.95`. When no stored metric matches, or several do, the error lists the stored names.

```py notype
# the metric of an `is_not_null("email")` check
email_nulls = dq.read_metric(
    dataset, table="customers", column="email", metric="null_count"
).df()
```

With the history of a metric you can derive values that depend on earlier loads, for example to detect a load that added far fewer rows than usual. See [derive stateful metrics from the history](./advanced.md#derive-stateful-metrics-from-the-history).

### Results tables

The results live in two tables of the dataset. Each row carries the `_dlt_load_id` of the load that wrote it, which ties the rows of one run together and to the `_dlt_loads` table:

```mermaid
erDiagram
    "_dlt_loads" ||--o{ "_dlt_checks" : "load_id = _dlt_load_id"
    "_dlt_loads" ||--o{ "_dlt_dq_metrics" : "load_id = _dlt_load_id"
    "_dlt_dq_metrics" ||--o{ "_dlt_checks" : "_dlt_load_id and metric_id"
    "_dlt_loads" {
        text load_id PK
        text schema_name
        timestamp inserted_at
    }
    "_dlt_checks" {
        text _dlt_load_id FK
        text table_name
        text check_qualified_name
        text outcome
        text check_value
        text threshold
        text metric_id FK
        text check_id
        text checked_load_id
    }
    "_dlt_dq_metrics" {
        text _dlt_load_id FK
        text level
        text table_name
        text column_name
        text metric_name
        bigint metric_value
        text metric_id
        text checked_load_id
    }
```

`_dlt_checks` has one row for each check in each run:

| Column                                       | Content                                                                     |
| -------------------------------------------- | --------------------------------------------------------------------------- |
| `_dlt_load_id`                               | The load that wrote the result                                              |
| `table_name`                                 | The table that the check reads                                              |
| `check_qualified_name`                       | The name of the check, for example `payment_method__is_in`                  |
| `outcome`                                    | `pass` or `fail`                                                            |
| `check_value`, `threshold`                   | The value that the check decided on, and its limit. Both are stored as text |
| `check_data_type`                            | The dlt data type of `check_value` and `threshold`                          |
| `row_count`, `success_count`, `success_rate` | The rows of the table, the rows that passed, and their share                |
| `metric_id`, `metric_ids`                    | The metric values that the check used                                       |
| `check_id`                                   | Identifies the check in all runs: its schema, table and name                |
| `checked_load_id`                            | The latest load of the data at the start of the run                         |
| `schema_name`                                | The schema of the table                                                     |
| `check_description`                          | The description of the check and its arguments                              |

`_dlt_dq_metrics` has one row for each metric value in each run:

| Column                                   | Content                                                                          |
| ---------------------------------------- | -------------------------------------------------------------------------------- |
| `_dlt_load_id`                           | The load that wrote the value                                                    |
| `level`                                  | `column`, `table` or `dataset`                                                   |
| `table_name`, `column_name`              | The table and the column of the metric. Null where the level has none            |
| `metric_name`                            | The qualified name of the metric, for example `null_count` or `quantile__0.95`   |
| `metric_value`, `metric_value__v_<type>` | The value, in the column of its data type                                        |
| `metric_id`                              | Identifies the metric in all runs: its schema, table, column, name and arguments |
| `checked_load_id`                        | The latest load of the data at the start of the run                              |
| `schema_name`                            | The schema of the table                                                          |
| `metric_description`                     | The description of the metric                                                    |
| `metric_data_type`                       | The dlt data type of the value. It names the column that holds the value         |

The readers add `loaded_at`, the time of the load. New columns are added at the end, so code that reads columns by position keeps working.

Some columns deserve a longer explanation:

- **`checked_load_id`** is the latest load of the schema of the table at the start of the run. Metrics and checks always read all rows of a table, so `checked_load_id` does not select rows. It tells which version of the data a result describes.
- **Metric values** keep their data type. Integers are stored in `metric_value` and other types in `metric_value__v_<type>`, for example `metric_value__v_double` or `metric_value__v_timestamp`. `read_metric` returns them as one `metric_value` column.
- **`check_value` and `threshold`** are text, so that decimals and timestamps keep their exact value. `coerce_value(check_data_type, "text", value)` from `dlt.common.data_types.type_helpers` converts them back.
- **`success_count`** is set for row checks. **`success_rate`** is the share of rows that passed, and 1 for a table without rows. For a value check such as `freshness`, a passed check gives 1 and a failed check gives 0.
- **`metric_id`** of a check result points to the first metric that the check used. If the check used several metrics, **`metric_ids`** is a JSON array of all of them, otherwise it is null.
- **`check_id`** does not include the threshold, so a check keeps its history when you change its threshold.

To get the metric value behind each check result, join the two tables on `_dlt_load_id` and `metric_id`:

```py notype
checks = dq.read_check(dataset, load_ids=[last_load_id]).df()
metrics = dq.read_metrics(dataset, load_ids=[last_load_id]).df()

joined = checks.merge(metrics, on=["_dlt_load_id", "metric_id"], suffixes=("", "_metric"))
joined[["check_qualified_name", "outcome", "metric_name", "metric_value"]]
```

```text
                 check_qualified_name outcome                              metric_name  metric_value
0                  email__is_not_null    fail                               null_count             1
1                    email__is_unique    pass                          duplicate_count             0
...
```

Here each check result is paired with the metric that it was evaluated on: `email__is_not_null` failed on a `null_count` of 1, while `email__is_unique` passed on a `duplicate_count` of 0.

:::note
Results tables that an earlier version of dlthub wrote do not have all columns. The readers raise `dq.DataQualityResultsOutdated` until one `dq.run` adds the columns.
:::

### Several sources in one dataset

Several pipelines or sources can load into one dataset, each with its own schema. `pipeline.dataset()` holds the schemas of all sources the pipeline loaded, and `dq.run(pipeline)` checks each of them on its own: its registered and derived checks, its metrics and its dataset metrics. Pass `pipeline.dataset(schema="crm")` to check one source only.

Results of all schemas are stored in the same `_dlt_dq_metrics` and `_dlt_checks` tables. Each row records the schema of the checked table in `schema_name`, and the latest load of that schema in `checked_load_id`.

Checks and metrics passed in `checks=` and `metrics=` go to the first schema with the table, the default schema of the pipeline first, and `dataset_metrics=` to the default schema. References between tables of different schemas are not checked.

`read_metric` and `read_check` return results of the schemas of the dataset you pass, and results stored by earlier versions that do not record a schema. Pass `schema_names=` to read results of other schemas stored in the dataset, for example of other pipelines:

```py notype
# results of all sources of the pipeline
pipeline_checks = dq.read_check(pipeline.dataset())
# results of the `crm` source only
crm_checks = dq.read_check(pipeline.dataset(schema="crm"))
# results of the `billing` schema that another pipeline stored in the dataset
billing_checks = dq.read_check(pipeline.dataset(), schema_names=["billing"])
```

Dataset-level metrics, for example `total_row_count`, are computed on the tables of one schema, so each source has its own values.

## Roadmap

- Thresholds on any metric (for example, `null_rate` below 0.1). Checks are already evaluated on metrics, starting with `freshness`.
- Support user-defined group-by metrics
- Support completely custom checks via `@dlt.hub.transformation` (for example, SQL, SQLGlot, Ibis, Narwhals, Polars)
- Trigger actions based on check result or outcome (for example, send Slack notification)
- Track metrics and checks changes via `dlt.Schema` versioning
