Data Quality & Validation — Data Engineering

Data quality is measured per dimension: completeness, validity (follows the format and rules), accuracy, consistency, timeliness, uniqueness. One check = one…

Since the first lesson, Bookshop's three dirty rows (the doubled item 9, Maya's empty city, the 190 price) have been cleaned in the transform, because we know where they are. Tomorrow a fourth dirty row may turn up that you've never seen. That's what data quality validation is for: checking data against clear rules before anyone uses it, then deciding what happens when a rule is broken. It works like the person who receives goods at a minimarket's warehouse. When a truck arrives, they match the number of boxes against the delivery note and check expiry dates, price labels and goods delivered twice. Anything odd goes onto the returns shelf; the rest goes onto the racks. If the truck arrives empty, they stop receiving and call the sender. Bookshop's pipeline needs the same person: the checks, a returns shelf called quarantine, and a stop button.

Six dimensions of data quality

Each check measures one dimension of data quality:

Dimension Its question At Bookshop
Completeness is all the expected data there? Maya's city is NULL; raw row count = source
Validity do the values follow the format and rules? a price must be between 1 and 100
Accuracy are the values true to reality? $18 for a $19 book passes validity, yet it is still wrong
Consistency does the data agree across tables and systems? every book_id in an order exists in books
Timeliness is the data recent enough? the newest order is no older than 24 hours
Uniqueness is anything doubled? each order and book pair appears once

Validity is the one checked most often: values that follow the format and rules. Accuracy is harder, because it needs a source of truth to compare with, such as the catalogue.

A check is a query that looks for offenders

The simplest way to write a check: one SELECT that looks for rows that break the rule. It passes when the result is 0 rows. Everything below runs in SQLite (the same as the Lab and the Playground) on raw_order_lines, the 19 raw rows from the ETL lesson.

-- unique: one row per (order_id, book_id) pair
SELECT item_id, order_id, book_id, qty
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY item_id) AS rn
      FROM raw_order_lines)
WHERE rn > 1;
-- 9 | 6 | 2 | 2

-- not_null: the city must be filled in
SELECT item_id, customer, city FROM raw_order_lines WHERE city IS NULL;
-- 11 | Maya Sari | NULL
-- 19 | Maya Sari | NULL

-- accepted range: a sensible price
SELECT item_id, title, price FROM raw_order_lines
WHERE price NOT BETWEEN 1 AND 100;
-- 16 | The Dancer | 190

Three checks, three dirty rows caught. What if the unique check sits on item_id instead? The result is 0 rows: it passes. The retried job saved its copy with a new id (9), so item_id really is unique. A unique check must use the business key, the columns that really must not repeat in the real world: one book in one order.

Three more checks, and all three pass on today's data:

Check The query looks for Result
relationships order_items whose book_id is not in books (LEFT JOIN ... WHERE b.id IS NULL) 0 rows
row count a source row count that differs from raw 19 = 19
freshness a newest order older than 24 hours checked Saturday 06:00: 19.5 hours

A check that passes still earns its place. raw_order_lines is built with a JOIN to books. If one day an admin deletes The Dancer from the catalogue, that JOIN silently drops its 4 order lines: relationships finds 4 offenders, and row count becomes 19 against 15. Freshness can change without anything breaking, too: checked on Monday at 06:00, the newest order (Friday 10:30) is 67.5 hours old.

Where checks run

models:
  - name: raw_order_lines
    data_tests:
      - dbt_utils.unique_combination_of_columns:
          arguments:
            combination_of_columns: [order_id, book_id]
    columns:
      - name: city
        data_tests:
          - not_null:
              config:
                severity: warn
      - name: price
        data_tests:
          - dbt_utils.accepted_range:
              arguments:
                min_value: 1
                max_value: 100
import great_expectations as gx
import pandas as pd

df = pd.read_csv("order_lines.csv")

