“The Data Is Wrong”: Four Steps to Build Trust in Your Data

It’s Monday morning, and you’re joining your first meeting of the day to discuss a report you built last week. Within the first few minutes, someone points out a number they think is wrong. The room goes quiet and your heart skips a beat. An executive gives you a look, and before you can show the custom visualization you spent hours building, you’re fielding pointed questions about data quality. The only thing you can say is that you’ll look into it and get back to them.
If you’ve ever heard “The data is wrong” or “We can’t trust the data,” you work with data. No data warehouse is flawless, but data quality comes in degrees. In this article, we’ll walk through four practical ways to improve data quality and give your executives confidence in your numbers. The goal is to improve both the quality of your data and how people perceive it.
Communication is key
Before diving into code, share your data quality plan with the leadership team before the project even begins. Feel free to use this article but make sure you own the conversation from day one. In the data world, you are always “guilty until proven innocent.”
It’s also wise to be transparent about data issues before someone opens a ticket. One of the owners at a consulting firm I worked for put it best: “Bad news doesn’t age well.” They’re going to discover the issue anyway, so it’s better they hear it from you, along with your plan and timeline. That way you get ahead of it before the fear-mongers turn a small bug into the company’s dying days.
Step 1: Build error alerting

What this prevents: Hearing about a stale table from an executive, or scrambling to resolve coding issues.
Two kinds of problems should always trigger an alert. One is code that fails, and the other is data that is stale. The code that fails is easy to spot. Stale data is sneakier, because nothing errors and the report simply shows yesterday’s numbers.
I handle both in a single Spark notebook, dq_alerts, that runs right after your loads in Fabric, Databricks, or Synapse. It logs every step to a Delta table, checks every table on a list, and emails the data team when something is wrong.
Catch failures and log them
Start with an audit log table and a small helper that writes one row to it. A DataFrame, unlike an INSERT string, won’t break when an error message contains quotes.
from datetime import datetime
import pandas as pd
import requests
from pyspark.sql import functions as F
spark.sql("CREATE SCHEMA IF NOT EXISTS dq")
spark.sql("""
CREATE TABLE IF NOT EXISTS dq.audit_log (
process_name STRING NOT NULL,
status STRING NOT NULL, -- 'Success' or 'Failed'
error_type STRING,
error_message STRING,
logged_at TIMESTAMP NOT NULL
) USING DELTA
""")
def log_audit(process_name, status, error=None):
row = [(process_name, status,
type(error).__name__ if error else None,
str(error)[:4000] if error else None)]
(spark.createDataFrame(row, "process_name STRING, status STRING, "
"error_type STRING, error_message STRING")
.withColumn("logged_at", F.current_timestamp())
.write.mode("append").saveAsTable("dq.audit_log"))
Then wrap each load in try / except. If the load succeeds, log it as Success. If it fails, log Failed and re-raise the error.
process_name = "Load FactSales"
try:
spark.sql("""
INSERT INTO dw.fact_sales
SELECT order_id, customer_id, order_date, amount,
current_timestamp() AS load_date
FROM stg.sales
WHERE order_date >= date_sub(current_date(), 1)
""")
log_audit(process_name, "Success")
except Exception as e:
log_audit(process_name, "Failed", e)
raise # re-raise so the pipeline marks the notebook activity as failed
Two things are different from SQL Server. First, there’s no BEGIN TRANSACTION or ROLLBACK. Each Delta write either fully succeeds or leaves the table untouched. If a load takes several statements, combine them into a single MERGE so it stays all-or-nothing. Second, spark.sql parses the query when it runs, so even a typo in your SQL raises a ParseException that gets logged.
Check for stale data
For stale data, keep a short list of every table you expect to refresh. I keep mine in Excel and drop it in the lakehouse Files folder, so it’s easy to maintain. Each row names the table, its date column, and how many hours old the data can be before it counts as stale. (The file paths in this article use Fabric’s /lakehouse/default/Files/ folder. On Databricks, use a Unity Catalog volume path such as /Volumes/<catalog>/<schema>/<volume>/ instead.)
Excel: freshness_config.xlsx
SchemaName | TableName | DateColumn | MaxAgeHours | IsActive
dw | fact_sales | load_date | 26 | 1
dw | dim_customer | modified_date | 48 | 1
The notebook loops through the list, runs MAX(date) for each table, and appends every result to a log table. Any table older than its allowed limit is flagged as stale. A missing table or renamed column is caught by the same try / except pattern and also reported as stale, instead of stopping the run.
def check_freshness(config_path="/lakehouse/default/Files/freshness_config.xlsx"):
config = pd.read_excel(config_path)
config = config[config["IsActive"] == 1]
# compare in the same time zone your dates are stored in
checked_at = datetime.now()
results = []
for row in config.itertuples(index=False):
table = f"{row.SchemaName}.{row.TableName}"
note = None
try:
max_date = spark.sql(
f"SELECT MAX(`{row.DateColumn}`) AS max_date "
f"FROM `{row.SchemaName}`.`{row.TableName}`"
).first()["max_date"]
except Exception as e:
max_date, note = None, f"Query failed: {e}"[:4000]
if max_date is None:
hours_old = None
else:
# handles DATE columns too
max_date = pd.Timestamp(max_date).to_pydatetime()
hours_old = round((checked_at - max_date).total_seconds() / 3600, 1)
is_stale = hours_old is None or hours_old > row.MaxAgeHours
results.append((table, max_date, hours_old, int(row.MaxAgeHours),
is_stale, note, checked_at))
log = spark.createDataFrame(results, "table_name STRING, max_date TIMESTAMP, "
"hours_old DOUBLE, max_age_hours INT, is_stale BOOLEAN, "
"note STRING, checked_at TIMESTAMP")
log.write.mode("append").saveAsTable("dq.freshness_log")
return log.filter("is_stale").drop("is_stale", "checked_at").toPandas()
Send the alert
Finally, the notebook pulls any problems into pandas, turns them into an HTML table, and posts it to a Logic App, which sends the email. (Neither Data Factory nor Spark has a built-in email step, so a Logic App is the usual way to send mail in Azure.) Because requests builds the JSON for you, there’s no fighting with quotes in the HTML.
LOGIC_APP_URL = "https://<your-logic-app-url>" # better: read it from Key Vault
def send_alert(subject, df):
html = f"<h3>{subject}</h3>" + df.to_html(index=False, border=1, na_rep="n/a")
response = requests.post(LOGIC_APP_URL, timeout=30, json={
"to": "data-team@company.com",
"subject": subject,
"message": html,
})
response.raise_for_status()
try:
stale = check_freshness()
log_audit("Freshness check", "Success")
except Exception as e:
log_audit("Freshness check", "Failed", e)
raise
if not stale.empty:
send_alert("Stale tables detected", stale)
failures = spark.sql("""
SELECT process_name, error_type, error_message, logged_at
FROM dq.audit_log
WHERE status = 'Failed'
AND logged_at >= current_timestamp() - INTERVAL 24 HOURS
ORDER BY logged_at DESC
""").toPandas()
if not failures.empty:
send_alert("Failed data loads in the last 24 hours", failures)
Schedule the notebook to run after your loads finish, and the data team will be alerted before anyone opens a ticket.
Step 2: Add data contracts to your CI/CD pipeline

