How do I measure whether my data can be trusted? The six dimensions of data quality, with SQL, thresholds and a scorecard
TL;DR
Difficulty: Intermediate
Data quality means fit for a purpose, so start by writing down who uses each table and for what.
- Measure six dimensions: completeness, uniqueness, validity, accuracy, consistency and timeliness. Each check is a precise rule over a defined set of rows, scored as the share that passes.
- Validity is not accuracy: a value can follow every format rule and still be wrong. Measure accuracy against an authority or with a hand checked sample and its margin of error.
- Set a warning and an error threshold from what the user can tolerate, never a blanket 100%.
- Store every result, watch each check as a trend with control limits, give every table an owner, and put a short quality note on every report.
What to read first
"Can I trust this number?" is the question every report eventually meets, and most people answer it with a feeling. This chapter replaces the feeling with measurements: six dimensions of data quality, each turned into a rule, a SQL query, a threshold and a trend, all worked through on one example online shop.
"Can I trust this number?" deserves a better answer than "I think so"
Every Monday at Wrenfield Home, an online homeware shop in Leeds, Priya opens her weekly report. Revenue, orders, returns, new customers, ad spend. And every few weeks she asks Callum, her developer and data engineer, the same question: "Can I trust this?"
Most people answer that question with a feeling. The numbers look about right, nobody has complained, the dashboard is green. A feeling is not an answer. It cannot tell Priya which number to trust and which to treat with care, it cannot tell her whether things got better or worse since last month, and it cannot be checked by anyone else.
This article replaces the feeling with measurements. By the end you will be able to take any table in your business, name the handful of things that make it trustworthy or not, turn each into a number between 0 and 100%, choose a threshold for it that means something, and track it week by week so you notice when it breaks.
If you have not read it yet, the chapter on what dirty data costs explains why this matters in money. This chapter is about how to measure it. The next chapter in this series, on data profiling, shows how to explore a table you know nothing about. This one assumes you know roughly what is in your tables and want to know how good they are.
A few terms first. A table is a set of rows with the same columns, like a spreadsheet tab. A row (or record) is one thing: one order, one customer. A column (or field) is one fact about it: the email, the total. A check is a rule you test every row against, such as "every order has an email address". And SQL (Structured Query Language) is the language you use to ask a database questions. All SQL in this article is PostgreSQL unless I say otherwise.
Quality means fit for the purpose, not perfect
The most useful definition of data quality is also the oldest. Richard Wang and Diane Strong, in a study of what data quality means to the people who actually use data, defined high quality data as "data that are fit for use by data consumers"1. The UK government's Data Quality Framework says the same thing in plainer words: data quality is "fitness for purpose", and the question to ask is whether the data is good enough for what you want to use it for2.
That sounds obvious until you notice what it rules out. It rules out the idea that a table is simply "clean" or "dirty". The same column can be perfectly good for one job and useless for another. So before you measure anything, you have to say what the data is for.
Example: one phone column, three purposes
Wrenfield Home stores a phone number on the shipping address of every order. In November 2026 the shop took 1,980 orders. For 40 of them, about 2%, the phone number was missing or could not possibly be a phone number.
Now look at three people who use that column.
- The courier. Wrenfield's courier texts customers a delivery slot and phones them when it cannot find the door. An order without a usable number risks a failed delivery, a second attempt and an annoyed customer. For the courier, 40 bad numbers a month is 40 possible problems, about nine a week.
- Marketing. Priya never sends marketing by text message. For her campaigns, the phone column does not matter at all. A completely empty column would be fine.
- Finance. The accountant reconciles revenue and VAT. The phone number plays no part in that. Again, irrelevant.
Same column, same 40 bad values, three different answers to "is this good enough?" The courier needs it close to complete. Marketing and finance do not care. Measuring quality therefore always starts with a sentence of the form "this data is used for this decision, by this person". Everything else in this article hangs off that sentence.
The six dimensions that turn trust into numbers
"Fit for purpose" is the goal. To measure it you need to break it into pieces. Those pieces are called dimensions: distinct ways in which data can be good or bad.
In 2013 a working group of DAMA UK, the British chapter of the Data Management Association, published a short paper that set out six core dimensions and how to measure each one3. The UK government later adopted the same six in its Data Quality Framework2. They are the closest thing the field has to a shared vocabulary, so I use them too.
| Dimension | The question it answers | A Wrenfield Home example |
|---|---|---|
| Completeness | Is everything there that should be there? | Does every order have a usable phone number? Did every daily 3PL file arrive? |
| Uniqueness | Is each thing recorded only once? | Is each customer one record, or are some people in there twice? |
| Validity | Does each value follow the rules for its format, type and range? | Is the country a code the shop recognises, or free text like "England"? |
| Accuracy | Does the value match reality? | Is that vase really 45 cm tall, or did a supplier send millimetres? |
| Consistency | Do two representations of the same thing agree? | Does an order's total equal its items plus shipping plus adjustments? Do the shop and GA4 agree on purchases? |
| Timeliness | Is the data available when it is needed, and recent enough? | Are last week's returns in the warehouse by Monday morning? |
Two international standards cover the same ground in more depth, and you will meet their names in procurement documents and audits. ISO 8000 is a whole series of standards on data quality. Its first part, ISO 8000 1:2022, gives an overview of the series and sets out the principles of information and data quality4. ISO/IEC 25012:2008 defines a data quality model for data held in a structured format in a computer system, with fifteen characteristics seen from two points of view: those inherent in the data itself and those that depend on the system holding it5. Wang and Strong's study arrived at fifteen dimensions in four categories, including ones such as interpretability and accessibility that the six do not cover directly1.
You do not need all of that to start. The six DAMA dimensions cover what goes wrong in almost every table a small or medium business owns, and they are simple enough to explain to an owner in five minutes. The DAMA paper itself makes two points worth keeping in mind: not every dimension matters for every data set, and you must agree the rules the data should meet before measuring anything against them3.
Example: the dimensions on one order
Take one order, number R482913011, placed on 12 November 2026. Callum walks Priya through the six questions on that single row.
- Completeness: the email is present, the shipping address is present, the phone field holds "n/a". That is not a phone number. Incomplete.
- Uniqueness: the order number appears once. Unique. But the customer's email,
Hannah.Ellis@example.com, also exists ashannah.ellis@example.com(lower case, trailing space) on an older account. The customer is not unique. - Validity: the email follows the format of an email address, the country is GB. Valid.
- Accuracy: the shipping address matches what the courier delivered to. Accurate, as far as anyone can tell.
- Consistency: item total £64.00, shipping £4.95, adjustments £0.00, total £68.95. The parts add up. Consistent.
- Timeliness: the order reached the warehouse at 5.40am the next morning, in time for the Monday report. Timely.
One row, six questions, two problems found, and each problem belongs to a clear dimension. That is the whole method. The rest of this article does it for millions of rows at once.
A dimension becomes a number through a rule and a count
Every quality measurement in this article has the same shape. You write a rule that a single row either passes or fails. You decide which rows the rule applies to, the population. You count how many rows in the population pass. The score is the share that passes.
where is the quality score of one check as a percentage, is the number of rows that pass the rule, and is the number of rows the rule applies to. It is an ordinary ratio, explained step by step in Foundations: ratios and rates.
The formula is trivial. The decisions behind it are not, and they are where most quality numbers go wrong.
- The rule must be written precisely enough that two people would classify every row the same way. "Phone is filled in" is not precise. "Phone, with spaces removed, has at least 10 digits and is not a known placeholder" is.
- The population must match the purpose. If only courier deliveries need a phone number, click and collect orders do not belong in .
- The period must be fixed. "Orders completed in November 2026, in UK time" is a population. "Recent orders" is not.
Example: the same data, three different scores
Callum measures phone completeness for November's 1,980 completed orders three ways.
First, naively, counting only database NULLs (a NULL is the database's marker for "no value at all"). Nine phone fields are NULL.
Here because only the nine NULLs fail. Second, treating empty strings and spaces as missing too. Another 11 fields hold an empty string or only spaces, so 20 are missing.
Now . Third, treating known placeholders as missing too. Four more fields hold "n/a" or "0000000000", so 24 are missing.
Now . Same data, three scores from 98.8% to 99.5%. Only the third is honest, because a courier cannot ring "n/a". The lesson: the definition of "missing" is part of the rule, and it has to be written down.
Completeness: is everything there that should be there?
DAMA UK defines completeness as the proportion of stored data against the potential of "100% complete", where business rules say what 100% means3. There are two kinds, and people often measure only the first.
Column completeness asks whether the fields in each row are filled. That is the phone example.
Population completeness asks whether all the rows are there at all. A table can have every field filled in every row and still be badly incomplete, because a whole day of rows never arrived. This kind of gap is invisible to any check that looks inside rows. You only find it by comparing the rows you have with the rows you expected.
A third subtlety is conditional completeness. Some fields are only required in some situations. A company name on an address is required for business customers and optional for everyone else. A tracking number is required once an order has shipped and not before. Measure these only on the rows where they are required, or your score mixes two populations.
Example: phone completeness in SQL
Wrenfield runs on Solidus, an open source eCommerce platform for Ruby on Rails. Orders live in spree_orders, addresses in spree_addresses, and each order points at its shipping address through ship_address_id. Callum writes the rule once, with every form of "missing" spelled out.
-- PostgreSQL: phone completeness for courier orders completed in November 2026 (UK time)
WITH november_orders AS (
SELECT o.id, o.number, a.phone
FROM spree_orders o
JOIN spree_addresses a ON a.id = o.ship_address_id
WHERE o.state = 'complete'
AND o.completed_at >= TIMESTAMPTZ '2026-11-01 00:00 Europe/London'
AND o.completed_at < TIMESTAMPTZ '2026-12-01 00:00 Europe/London'
),
classified AS (
SELECT
id,
CASE
WHEN phone IS NULL THEN 'null'
WHEN btrim(phone) = '' THEN 'empty'
WHEN lower(btrim(phone)) IN ('n/a', 'na', 'none', '-')
OR regexp_replace(phone, '\D', '', 'g') ~ '^0+$' THEN 'placeholder'
ELSE 'present'
END AS phone_status
FROM november_orders
)
SELECT
phone_status,
count(*) AS orders,
round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS share_pct
FROM classified
GROUP BY phone_status
ORDER BY orders DESC;
The regexp_replace(phone, '\D', '', 'g') part removes everything that is not a digit, so "000 000 0000" and "0000000000" are both caught as placeholders. The result:
| phone_status | orders | share_pct |
|---|---|---|
| present | 1,956 | 98.8 |
| empty | 11 | 0.6 |
| null | 9 | 0.5 |
| placeholder | 4 | 0.2 |
Completeness is 98.8%. Note the population: Wrenfield has no click and collect, so every completed order needs a phone. A shop with collection would add AND o.shipment_state IS NOT NULL or join to the shipping method and exclude collections.
Example: population completeness for the 3PL file
The 3PL warehouse sends one CSV of shipments and returns every day. Callum keeps a log of every file loaded, in a table he calls raw_3pl.file_log (an invented name for this example). Population completeness asks: of the days that should have a file, how many do?
-- PostgreSQL: which days in November have no 3PL file?
SELECT d::date AS expected_day
FROM generate_series(DATE '2026-11-01', DATE '2026-11-30', INTERVAL '1 day') AS d
LEFT JOIN raw_3pl.file_log f ON f.file_date = d::date
WHERE f.file_date IS NULL;
generate_series produces one row per calendar day. The LEFT JOIN keeps every day and attaches a file where one exists, so the days that come back are the gaps. In November one day is missing, the 23rd. Population completeness for the file is 29 of 30 days, 96.7%. Every row inside the other 29 files can be perfect, and Monday's shipped units will still be short by one day's worth. No column check would ever have told Callum that.
Uniqueness: is each thing recorded only once?
DAMA UK's rule is that nothing is recorded more than once, based on how that thing is identified, and its measure compares the number of real things with the number of records describing them3.
where is uniqueness as a percentage, is the number of distinct real things (people, orders, products), and is the number of records in the table that describe them. See Foundations: ratios and rates.
The hard part is . For an order, the shop gives each one a unique number, so counting real orders is easy and a uniqueness check is a plain test that the key never repeats. For a customer, nobody hands out a reliable key. You have to decide what makes two records "the same person", and every choice you make gives you a different .
So keep two kinds of uniqueness apart:
- Key uniqueness: does a column that is meant to be unique ever repeat? Order numbers, payment references, GA4 transaction IDs. The target is 100%, and anything less is a bug.
- Entity uniqueness: is each real world thing one record? Customers, products from several suppliers, companies. The target is a business decision, and the measurement depends on how good your matching is.
Example: duplicate customers at Wrenfield Home
Over five years Wrenfield has collected 78,000 customer records: 52,400 accounts in spree_users and 25,600 distinct email addresses used for guest checkouts, stored on the order itself in spree_orders.email. Callum suspects some people appear more than once, because a few emails differ only in capitals or a stray space, and some customers checked out as guests before opening an account.
He normalises every email (lower case, spaces trimmed) and counts how many records collapse into one.
-- PostgreSQL: customer records and the distinct people behind them, matched on normalised email
WITH customer_records AS (
SELECT 'account' AS kind, id::text AS record_id, email
FROM spree_users
UNION ALL
SELECT DISTINCT ON (o.email) 'guest', o.email, o.email
FROM spree_orders o
WHERE o.user_id IS NULL AND o.state = 'complete'
)
SELECT
count(*) AS records,
count(DISTINCT lower(btrim(email))) AS distinct_people,
count(*) - count(DISTINCT lower(btrim(email))) AS duplicate_records,
round(100.0 * count(DISTINCT lower(btrim(email))) / count(*), 1) AS uniqueness_pct
FROM customer_records;
| records | distinct_people | duplicate_records | uniqueness_pct |
|---|---|---|---|
| 78,000 | 75,582 | 2,418 | 96.9 |
Worked through with the formula:
Here and . So 2,418 records, 3.1%, are a second record of someone already there. Of those, 1,104 are accounts that differ only in case or spaces and 1,314 are guest checkouts by people who also have an account.
Two honest caveats belong next to that number. First, it is an upper bound on uniqueness. Anyone who used two different email addresses is still counted as two people, so the true uniqueness is lower. Second, it says nothing about which record is right. Measuring duplicates and merging them are different jobs. A later chapter in this series covers entity resolution, the craft of deciding that two records are one person.
Example: duplicate purchase events in GA4
GA4 (Google Analytics 4) exports its raw events to BigQuery every day, one table per day named events_YYYYMMDD6. Each purchase event carries ecommerce.transaction_id, the order number7. A purchase should appear once. When a customer reloads the confirmation page, it can appear twice.
-- BigQuery: purchase events versus distinct transaction IDs, November 2026
SELECT
COUNT(*) AS purchase_events,
COUNT(DISTINCT ecommerce.transaction_id) AS distinct_transactions,
ROUND(100 * COUNT(DISTINCT ecommerce.transaction_id) / COUNT(*), 1) AS uniqueness_pct
FROM `wrenfield-analytics.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261101' AND '20261130'
AND event_name = 'purchase';
The result is 1,683 purchase events for 1,671 distinct transactions. Key uniqueness is . Twelve orders were counted twice. Anyone summing purchase_revenue straight from the events overstates revenue by those twelve orders. The purchase event done right shows how to stop the duplicates at the source.
Validity: does each value follow the rules for its type, format and range?
A value is valid if it conforms to the syntax of its definition: its type, its format and its range3. Validity is the easiest dimension to measure, because you can check it by looking at the value alone, without knowing anything about the real world.
Typical validity rules for a shop:
- Type: a quantity is a whole number, a price is a decimal amount, a date is a real date.
- Format: an email has the shape of an email address, a UK postcode has the shape of a postcode, a SKU follows the shop's pattern.
- Range: a quantity is between 1 and 99, a price is above zero, an order date is not in the future.
- Allowed set: a country is one of the codes in the shop's country table, an order state is one of the states Solidus knows.
For email, a useful and well defined rule is the one the HTML standard uses for email inputs in browsers. The WHATWG HTML specification defines a "valid email address" with a pattern and says plainly that this is a wilful violation of the full email standard, RFC 5322, because the full standard allows forms nobody uses in practice8. That makes it a sensible validity check: strict enough to catch typos such as name@gmail,com, loose enough to accept every address a real person types.
The trap with validity is that a high score feels like quality. It is not. A value can be perfectly valid and completely wrong. A 25 cm mug recorded as 250 passes a "height between 1 and 300 cm" rule. Validity tells you a value could be right. Only accuracy tells you it is.
Example: the free text country column
Wrenfield's first platform let customers type their country. When Callum imported the old addresses into a table he named legacy.addresses, the country came along as free text in country_text. In the shop's own country table, spree_countries, the United Kingdom is GB. Callum checks the legacy values against that set.
-- PostgreSQL: is each legacy country value a code the shop knows?
SELECT
la.country_text,
count(*) AS addresses,
(sc.iso IS NOT NULL) AS valid
FROM legacy.addresses la
LEFT JOIN spree_countries sc ON sc.iso = la.country_text
GROUP BY la.country_text, sc.iso
ORDER BY addresses DESC;
| country_text | addresses | valid |
|---|---|---|
| GB | 3,100 | true |
| UK | 2,600 | false |
| United Kingdom | 2,300 | false |
| England | 1,050 | false |
| Scotland | 160 | false |
| Wales | 70 | false |
| IE | 60 | true |
| Ireland | 30 | false |
| (NULL) | 30 | false |
There are 9,400 rows. Thirty are NULL, so completeness is . Validity is measured on the 9,370 that have a value, and only GB and IE are in the allowed set:
Here and . A validity score of 33.7% sounds like a disaster. It is not, and this is exactly why a score needs context. Almost every invalid value is perfectly understandable to a person: "UK", "United Kingdom", "England", "Scotland" and "Wales" all mean GB. The meaning is there, the format is wrong. A mapping table fixes 6,180 of the 6,210 invalid rows in one go, and a later chapter in this series covers standardising values like these. The low score is still worth having. Any report that groups revenue by country_text today splits British revenue across six rows, and the score is what makes that visible.
Example: a range check that passes a wrong value
Wrenfield sells about 1,400 products in 2,100 variants (a variant is one size or colour of a product). Solidus stores dimensions on spree_variants in the columns height, width and depth. Two suppliers send centimetres. A third sends millimetres. Callum adds a range check: height between 1 and 300 cm, because nothing Wrenfield sells is taller than a floor lamp.
-- PostgreSQL: height outside the plausible range for homeware
SELECT count(*) FILTER (WHERE height IS NOT NULL) AS checked,
count(*) FILTER (WHERE height BETWEEN 1 AND 300) AS valid,
round(100.0 * count(*) FILTER (WHERE height BETWEEN 1 AND 300)
/ count(*) FILTER (WHERE height IS NOT NULL), 1) AS validity_pct
FROM spree_variants
WHERE deleted_at IS NULL;
The check finds 2,100 variants with a height and 2,083 inside the range, 99.2%. The 17 failures are tall items from the millimetre supplier: a 45 cm vase stored as 450. But a 25 cm mug from the same supplier, stored as 250, passes. So does a 12 cm candle holder stored as 120. Validity is 99.2%, and the dimensions are still wrong for hundreds of products. The next section measures how many.
Accuracy: does the data match the real world?
Accuracy is the degree to which data correctly describes the real object or event3. It is the dimension owners care about most and the one engineers measure least, for a simple reason: you cannot measure it by looking at the data alone. DAMA UK is explicit that accuracy can only be assessed in two ways: against the actual thing the data represents, or against an authoritative reference data set3.
That gives you two practical methods.
- Compare with an authority. For some data, another system is the better source of truth. The payment provider's settlement file says what money actually arrived. The courier's tracking says where a parcel actually went. Compare row by row.
- Check a sample by hand. Where no authority exists, take a random sample, check each row against reality (the product on the shelf, the supplier's spec sheet, a phone call), and estimate the accuracy of the whole table from the sample.
A sample gives you an estimate, not a fact. So an accuracy score from a sample should always travel with its margin of error.
Example: order totals against the payment settlement
Stripe and PayPal send settlement files listing every payment they processed. Callum loads them into staging tables, stg_stripe_payments and stg_paypal_payments (invented names), and compares what the shop thinks it charged with what the providers say they charged.
-- PostgreSQL: does the shop's order total match what the payment providers settled?
WITH settled AS (
SELECT order_number, sum(amount) AS settled_amount
FROM (
SELECT order_number, amount FROM stg_stripe_payments
UNION ALL
SELECT order_number, amount FROM stg_paypal_payments
) p
GROUP BY order_number
)
SELECT
count(*) AS orders,
count(*) FILTER (WHERE s.settled_amount = o.total) AS matching,
round(100.0 * count(*) FILTER (WHERE s.settled_amount = o.total) / count(*), 1) AS accuracy_pct
FROM spree_orders o
LEFT JOIN settled s ON s.order_number = o.number
WHERE o.state = 'complete'
AND o.completed_at >= TIMESTAMPTZ '2026-11-01 00:00 Europe/London'
AND o.completed_at < TIMESTAMPTZ '2026-12-01 00:00 Europe/London';
Of 1,980 November orders, 1,974 match exactly. Accuracy is . Callum looks at the six that do not. In every case a member of staff edited the order in the admin after the payment was taken, so the shop's total no longer matches what the customer paid. That is a process problem, not a data bug, and it now has a number attached.
Because the amounts are stored as NUMERIC, an exact comparison is safe. Had they been floating point numbers, the comparison would fail on rounding alone, which is one reason data types matter.
Example: product dimensions from a sample
For product dimensions there is no authority to join against. So Callum samples. He draws 200 variants at random, with a fixed seed so anyone can draw the same 200 again.
-- PostgreSQL: a reproducible random sample of 200 variants for a manual accuracy check
SELECT setseed(0.42);
SELECT v.id, v.sku, p.name, v.height, v.width, v.depth
FROM spree_variants v
JOIN spree_products p ON p.id = v.product_id
WHERE v.deleted_at IS NULL
ORDER BY random()
LIMIT 200;
setseed fixes the starting point of PostgreSQL's random number generator for the session, so random() returns the same sequence each time. He then checks each of the 200 against the supplier's spec sheet and, for anything doubtful, against the item in the warehouse. Thirteen are wrong: eleven are millimetres read as centimetres, two are typing errors. So 187 of 200 are accurate, an estimate of 93.5%.
How sure is that 93.5%? The usual answer is a confidence interval for a proportion9:
where is the share of accurate rows in the sample, is the sample size, and is the number of standard errors that gives the confidence you want, 1.96 for 95%. Foundations: confidence intervals explains the idea, and Foundations: sample size explains how to choose .
Worked through: and .
That is the standard error, the typical distance between the sample share and the true share. Multiplied by :
This is the margin of error, in the same units as .
So accuracy lies somewhere between and , with 95% confidence.
The NIST handbook notes that this simple interval becomes unreliable when the number of failures is small, and describes the Wilson interval as the better choice in that case9. Thirteen failures is on the edge, so Callum checks both in Python:
from statsmodels.stats.proportion import proportion_confint
accurate, sampled = 187, 200
for method in ("normal", "wilson"):
low, high = proportion_confint(accurate, sampled, alpha=0.05, method=method)
print(f"{method:>6}: {low:.1%} to {high:.1%}")
normal: 90.1% to 96.9%
wilson: 89.2% to 96.2%
proportion_confint from statsmodels computes both intervals10. The Wilson interval is shifted slightly down, because accuracy close to 100% cannot spread as far upwards as downwards. Either way the message to Priya is the same: roughly one product in 15 has wrong dimensions, and since shipping costs are calculated from them, that matters. Validity said 99.2%. Accuracy says about 93%. The gap between those two numbers is the size of the millimetre problem.
Accuracy of personal data is also a legal duty
When the data is about people, accuracy is not only good practice. Under the UK GDPR, personal data must be "accurate and, where necessary, kept up to date", and every reasonable step must be taken to erase or correct inaccurate data without delay11. The Information Commission's (formerly the ICO's) guidance adds two practical points: what counts as reasonable depends on how much accuracy matters for the purpose, and you should record where the data came from12. A customer's delivery address matters a great deal. An old newsletter preference much less. This is general information and not legal advice, but measuring the accuracy of customer data, and keeping a record of the measurement, is the kind of evidence that shows the reasonable steps were taken.
Consistency: do two versions of the same thing agree?
Consistency is the absence of difference when you compare two or more representations of a thing against a definition3. It covers three situations.
- Within a row: fields that should agree with each other do. An order's total equals its parts. A delivery date is not before the order date.
- Across tables: an order's total equals the sum of its line items.
- Across systems: the shop, GA4, the 3PL and the payment providers tell the same story about the same orders.
DAMA UK makes a point that surprises people: data can be consistent without being valid or accurate3. Two systems can agree perfectly on a wrong value, for instance when one copied from the other.
Example: does each order add up?
In Solidus, an order's total is calculated as the item total plus the shipment total plus the adjustment total, where adjustments include promotions and tax added on top13. That gives a rule every order must pass.
-- PostgreSQL: orders whose total does not equal the sum of its parts
SELECT
(o.completed_at < DATE '2024-01-01') AS legacy_import,
count(*) AS orders,
count(*) FILTER (
WHERE o.total <> o.item_total + o.shipment_total + o.adjustment_total
) AS inconsistent
FROM spree_orders o
WHERE o.state = 'complete'
GROUP BY 1;
| legacy_import | orders | inconsistent |
|---|---|---|
| false | 69,300 | 0 |
| true | 49,500 | 1,262 |
Orders created by Solidus itself are 100% consistent. Orders imported from the old platform are not: 1,262 of 49,500 differ by one or two pence. Consistency for the legacy orders is:
Here legacy orders. The cause is the old platform storing prices as floating point numbers. Converting them to decimals rounded some parts up and others down, and the parts no longer add up to the stored total. Callum now has a decision to make, and it belongs in the rule: is a difference of a penny a failure? For the VAT return, the legacy years are long filed and closed. For a lifetime value model, a penny is noise. He writes the rule with an explicit tolerance, abs(o.total - (o.item_total + o.shipment_total + o.adjustment_total)) > 0.02, documents why, and the legacy orders pass. A tolerance that is written down is a decision. A tolerance that is hidden in a rounded report is a secret.
Example: the shop and GA4 never agree, and that is fine
GA4 counts fewer purchases than the shop, because some customers decline analytics cookies and some browsers block the tag. At Wrenfield the gap is about 15%. When analytics, ads and orders disagree explains the causes in full.
A naive consistency check would demand that the two match and fail every single day. That check is useless. The useful check measures the ratio and compares it with its own normal range.
where is the consistency ratio, is the number of distinct purchase transactions GA4 recorded, and is the number of completed orders in the shop for the same days. See Foundations: ratios and rates.
For November: . Over the past year Wrenfield's ratio has stayed between 0.80 and 0.90. So 0.844 passes. The alarm goes off when the ratio leaves that band. If it drops to 0.62 one week, the tracking broke. If it jumps to 1.02, GA4 is double counting. The gap is not the problem. A change in the gap is.
Timeliness: is the data there when the decision is made?
Timeliness is the degree to which data represents reality at the point in time it is needed3. In practice it has two parts.
- Freshness: how old is the newest data right now? If the last order in the warehouse is from 2am yesterday, the data is about 30 hours stale.
- Latency: how long after something happens does it reach the data? A return handed in at the warehouse on Monday that appears in the data on Thursday has a latency of three days.
Timeliness is always relative to a decision. Data that is a day old is perfectly timely for a monthly board pack and useless for deciding which ads to pause this afternoon.
Some sources have their timing built in. GA4's daily export to BigQuery typically arrives mid afternoon in the property's time zone, can be delayed until the next day, and GA4 keeps updating each daily table for up to two calendar days plus the current day6. So yesterday's GA4 numbers are not final until the day after tomorrow. A report that reads them at 7am will always be early.
Example: returns from the 3PL arrive late
The 3PL's daily file lists returns as they are processed in the warehouse, not when the customer sent them. Callum measures the latency: the days between the 3PL's receipt date in the file and the date the row first appeared in the warehouse. The 3PL writes its dates in local time without a time zone, so he compares dates, not timestamps, to avoid a one hour error in summer.
-- PostgreSQL: how many days after receipt does each November return appear in the data?
SELECT
(r.first_loaded_at AT TIME ZONE 'Europe/London')::date - r.received_local::date AS days_late,
count(*) AS returns
FROM stg_3pl_returns r
WHERE r.received_local >= DATE '2026-11-01'
AND r.received_local < DATE '2026-12-01'
GROUP BY 1
ORDER BY 1;
| days_late | returns |
|---|---|
| 1 | 62 |
| 2 | 41 |
| 3 | 33 |
| 4 | 24 |
| 5 | 18 |
That is 178 returns, close to the 9% return rate on 1,980 orders. The share available within two days is:
where is the share of returns in the data within two days. Within five days it is 100%.
What does that mean for Priya's Monday report? If it shows last week's returns, it shows only about 58% of them for the last two days of the week, so the return rate looks better than it is, every single week. There are two honest fixes. Either the report shows returns only for weeks that ended at least five days ago, or it shows the latest week marked as provisional. A third fix belongs at the source: ask the 3PL to send returns daily as they are received, which is a conversation about a contract, not about SQL.
Example: freshness checks in dbt
Wrenfield's transformations run in dbt Core, a tool that turns SQL files into tested tables. dbt can check the freshness of each source: you name a column that records when each row was loaded, and say how old the newest row may be before dbt warns or fails14.
# models/staging/sources.yml (dbt Core 1.10 or later)
sources:
- name: shop
schema: raw_shop
config:
loaded_at_field: _loaded_at
freshness:
warn_after: {count: 26, period: hour}
error_after: {count: 36, period: hour}
tables:
- name: spree_orders
- name: spree_line_items
- name: threepl
schema: raw_3pl
config:
loaded_at_field: _loaded_at
freshness:
warn_after: {count: 2, period: day}
error_after: {count: 3, period: day}
tables:
- name: returns
Running dbt source freshness (or dbt freshness in recent versions, which also covers models) compares the newest _loaded_at with the current time and reports pass, warn or error for each table14. The thresholds follow from the schedule: the shop loads every night at 2am, so data older than 26 hours means one load was missed, and older than 36 hours means something is properly broken.
Thresholds come from the decision, not from a wish for 100%
A score without a threshold is trivia. "Phone completeness is 98.8%" says nothing until someone says what is good enough. There are three sensible ways to choose a threshold, and the best ones combine them.
- From the tolerance of the decision. Ask the person who uses the data how many bad rows they can live with before they would act differently. Turn that into a percentage.
- From the current baseline. If a check has been at 98.8% for a year, a threshold of 100% fires every day and gets ignored. Start just below the current level, so the check catches things getting worse, and tighten it as the source improves.
- From the cost of a failure. A duplicate order number can double revenue in a report, so its threshold is 100% with no tolerance. A missing newsletter preference costs nothing, so it may not need a check at all.
The tolerance turns into a threshold with one line of arithmetic.
where is the threshold as a percentage, is the number of bad rows per period the user can tolerate, and is the number of rows in that period. See Foundations: ratios and rates.
Most checks deserve two thresholds, not one. A warning level means someone should look this week. An error level means stop: do not publish the numbers that depend on this table until it is fixed.
Example: a threshold for usable phone numbers
Priya talks to the courier. A handful of failed contacts a week is normal and costs little. More than five a week starts to cost redeliveries, and more than ten means something has changed. Wrenfield ships about 457 orders a week ().
Warning threshold, with :
Error threshold, with :
The check is on usable phone numbers: present and plausible. In November that is (the 24 missing plus 16 present but impossible, such as five digits). That is below the warning level and above the error level. Callum's status for the month: warning. It is worth a look, it is not a crisis.
In dbt, the same thresholds become a test with warn_if and error_if. By default a dbt test fails on any failing row, its severity is error, and warn_if and error_if let you set counts instead15.
# models/marts/schema.yml (dbt Core 1.10.5 or later for the arguments key)
models:
- name: fct_orders
columns:
- name: ship_phone_usable
data_tests:
- accepted_values:
arguments:
values: [true]
quote: false
config:
severity: error
warn_if: "> 21" # more than 5 a week over a 30 day month
error_if: "> 43" # more than 10 a week
The counts are the weekly tolerances scaled to the 30 day window the model covers: and . November's 40 unusable numbers produce a warning, exactly as the percentage said.
A scorecard per table shows where trust is earned
One check answers one question. Priya wants to know which tables she can rely on. A scorecard gathers every check for a table, with its score, its thresholds and its status, in one place.
To build one, every check writes its result into one results table each time it runs. That table is also what makes trends possible later.
-- PostgreSQL: one row per check per run
CREATE TABLE dq.check_results (
check_id text NOT NULL, -- e.g. 'orders.ship_phone_usable'
table_name text NOT NULL,
dimension text NOT NULL CHECK (dimension IN
('completeness','uniqueness','validity','accuracy','consistency','timeliness')),
period_start date NOT NULL,
period_end date NOT NULL,
n_checked bigint NOT NULL,
n_passed bigint NOT NULL,
warn_pct numeric(5,2),
error_pct numeric(5,2),
run_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (check_id, period_start, run_at)
);
-- The scorecard: the latest result of every check, with its status
CREATE VIEW dq.scorecard AS
SELECT DISTINCT ON (check_id)
table_name, dimension, check_id, period_start, period_end,
round(100.0 * n_passed / nullif(n_checked, 0), 1) AS score_pct,
warn_pct, error_pct,
CASE
WHEN 100.0 * n_passed / nullif(n_checked, 0) < error_pct THEN 'error'
WHEN 100.0 * n_passed / nullif(n_checked, 0) < warn_pct THEN 'warning'
ELSE 'pass'
END AS status
FROM dq.check_results
ORDER BY check_id, run_at DESC;
DISTINCT ON (check_id) with ORDER BY check_id, run_at DESC keeps only the newest run of each check, a PostgreSQL shortcut for "latest row per group". nullif(n_checked, 0) avoids a division by zero when a check finds no rows.
Example: the scorecard for November
| Table | Check | Dimension | Score | Warn below | Error below | Status |
|---|---|---|---|---|---|---|
| Orders | Usable ship phone | Completeness and validity | 98.0% | 98.9% | 97.8% | warning |
| Orders | Order number unique | Uniqueness | 100% | 100% | 100% | pass |
| Orders | Email valid | Validity | 99.8% | 99.5% | 99.0% | pass |
| Orders | Total matches settlement | Accuracy | 99.7% | 99.5% | 99.0% | pass |
| Orders | Loaded by 6am | Timeliness | 96.7% | 95% | 90% | pass |
| Customers | One record per email | Uniqueness | 96.9% | 98% | 95% | warning |
| Legacy addresses | Country is a known code | Validity | 33.7% | 95% | 90% | error |
| Products | Dimensions correct (sample) | Accuracy | 93.5% | 98% | 95% | error |
| GA4 events | Purchase ratio to shop | Consistency | 84.4% | 80% | 75% | pass |
| 3PL returns | In the data within 2 days | Timeliness | 57.9% | 90% | 80% | error |
Two of the scores need a word. The email check found three invalid addresses in 1,980, so , shown rounded. The GA4 ratio of 0.844 is shown as 84.4%, with its band expressed as a floor, since a ratio above 0.90 is a separate alarm.
Read the scorecard as Priya would. Orders: trustworthy for revenue and order counts, one warning that matters to the courier, not to the report. Customers: counts of "new customers" are inflated by up to 3.1%. Country revenue from legacy years: do not use until the mapping is done. Shipping cost analysis: do not trust product dimensions until the millimetre supplier is fixed. Returns: last week's return rate is understated until five days have passed.
That is a far more useful answer to "can I trust this?" than yes or no. It says which numbers, for which decisions, and why.
One number per table hides the check that matters
It is tempting to roll a scorecard into a single score per table. DAMA UK notes that each dimension is likely to carry a different weighting, and that you have to decide how much each contributes3. A weighted average does that:
where is the table's overall score, is the score of check , and is the weight you give check . It is a weighted mean, covered in Foundations: mean.
Example: the orders table in one number
Callum weights the five orders checks by how much damage a failure does: usable phone 1, order number unique 3, email valid 2, total matches settlement 3, loaded by 6am 2. The weights add up to 11.
So . A score of 99.1% looks excellent, and it hides the warning on the phone check completely. Now imagine order numbers start repeating: uniqueness drops to 99%, and the overall score barely moves, to 98.8%, while revenue in every report is wrong. That is why I always show the worst critical check next to any overall score, and never the overall score alone. An average is useful for a trend over months. A decision needs the individual checks.
Quality is a trend, not a snapshot
A single scorecard tells you where you are. It does not tell you whether something just broke. A check that has sat at 98.9% for months and drops to 98.0% is far more alarming than a check that has always been at 98.0%. You only see that if you keep every run.
The simplest robust way to judge "is this week unusual?" is borrowed from manufacturing: the control chart. You take a stable period, compute the mean and standard deviation of the score, and draw limits three standard deviations either side. The NIST engineering statistics handbook describes this as the accepted standard in industry: with normally distributed values, a point falls outside three standard deviations only about 0.3% of the time by chance16.
where and are the lower and upper control limits, is the mean score over the stable period, and is the standard deviation of the score over that period. Foundations: mean and Foundations: spread explain both.
Example: the week a checkout change broke phone completeness
On 17 August 2026 a redesign of Wrenfield's checkout went live. In the new layout the phone field moved below the fold, and a developer made it optional "for now". Nobody told Callum. Here is weekly phone completeness from the beginning of July to the end of September.
Callum computes the limits from the seven stable weeks, 27 to 33: 98.9, 99.0, 98.8, 98.9, 99.1, 98.9 and 98.8.
The mean:
So . The standard deviation of those seven values is 0.107 (the squared differences from the mean add up to 0.0686, divided by 6 gives 0.0114, and its square root is 0.107). So:
and the upper limit, :
Any week below is unusual. Week 34 comes in at 93.6%, five full points below the lower limit. That is not noise. The check flags it on the Monday after the first full week, Callum finds the checkout change in the release register within the hour, and the field is required again the following week. Without the trend, the monthly scorecard at the end of August would have shown about 96% and someone might have shrugged.
The same query that builds the chart builds the alert:
-- PostgreSQL: flag weeks outside the control limits of the eight weeks before them
WITH weekly AS (
SELECT period_start,
100.0 * n_passed / n_checked AS score
FROM dq.check_results
WHERE check_id = 'orders.ship_phone_complete'
),
limits AS (
SELECT period_start, score,
avg(score) OVER w AS mean_prev,
stddev_samp(score) OVER w AS sd_prev
FROM weekly
WINDOW w AS (ORDER BY period_start ROWS BETWEEN 8 PRECEDING AND 1 PRECEDING)
)
SELECT period_start, round(score, 1) AS score,
round(mean_prev - 3 * sd_prev, 2) AS lcl
FROM limits
WHERE score < mean_prev - 3 * sd_prev
ORDER BY period_start;
The window ROWS BETWEEN 8 PRECEDING AND 1 PRECEDING computes the limits from the eight weeks before each week, never including the week being judged, so a broken week cannot drag its own limit down. Two practical notes. Very stable checks have a tiny standard deviation, so add a minimum width (for example, never flag a change smaller than half a point) or you will be woken by noise. And after a real change in the business, such as a new checkout that is supposed to collect fewer phones, restart the stable period.
Who owns the quality of a table
Measurements without owners produce reports nobody acts on. The UK framework puts it simply: people who lead and use data are accountable for its quality2. In a small business three roles cover it, and one person can hold more than one.
| Role | What they do | At Wrenfield Home |
|---|---|---|
| Data owner | Decides what the data is for, accepts the thresholds, decides what happens when a check fails | Priya for orders, customers and finance. The buyer for products. |
| Data steward | Writes and maintains the checks, investigates failures, keeps the rule register, tells the owner | Callum |
| Data producer | The system, team or supplier that creates the data, and the only one who can fix it at the source | The checkout code (Callum), the 3PL, the three suppliers, the payment providers |
The point of naming them is that every failing check has somewhere to go. A failing product dimension check goes to the buyer, who calls the supplier. A failing phone check goes to whoever changed the checkout. A failing returns timeliness check goes to Priya, because only she can renegotiate with the 3PL.
Example: what each role did in week 34
Callum, as steward, saw the control chart alert on Monday morning, found the change in the release register and checked that the drop started on the day of the release. Priya, as owner, decided the phone field had to be required again, because the courier's failed deliveries cost more than the friction of one field. Callum, now as producer, made the change test first: a failing test that a checkout without a phone is rejected, then the fix. The test driven development explainer shows that habit in detail. The incident took one conversation, because everyone knew whose decision each step was.
Service levels turn expectations into promises
Thresholds say what good enough looks like for one run. Service levels say what good enough looks like over time, and they are how a data team, even a team of one, makes a promise the business can plan around.
The terms come from site reliability engineering at Google, as set out in its book on the subject17. Here they are, applied to data.
- A service level indicator (SLI) is a carefully defined number that measures some aspect of the service. For data: "the share of days on which yesterday's orders were in the warehouse by 6am".
- A service level objective (SLO) is a target for that indicator: "on at least 95% of days in any 30 day window".
- A service level agreement (SLA) is a contract with consequences when the objective is missed. Inside a small business that is rarely formal. With an outside supplier, such as a 3PL, it can be written into the contract.
An SLO also gives you an error budget: how much failure the target allows. A 95% objective over 30 days allows late days, so one late day is within budget and two are not.
Example: Wrenfield Home's data service levels
Callum and Priya agree three objectives, written in one place where both can see them.
| Indicator | Objective | November 2026 | Met? |
|---|---|---|---|
| Orders loaded by 6am | at least 95% of days in 30 | 29 of 30, 96.7% | yes, one late day (the 14th, a failed nightly job) |
| GA4 to shop purchase ratio inside 0.80 to 0.90 | every week | 4 of 4 weeks | yes |
| 3PL returns in the data within 2 days | at least 90% of returns | 57.9% | no, and it cannot be met by engineering alone |
The third line is the useful one. It turns "returns data is a bit late" into a specific gap between what the business needs and what the supplier delivers. That is the evidence Priya takes to the 3PL when the contract comes up: a clause that returns are reported within one working day of receipt.
Putting it to work: can this number go in the report?
Everything above comes together at one moment: the Monday report is about to go out. The checks have run. Here is the decision Callum follows.
Example: the report for the week ending 29 November
The checks run at 6.30am on Monday 30 November. No check that feeds the report is at error level: the legacy country and product dimension checks are failing, but this report uses neither. The orders source is fresh. The 3PL returns for Friday to Sunday are not yet complete, so returns for those three days are marked provisional. The phone check and the customer uniqueness check are at warning. Callum adds two lines under the headline numbers:
- "Returns for 27 to 29 November are provisional. About 40% of returns reach the data more than two days after they arrive at the warehouse. Final figures on Friday."
- "New customer count may be up to 3% high: some returning customers are counted twice. Fix in progress."
The report goes out at 7am. Priya now knows which numbers to act on and which to hold lightly, and she did not have to ask.
Conclusion
Trust in data is not a feeling, it is a set of measurements. Start by writing down what each table is for and who uses it, because quality only means fit for that purpose. Break quality into the six dimensions (completeness, uniqueness, validity, accuracy, consistency and timeliness), write each check as a precise rule over a defined population, and count. Measure accuracy against an authority where one exists and with a sample and its margin of error where none does, and never mistake a high validity score for accuracy. Derive thresholds from what the user can tolerate, with a warning level and an error level. Store every result, so you can watch each check as a trend and catch the week something breaks. Give every table an owner and a steward, agree service levels for the few things that matter most, and let every report carry a short, honest note about the checks it depends on. Then the next time someone asks whether they can trust a number, the answer will be a specific one.