context = gx.get_context(mode="ephemeral")
batch = (
    context.data_sources.add_pandas("bookshop")
    .add_dataframe_asset("order_lines")
    .add_batch_definition_whole_dataframe("all_rows")
    .get_batch(batch_parameters={"dataframe": df})
)

suite = gx.ExpectationSuite(name="order_lines")
suite.add_expectation(gx.expectations.ExpectCompoundColumnsToBeUnique(column_list=["order_id", "book_id"]))
suite.add_expectation(gx.expectations.ExpectColumnValuesToNotBeNull(column="city"))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(column="price", min_value=1, max_value=100))

result = batch.validate(suite)
print(result.success)
for r in result.results:
    print(r.expectation_config.type, r.success, r.result["unexpected_count"])
False
expect_compound_columns_to_be_unique False 2
expect_column_values_to_not_be_null False 2
expect_column_values_to_be_between False 1

When a check fails: stop or quarantine

Each check gets a severity. error means the data may not pass; warn means record it and tell someone, but carry on. Maya's NULL city is a warn: her sales are real, and the city is filled in as Unknown. The duplicate and the 190 price are errors. For an error check there are two choices:

CREATE TABLE quarantine AS
SELECT item_id, order_id, book_id, qty, price, 'unique' AS failed_check
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY item_id) AS rn
      FROM raw_order_lines)
WHERE rn > 1
UNION ALL
SELECT item_id, order_id, book_id, qty, price, 'accepted_range'
FROM raw_order_lines
WHERE price NOT BETWEEN 1 AND 100;

Then sales is built from raw_order_lines with WHERE item_id NOT IN (SELECT item_id FROM quarantine). The result: 2 rows in quarantine (items 9 and 16), 17 rows in sales, and a reconciliation check: 19 raw rows = 17 + 2, nothing lost silently. The price: the owner's report is 1 book short (Rizky's order) until someone fixes item 16. When the fix is certain, like the catalogue price in the ETL lesson, just fix it in the transform. Quarantine is for what can't be fixed automatically.

⚠️ Checks that fool you, alarms that get ignored

TL;DR: Data quality is measured per dimension: completeness, validity (follows the format and rules), accuracy, consistency, timeliness, uniqueness. One check = one SELECT that looks for offenders; it passes at 0 rows. At Bookshop: unique on the business key (order_id, book_id) catches item 9 (unique on item_id passes instead), not_null catches Maya's 2 rows, an accepted range of 1 to 100 catches item 16; relationships, row count (19 = 19) and freshness pass today. Checks run as a gate on load, as dbt tests (unique, not_null, accepted_values, relationships), or with Great Expectations (Expectations such as ExpectColumnValuesToBeBetween) and Soda Core. On failure: severity warn carries on and tells someone, error stops the pipeline or moves the rows to quarantine, then checks that raw = sales + quarantine (19 = 17 + 2).

⚡ A check is a query that looks for offenders

Write:

SELECT item_id, customer, city FROM raw_order_lines WHERE city IS NULL;

Meaning: One check = one SELECT that looks for rows that break the rule. It passes when the result is 0 rows. This one finds Maya's 2 rows.

⚡ Unique on the business key

Guess first: the unique check sits on item_id. Is the doubled item 9 caught?

No, the check passes. The retried job saved its copy with a new id (9), so item_id really is unique. A unique check must use the business key: (order_id, book_id).

Meaning: The business key is the columns that really must not repeat in the real world: one book in one order.

⚡ Expectations

Write:

suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(column="price", min_value=1, max_value=100))

Meaning: In Great Expectations, an Expectation is a declarative rule checked against the data, such as "values must be between X and Y". The result is a validation report you can use as a gate in the pipeline.

⚡ Warn, error, quarantine

Meaning: Severity warn means record it, tell someone, and carry on, like Maya's empty city. error means stop the pipeline, or move the rows to quarantine. Then reconcile: 19 raw rows = 17 + 2.

What you will learn