The catalog from the previous lesson says what data exists, what it means and where it comes from, but not whether it is correct. And at DataCorp there are reasons for doubt: Laura has found the city "Valencia" spelled four different ways, customers who seem to have been registered twice and the odd order whose amount does not match the sum of its lines. As long as that is not measured, every figure in a report will carry the same question behind it: "are we sure this is right?".
Data quality is the degree to which data is fit for the use it is intended for. In this lesson we will see which dimensions it breaks down into, how to find out the real state of a dataset through profiling, how to turn expectations into rules that check themselves, at which points of the flow to validate and what to do when a check fails, how to clean and standardize, and how to measure quality in order to improve it continuously.
What quality is and what its dimensions are
The classic definition is that data has quality if it is fit for use. It is a relative definition: an incomplete postal address is irrelevant for calculating net sales by city, but unacceptable for shipping a parcel. That is why quality is always defined with respect to a use, and it is defined by business people, not by the technical team.
To be able to measure it, it is broken down into dimensions:
| Dimension | Question | Example of a defect at DataCorp |
|---|---|---|
| Accuracy | Does the data reflect reality? | A customer from Girona is recorded with the city "Gerona, Italy" |
| Completeness | Is all the expected data there? | Customers without city; a day with half of its orders |
| Consistency | Is the data free of contradictions? | total_amount different from the sum of the order's lines |
| Uniqueness | Does each entity appear only once? | The same customer registered twice |
| Validity | Does the data respect the format and the allowed values? | status = 'delivred'; an email without @ |
| Timeliness (freshness) | Is the data available when it is needed? | Yesterday's sales arrive at 10:00 and RQ-04 requires 07:00 |
| Integrity | Are the relationships between data preserved? | An order line whose product_id does not exist in products |
Two useful nuances. Accuracy is the hardest to check, because it requires comparing with reality or with a trusted source; the others can be verified by looking at the data alone. And a piece of data can be valid without being accurate: "Seville" is a valid city, but it is not accurate if the customer lives in Bilbao.
Data profiling
Before writing rules you have to know what the data is really like. Data profiling is the systematic examination of a dataset to describe its content: how many rows it has, how many nulls, how many distinct values, which minimums and maximums, which values are repeated. It is done on the platform's raw copy, never on production (RQ-07).
Profiling with SQL
SELECT
COUNT(*) AS total_rows,
COUNT(DISTINCT customer_id) AS distinct_ids,
COUNT(*) - COUNT(email) AS null_emails,
COUNT(DISTINCT LOWER(TRIM(email))) AS distinct_normalized_emails,
COUNT(*) - COUNT(city) AS null_cities,
COUNT(DISTINCT city) AS distinct_cities,
MIN(signup_date) AS first_signup,
MAX(signup_date) AS last_signup
FROM raw.customers;Each expression addresses one dimension:
COUNT(*)counts rows andCOUNT(column)counts only those that are not null, so their difference is the number of nulls (completeness).COUNT(DISTINCT customer_id)must matchtotal_rows; if it does not, there are repeated identifiers (uniqueness).LOWER(TRIM(email))converts the email to lowercase and strips the leading and trailing spaces before counting. PostgreSQL'sUNIQUEconstraint is case-sensitive, so[email protected]and[email protected]coexist as two different customers.MINandMAXgive away impossible values, such as dates in the future.
The result on DataCorp's data:
total_rows | distinct_ids | null_emails | distinct_normalized_emails | null_cities | distinct_cities | first_signup | last_signup 200000 | 200000 | 0 | 199400 | 1840 | 1312 | 1900-01-01 | 2026-11-17
Four findings in a single query: there are about 600 possible duplicate customers (200,000 − 199,400); 1,840 customers without a city (0.92%); 1,312 distinct cities, too many for a store that sells in Spain, which points to spelling variants; and a signup date of 1900, probably a default value from some old migration.
Profiling with pandas
With Python's pandas library, the profile of all the columns is obtained in one go:
import pandas as pd
# Read the raw extract of customers (pandas decompresses the gzip by itself)
customers = pd.read_csv("customers_20261117.csv.gz", parse_dates=["signup_date"])
profile = pd.DataFrame({
"type": customers.dtypes.astype(str), # detected type
"null_pct": (customers.isna().mean() * 100).round(2), # % of nulls
"distinct": customers.nunique(), # distinct values
})
print(profile)
# The 6 most frequent values of 'city', counting nulls as well
print(customers["city"].value_counts(dropna=False).head(6))customers.isna() marks each empty cell with True; .mean() calculates the proportion of True values per column (in Python, True is worth 1 and False is worth 0). value_counts counts how many times each value appears:
Here is Laura's problem in plain sight: Valencia appears in four forms. A report of sales by city would show it in four rows, and the first one would understate the city by 15%.
Profiling does not fix anything: it describes. Its result is the raw material for defining the rules, and it must be shared with the domain steward, who is the one who knows whether a finding is a defect or something normal.
Quality rules
A quality rule is an expectation about the data expressed in such a way that it can be checked automatically and gives an unambiguous result: it either holds or it does not. Every rule needs five elements: what it checks, on which data, with what tolerance threshold, with what severity and who is accountable for it.
Laura, as steward of Sales and of Customers, agrees the first ten with Carmen and Nuria:
| Id | Rule | Dimension | Severity |
|---|---|---|---|
| DQ-01 | order_id is unique in orders |
Uniqueness | Blocking |
| DQ-02 | customer_id, order_date and total_amount are not null |
Completeness | Blocking |
| DQ-03 | status is one of the six allowed values |
Validity | Quarantine |
| DQ-04 | Every order line has an existing order and product | Integrity | Quarantine |
| DQ-05 | total_amount = SUM(quantity × unit_price), with a tolerance of €0.01 |
Consistency | Warning (blocking if more than 0.1% of the orders fail) |
| DQ-06 | Yesterday's orders are loaded before 07:00 | Timeliness | Blocking |
| DQ-07 | The number of orders for the day is between 750 and 4,500 | Completeness | Warning |
| DQ-08 | The net sales in consumption.fact_sales match those calculated on cleansed.orders |
Consistency | Blocking |
| DQ-09 | email has the format of an email address |
Validity | Warning |
| DQ-10 | No two customers have the same normalized email | Uniqueness | Warning |
The meaning of each severity is explained further below. Rule DQ-07 is an example of a volume rule: with an average of 1,500 orders a day, fewer than half suggests an incomplete load, and more than three times as many, a duplication (the upper threshold will have to be raised during campaigns such as Black Friday).
Implementing the rules in SQL and Python
Checks in SQL
The simplest and most widespread pattern is to write each rule as a query that returns the rows that break it. If it returns none, the rule holds.
-- DQ-03: statuses that are not allowed
SELECT order_id, status
FROM cleansed.orders
WHERE status NOT IN ('pending','paid','shipped','delivered','cancelled','returned')
OR status IS NULL;The OR status IS NULL is necessary: in SQL, comparing a null with a list yields neither true nor false, and the row would slip through the check.
Rule DQ-05 tests the assumption from lesson 02-04 (prices with VAT included and no separate shipping costs):
-- DQ-05: the order amount must be the sum of its lines
SELECT
o.order_id,
o.total_amount,
COALESCE(SUM(ol.quantity * ol.unit_price), 0) AS line_sum
FROM cleansed.orders o
LEFT JOIN cleansed.order_lines ol ON ol.order_id = o.order_id
GROUP BY o.order_id, o.total_amount
HAVING ABS(o.total_amount - COALESCE(SUM(ol.quantity * ol.unit_price), 0)) > 0.01;LEFT JOINkeeps the orders with no lines at all; with a plainJOINthey would disappear from the result and pass the check without deserving to.COALESCE(..., 0)turns the sum of an order with no lines into 0, which would otherwise be null.HAVINGfilters after grouping, andABStakes the difference as an absolute value. The €0.01 tolerance absorbs rounding.
For order 9005 (a vacuum cleaner at 199.00 plus two bags at 29.95), the sum of the lines is 199.00 + 59.90 = 258.90, equal to its total_amount: it does not appear in the result.
Reconciling net sales
To reconcile is to check that the same quantity, calculated by two independent paths, gives the same result. Rule DQ-08 compares the official definition applied directly to the cleansed orders with the sum from the fact table:
WITH source_side AS (
SELECT COUNT(*) AS num_orders, SUM(total_amount) / 1.21 AS net_sales
FROM cleansed.orders
WHERE status NOT IN ('cancelled', 'returned')
AND order_date >= DATE '2026-10-01' AND order_date < DATE '2026-11-01'
),
target_side AS (
SELECT COUNT(DISTINCT s.order_id) AS num_orders, SUM(s.net_amount) AS net_sales
FROM consumption.fact_sales s
JOIN consumption.dim_date d ON d.date_sk = s.date_sk
WHERE s.order_status NOT IN ('cancelled', 'returned')
AND d.year_number = 2026 AND d.month_number = 10
)
SELECT
src.num_orders AS source_orders, tgt.num_orders AS target_orders,
ROUND(src.net_sales, 2) AS source_net,
ROUND(tgt.net_sales, 2) AS target_net,
ROUND(src.net_sales - tgt.net_sales, 2) AS difference
FROM source_side src CROSS JOIN target_side tgt;The two subqueries (WITH) calculate the same thing separately and CROSS JOIN puts them in a single row so that they can be compared. The expected result for October 2026 is 42,780 orders and €2,828,429.75 on both sides, with a difference of 0.00. The rule allows a difference of up to €1 a month, because net_amount is stored rounded to four decimal places on each line.
The same technique makes it possible to reconcile the two figures that pitted Marketing against Finance, and to document the bridge between them:
| Item | Orders | Amount |
|---|---|---|
| Gross sales (Marketing's figure) | 46,500 | €3,720,000.00 |
| − Cancelled and returned orders | −3,720 | −€297,600.00 |
| = Amount including VAT of the valid orders | 42,780 | €3,422,400.00 |
| ÷ 1.21 (VAT is removed) | ||
| = Net sales (Finance's figure) | 42,780 | €2,828,429.75 |
Validations in Python
When the data is still in files, or the rule is hard to express in SQL, validation is done in Python. This example applies several rules to a batch of orders and returns a summary:
import pandas as pd
STATUSES = {"pending", "paid", "shipped", "delivered", "cancelled", "returned"}
REQUIRED = ["customer_id", "order_date", "total_amount"]
def validate_orders(orders: pd.DataFrame) -> pd.DataFrame:
"""Applies the rules to a batch and returns one result row per rule."""
# Each rule is a series of True/False: True = the row BREAKS the rule
rules = {
"DQ-01": orders["order_id"].duplicated(keep=False),
"DQ-02": orders[REQUIRED].isna().any(axis=1),
"DQ-03": ~orders["status"].isin(STATUSES),
}
results = []
for rule_id, fails in rules.items():
results.append({
"rule": rule_id,
"rows": len(orders),
"failing": int(fails.sum()),
"compliance_pct": round(100 * (1 - fails.mean()), 2),
})
return pd.DataFrame(results)duplicated(keep=False)marks all the rows of a repeated identifier, not just the second one.isna().any(axis=1)is true if any of the row's required fields is missing.~is negation:~isin(STATUSES)marks the statuses that are not in the list (nulls too).- The number of failing rows is stored, not just a "pass / fail": that is what makes it possible to apply thresholds and see trends.
Tools
You do not need to build everything by hand. There are tools that let you declare the rules and that take care of running them and reporting:
- Great Expectations: an open-source Python library; the rules are declared as "expectations" and it generates result reports.
- Soda: the rules are written in a declarative language on top of YAML and are run against the data store.
- dbt tests: if the transformations are done with dbt, its tests (uniqueness, not null, accepted values, relationships) cover a good part of the basic rules right next to the transformation code itself.
All of them are based on the same idea we have just coded. The choice for DataCorp will be made together with that of the processing tools, in Module 4.
Where to validate and what to do when a check fails
The earlier a defect is detected, the cheaper it is. That is why checks are set up at three points of the flow, taking advantage of the storage zones:
graph LR
F["Sources"] --> C1{"Check 1<br/>on ingestion"}
C1 --> B["Raw zone"]
B --> C2{"Check 2<br/>between zones"}
C2 -->|"correct rows"| D["Cleansed zone"]
C2 -->|"defective rows"| Q["Quarantine"]
D --> C3{"Check 3<br/>before publishing"}
C3 -->|"correct"| P["Consumption zone"]
C3 -->|"fails"| X["Not published:<br/>the previous version stays visible"]
| Point | What is checked | Example rules |
|---|---|---|
| 1. On ingestion | That the batch has arrived, has the expected structure and a reasonable volume. The content is not judged: everything is stored in the raw zone (ADR-002) | DQ-06, DQ-07, contract schema |
| 2. Between raw and cleansed | Row by row: format, allowed values, nulls, uniqueness, integrity | DQ-01 to DQ-05, DQ-09, DQ-10 |
| 3. Before publishing to consumption | The dataset as a whole: reconciliations and totals | DQ-08 |
When a rule fails there are three possible responses, which correspond to the severities in the table of rules:
| Action | What it consists of | When to use it |
|---|---|---|
| Block | The load stops. Users keep seeing the data from the previous load, with a notice that it is not up to date | The defect invalidates the whole dataset (duplicate identifiers, failed reconciliation) |
| Quarantine | The defective rows are set aside in a separate location, with the reason; the rest carries on | The defect affects specific rows and the others are usable |
| Warn | The load carries on in full and the steward is notified | The defect does not prevent use, but it must be fixed |
The principle that guides the choice: yesterday's data flagged as such is preferable to today's data that is wrong. A dashboard with erroneous figures destroys a trust that takes months to regain.
At DataCorp, the quarantine is stored under the _quarantine/<source>/<entity>/load_date=YYYY-MM-DD/ prefix of the datacorp-data-cleansed bucket, and each row carries two added columns: failed_rule and quarantine_date. The quarantine is not a dumping ground: the steward reviews it every week and every row ends up either corrected and reprocessed, or discarded with a reason. And since the raw zone keeps the original, nothing is lost.
Cleaning and standardization
Detecting is not fixing. Cleaning corrects or sets aside the defective data, and standardization brings equivalent values to a single form. Two rules to begin with: cleaning is done on the way into the cleansed zone, never in the raw zone, and every correction must be a written, repeatable rule, not a manual touch-up.
Cities spelled in several ways. Format variants are solved with functions; language variants or typos, with an alias table maintained by the steward:
-- cleansed.ref_city_alias(alias, city): 'valència' -> 'Valencia', 'gerona' -> 'Girona'
SELECT
c.customer_id,
COALESCE(a.city, -- 1st: known alias
INITCAP(TRIM(c.city)), -- 2nd: format cleanup
'Unknown') -- 3rd: explicit value if it was null
AS city
FROM raw.customers c
LEFT JOIN cleansed.ref_city_alias a
ON a.alias = LOWER(TRIM(c.city));TRIM removes surplus spaces, LOWER converts to lowercase in order to search the alias table and INITCAP capitalizes the first letter of each word. COALESCE returns the first non-null value in the list, so the three strategies are applied in order of preference.
Duplicate customers. They are located by grouping on the normalized email:
SELECT LOWER(TRIM(email)) AS normalized_email,
COUNT(*) AS signups,
MIN(customer_id) AS oldest_id
FROM raw.customers
GROUP BY LOWER(TRIM(email))
HAVING COUNT(*) > 1;This query implements rule DQ-10 and only finds the most obvious duplicates. Deciding when two records are the same person and which data to keep is a problem in its own right, entity resolution, which is covered in lesson 03-06.
Nulls. There is no single answer; it depends on the column and on the use:
| Strategy | Example | When |
|---|---|---|
| Reject the row (quarantine) | Order without customer_id |
The field is essential |
| Explicit "unknown" value | city = 'Unknown' |
The field is used for grouping and the row is still useful |
| Leave the null | Ticket without order_id |
The absence is legitimate and meaningful |
| Impute an estimated value | Fill in with the mean | Only in statistical analyses, and leaving it flagged |
What must never be done is to make up a value that looks real (assigning "Madrid" to somebody who has no city): it turns a visible defect into an invisible one.
Indicators and quality dashboard
Each run of a rule is stored in a results table, quality.rule_results(rule_id, run_date, dataset, rows_evaluated, rows_failed, result). The indicators are built on top of it:
| Indicator | Calculation | Target |
|---|---|---|
| Compliance with a rule | (rows evaluated − rows that fail) / rows evaluated | Depends on the rule (100% for the blocking ones) |
| Domain quality index | Rules passed / rules run, in the period | ≥ 98% |
| Timeliness | Days with the data available before 07:00 / days in the month | ≥ 95% |
| Pending quarantined rows | Count of those more than 7 days old | 0 |
| Open data issues | Count, and average resolution time | Less than 5 working days |
The quality dashboard shows these indicators by domain and how they evolve. A minimal version for the Sales domain, on November 18, 2026:
| Rule | Evaluated | Failing | Compliance | Status |
|---|---|---|---|---|
DQ-01 Uniqueness of order_id |
1,512 | 0 | 100% | OK |
| DQ-03 Valid status | 1,512 | 2 | 99.87% | 2 rows in quarantine |
| DQ-05 Amount = sum of lines | 1,512 | 1 | 99.93% | Warning |
| DQ-08 Net sales reconciliation | 1 | 0 | 100% | OK |
The dashboard must be visible to the users, not just to the data team. Publishing the quality status next to each dataset in the catalog (an operational metadata item from lesson 03-02) builds more trust than hiding the problems.
The cost of poor quality: the 1-10-100 rule
The 1-10-100 rule sums up an empirical observation: the cost of a defect is multiplied by roughly ten at each stage it passes through undetected.
| Stage | Relative cost | Example with the customer's city |
|---|---|---|
| Prevent at the source | 1 | The signup form offers the city in a list instead of a free-text field |
| Correct afterwards | 10 | Maintaining the alias table and reviewing the quarantine every week |
| Fail: the defect reaches the point of use | 100 | A regional campaign is sized with 15% fewer customers than there really are; an erroneous report reaches management |
The figures are not exact; what matters is the proportion and its consequence: the best correction is made at the source. The analytical platform can clean, but each cleanup is a recurring cost that a validation in the store application would avoid for good. A good part of the €122,160 a year of the cost of disorder estimated in lesson 01-02 was hours spent reconciling and correcting data by hand, that is, costs of poor quality.
Continuous improvement and the steward's role
Quality is not achieved with a cleanup project: data degrades every day. It is managed as a cycle:
graph LR
A["1. Define<br/>rules and thresholds"] --> B["2. Measure<br/>run and record"]
B --> C["3. Analyze<br/>look for the root cause"]
C --> D["4. Improve<br/>fix at the source"]
D --> E["5. Control<br/>watch that it does not reappear"]
E --> A
The step that is usually skipped is the third. Cleaning the 380 occurrences of "VALENCIA" solves the symptom; finding out that they come from an old import that wrote in uppercase, and fixing it, solves the cause. The lineage from lesson 03-02 is the tool for that tracing.
The division of responsibilities follows the governance framework from lesson 03-01:
| Role | Responsibility for quality |
|---|---|
| Owner | Approves the thresholds and decides what level of quality is acceptable for their domain |
| Data steward | Proposes the rules, reviews the warnings and the quarantine, investigates the causes with the areas that generate the data and pushes for its correction at the source |
| Technical custodian | Implements and runs the rules, and maintains the quality dashboard |
| Data producers | Fix the data in the source system |
The idea that sums up this division: quality is the business's responsibility, and the data team gives it the means. If Íñigo decided on his own which orders are valid, he would be making a decision that belongs to Carmen.
Common Mistakes and Tips
- Aiming for perfection. 100% on every rule is extremely expensive and unnecessary. Set thresholds according to the use.
- Cleaning without recording. If a transformation corrects silently, nobody will ever know that the source is wrong. Always count how many rows have been corrected.
- Correcting by hand in the consumption zone. The next load will undo the fix. Every correction must be a rule in the process or a change at the source.
- Checking only the structure. The fact that the columns exist and have the right type does not guarantee that the amounts add up. Add reconciliations.
- Too many warnings. If fifty alerts arrive every morning, all of them will be ignored. Few rules, well chosen and with realistic severities.
- Using
JOINin an integrity check. The orphan rows, which are exactly the ones you are looking for, disappear from the result. UseLEFT JOIN. - Forgetting nulls in conditions.
status NOT IN (...)does not detect a null status. - Tip: start with the rules that protect the figures management looks at. At DataCorp, those for net sales.
- Tip: when a user finds an error that no rule detected, besides fixing it, add the rule that would have detected it.
Exercises
Exercise 1: Identifying the dimension
State which quality dimension each case fails:
- The inventory of warehouse 2 has not arrived tonight.
- A customer is recorded with
signup_date= 2031-04-12. - A ticket has
order_id= 99887766, which does not exist. - An order with status
deliveredhastotal_amount= 0.00 and three lines with a price. - The same product appears twice in
products, with different identifiers.
Exercise 2: Writing an integrity rule
Write the SQL query for the products part of rule DQ-04: it must return the order lines whose product_id does not exist in cleansed.products. What action corresponds to the rows it returns?
Exercise 3: Deciding the response
One morning, the checks give these results. State what action you would take in each case and why:
- 310 orders have arrived for the previous day (a normal Tuesday).
- There are 4 orders with the status
out_for_delivery, which is not in the list. - The net sales reconciliation shows a difference of €18,240.00.
Solutions
Exercise 1
- Completeness (expected data is missing) and timeliness (it has not arrived on time).
- Validity (a signup date cannot be in the future) and, therefore, accuracy.
- Integrity (reference to a nonexistent order).
- Consistency (the amount contradicts the lines; this is what DQ-05 detects).
- Uniqueness.
Exercise 2
SELECT ol.line_id, ol.order_id, ol.product_id
FROM cleansed.order_lines ol
LEFT JOIN cleansed.products p ON p.product_id = ol.product_id
WHERE p.product_id IS NULL;LEFT JOIN keeps all the lines; in those that find no product, the columns of p are left null, and the WHERE selects precisely those. The severity of DQ-04 is quarantine: those lines are set aside with the reason and the rest of the batch carries on.
Watch out for the consequence: when a line is set aside, its order would be left with an amount lower than its total_amount and DQ-05 would fail. The consistent thing to do is to quarantine the whole order with all its lines.
Exercise 3
- A warning according to the table of rules, but it is best treated as a block. 310 is far below DQ-07's minimum of 750: the extraction almost certainly ended up incomplete. The prudent course is not to publish, to investigate with the lineage (did the extraction fail? was the store down?) and to keep the previous data visible. It is a good argument for proposing to the committee that DQ-07 become blocking when the volume falls below half the minimum.
- Quarantine for those 4 orders (DQ-03) and an immediate notice to Laura. It is not a data error but a change at the source: the store team has added a status without giving notice, which breaches the data contract from lesson 03-02. Carmen must decide whether
out_for_deliverycounts as a valid order before it is incorporated. - Block the publication (DQ-08). A difference like that is not rounding: it points to orders that are lost, duplicated or with statuses not updated between the cleansed zone and the fact table. It is investigated before anything is published.
Conclusion
Data quality is fitness for the intended use and it is measured in dimensions: accuracy, completeness, consistency, uniqueness, validity, timeliness and integrity. Profiling reveals the real state of the data (at DataCorp, about 600 possibly duplicate customers, 1,840 without a city and Valencia spelled four ways), and quality rules turn expectations into automatic checks with a threshold and a severity. We have implemented in SQL the consistency between an order's amount and its lines and the reconciliation of net sales, which also explains step by step the distance between October's €3,720,000 gross and €2,828,429.75 net. The rules are applied at three points (on ingestion, between zones and before publishing) and their failures are resolved by blocking, quarantining or warning. Cleaning is done in the cleansed zone and in a repeatable way, but the 1-10-100 rule is a reminder that the cheapest thing is to prevent at the source. All of this works as a continuous cycle in which the steward of each domain proposes the rules and chases down the causes.
Data that is correct and well documented is also more valuable, and therefore more sensitive. The customers table contains the names and email addresses of 200,000 people, the access credentials are still shared and the GDPR imposes obligations that DataCorp has not yet addressed. In the next lesson we will deal with data security and privacy: who can see what, how it is protected and what rights the people the data refers to have.