What this prevents: Releasing code that quietly adds duplicates, missing values, or broken business rules to production.
Once you’ve built a table in your warehouse, sample a set of rows (I use 1,000) and ask Claude to identify the patterns and return them as a YAML data contract. Look for which columns are unique, can’t be null, and have the proper data types. Remember to mask or remove sensitive fields first, such as Social Security numbers or emails.
Here is a sample of 1,000 rows from dw.dim_customer (sensitive fields masked).Identify the data quality rules this table should always meet: unique keys,required columns, allowed values, formats, and date logic. Return them as a YAML data contract using the format below. Flag any rule you're unsure about.
You can then run that contract against your table in staging before promoting code to production. Tools like Great Expectations, Soda, and dbt tests do this out of the box. If you use one of them, tell Claude which one so it returns the correct YAML format. If you’d rather build your own, the contract can be a simple YAML file like this one.
table: dw.dim_customer
checks:
- name: customer_id is unique
type: unique
column: customer_id
- name: email is populated
type: not_null
column: email
- name: email is a valid format
type: regex
column: email
pattern: '^[^@ ]+@[^@ ]+[.][A-Za-z]{2,}$'
- name: end_date is not before start_date
type: sql
query: SELECT COUNT(*) FROM dw.dim_customer WHERE end_date < start_date
- name: table has a reasonable row count
type: row_count_min
min: 1000
severity: warn # warn = report it, but don't block the release
A short Spark notebook then runs each check against the staging table as part of your release pipeline, and stops the release if any error-level check fails. For a more thorough walkthrough, see the article linked at the end of this section.
Over time, add more checks and warnings. Doing so will stop you from accidentally releasing code that creates duplicate records or end dates before start dates. Regex checks validate formats like emails, phone numbers, and postal codes, and the sql check type lets you test any business rule you can write as a query.
What it looks like when a contract does its job
Here’s a sample of the output when a developer’s new join accidentally creates duplicate customers in staging:
[ERROR] customer_id is unique: 4212 failing
[PASS] email is populated: 0 failing
[PASS] email is a valid format: 0 failing
[PASS] end_date is not before start_date: 0 failing
[PASS] table has a reasonable row count: 0 failing
Contract failed: 1 error-level check. Release stopped.
The release stops, the developer fixes the join, and nobody in the business ever sees 4,212 duplicate customers in their revenue report. The beauty is that the issue never makes it to production, and you save face.
For a more detailed look at data contracts, see Catch Data Issues Before They Reach Production.
Step 3: Build poor data quality dashboards
What this prevents: The data team taking the blame for problems that start in the source systems.
Most data issues can’t be fixed by the data team. If your sales team enters duplicate accounts in Salesforce, or emails that aren’t formatted correctly, your pipeline checks won’t catch them, because the data is technically valid. This is where an analyst can review the source data, identify the common problems, and turn each one into a SQL query that runs on a schedule.
from pyspark.sql import functions as F
DATA_ISSUES_SQL = """
-- Possible duplicate accounts: same name (ignoring case/spaces) and postal code
SELECT 'Salesforce' AS source_system,
'Duplicate Account' AS issue_type,
id AS record_id,
name AS record_name,
owner_name AS record_owner,
CONCAT('Matches ', dup_count - 1, ' other account(s)') AS detail
FROM (
SELECT *,
COUNT(*) OVER (PARTITION BY UPPER(TRIM(name)), billing_postal_code) AS dup_count
FROM stg.sf_account
) AS a
WHERE dup_count > 1
UNION ALL
-- Badly formatted emails
SELECT 'Salesforce', 'Invalid Email',
id, CONCAT_WS(' ', first_name, last_name), owner_name, email
FROM stg.sf_contact
WHERE email IS NOT NULL
AND NOT email RLIKE '^[^@ ]+@[^@ ]+[.][A-Za-z]{2,}$'
"""
Save the results as a Delta table, then append the daily counts to a trend table so you can show leadership how the numbers change over time. The same try / except pattern and log_audit helper from Step 1 make sure you hear about it if this job fails.
try:
issues = spark.sql(DATA_ISSUES_SQL)
# Current list of issues for the dashboard (replaced on every run)
issues.write.mode("overwrite").saveAsTable("dq.data_issues")
# Daily counts for the trend chart (appended on every run)
(issues.groupBy("source_system", "issue_type").count()
.withColumnRenamed("count", "issue_count")
.withColumn("snapshot_date", F.current_date())
.write.mode("append").saveAsTable("dq.issue_trend"))
log_audit("Data issue snapshot", "Success")
except Exception as e:
log_audit("Data issue snapshot", "Failed", e)
raise
Point Power BI at dq.data_issues (Direct Lake or the SQL analytics endpoint both work), include the record owner, and let end users fix their own data.
To be honest, I’ve rarely seen a team actually use these dashboards to fix anything. They usually say it would take too much time and that the issues aren’t material to the business. That’s fine. The real purpose of these dashboards is to educate leadership about the data quality issues you’re facing, and the trend line makes it visible. Once other teams are accountable for their data, there’s less finger-pointing and more collaboration.
Step 4: Check Excel files before loading them
What this prevents: One messy spreadsheet adding poor-quality data to your data warehouse.
Excel files are never going away, because they’re simple. They’re the junk drawer in an otherwise clean kitchen. Everything is technically in there, but good luck finding the scissors. Because Excel doesn’t enforce a schema, an integer column ends up full of decimals, ranges like “10–15,” and values like “50+.”
You have two options. You can build a config-driven process that finds every issue in the file before it’s loaded, or you can replace the spreadsheet with a Power App on a SharePoint (or Dataverse) back end that enforces data governance at entry. Even a few lines of Python can catch the worst offenders.
import pandas as pd
# Read everything as text so nothing gets silently converted
df = pd.read_excel("/lakehouse/default/Files/uploads/budget_upload.xlsx", dtype=str)
qty = df["Quantity"].str.strip()
bad = df[~qty.str.fullmatch(r"-?\d+", na=False)] # blanks, decimals, ranges and "50+" all fail
if not bad.empty:
bad = bad.assign(ExcelRow=bad.index + 2) # +2 = header row + zero-based index
print(bad[["ExcelRow", "Quantity"]].to_string(index=False))
raise ValueError("Fix the rows above before loading.") # fails the notebook run
When a file fails, don’t load any of it. Have the notebook reject the file and use the send_alert function from Step 1 to email the uploader the exact rows to fix. They learn the rules, the fix happens where the mistake was made, and bad data never reaches your warehouse.
For the full config-driven version, see Stop Fixing Your Users’ Sloppy Excel Files. It walks through building the code step by step.
Wrapping up
These four steps will improve data quality and reliability, but all of them need regular review. You’ll keep finding new ways for data to fail, and each one should be added to your checks.
Communication is still the real key. A data engineering or data architecture role is more than a coding job. Today it takes a bit of salesmanship, because you have to sell the company on these initiatives and teach people how data actually works.
Remember the meeting at the start of this article? The fix was simply removing a filter. Don’t expect your users to be data experts, or even to understand the basics of Power BI. As you develop dashboards, work closely with them until they’re comfortable with the tools.
As you build relationships and trust, “We can’t trust the data” turns into “This data doesn’t make sense to me. Help me understand it.”







Comments