Have you ever imported a CSV file into a database, only to discover that some values were incorrect, missing, or interpreted differently than expected?
A CSV file may look perfectly fine when opened in Excel or a text editor, but that does not always mean its data is ready for import. For example, customer IDs may lose leading zeros, dates may use different formats, or numeric values may not represent what the receiving system expects.
This is where a data contract becomes useful. By clearly defining the expected columns, data types, formats, and validation rules, we can reduce the risk of importing incorrect or inconsistent data.
In this article, we’ll explore why agreeing on the meaning and structure of CSV data is important, how a simple data contract can help, and what to check before importing a file into a database.
Describe meaning as well as types
Suppose a partner sends daily invoice data. A useful contract might begin with:
| Field | Example rule |
|---|---|
| InvoiceId | Required text identifier, unique within the agreed source scope. |
| CustomerCode | Text; preserve leading zeros. |
| InvoiceDate | ISO date in YYYY-MM-DD format; invoice issue date. |
| NetAmount | Decimal amount excluding tax; agreed precision and scale. |
| Currency | Required supported currency code. |
The phrase “decimal amount” is not enough without the business definition. Does a negative value represent a credit note? Is tax included? Can the same invoice arrive again as a correction? Those decisions affect the import logic.
Specify the file format explicitly
Agree on encoding, delimiter, quoting rules, headers and line endings. Define how embedded commas and newlines are represented. Use a CSV parser instead of splitting each line on a comma.
In Python, the standard csv module handles structured CSV reading. This small illustration validates the header before processing the rows:
import csv
expected = ["InvoiceId", "CustomerCode", "InvoiceDate",
"NetAmount", "Currency"]
with open("invoices.csv", encoding="utf-8", newline="") as source:
reader = csv.DictReader(source)
if reader.fieldnames != expected:
raise ValueError("Unexpected CSV header")
for row_number, row in enumerate(reader, start=2):
if None in row or any(v is None for v in row.values()):
raise ValueError(f"Wrong field count at record {row_number}")
if not row["InvoiceId"].strip():
raise ValueError(f"Missing InvoiceId at record {row_number}")
# Validate date, decimal, currency and business rules next.
This is a header-and-shape illustration, not a complete invoice loader. Record numbers are logical records; quoted fields can span multiple physical lines. The contract here intentionally requires the exact column order and UTF-8 without a byte-order mark.
Define missing and invalid values separately
An empty amount should not automatically become zero. “Unknown,” “not applicable” and “zero” can have different consequences for a financial report.
Decide which fields are mandatory, which can be empty, and which require rejection of the complete file. For decimal values, use decimal arithmetic and validate the agreed scale rather than relying on binary floating-point values for money.
Keep rejected records explainable
Use a staging area or validation step before updating business tables. Record the source file identifier, processing run, accepted count, rejected count and concise reasons for rejection. Avoid putting entire sensitive rows into unrestricted logs.
Reconcile the counts: every input record should have an understood outcome. For a repeated file, decide whether to reject it, replace an earlier version or process it idempotently.
Make changes visible
If the producer adds a column or changes the meaning of an existing value, agree how that change is announced and versioned. A parser that accepts every new shape silently can hide an upstream breaking change.
The contract does not need to be a large document. One agreed page, a few representative files and clear rejection rules can prevent hours of downstream investigation.
Technical references
Continue learning
For a structured introduction to data management, quality and governance, explore my course Data Management for Beginners – Main Principles on Udemy. Review the curriculum and preview to see whether it fits your next learning goal.
Read Also
- What is Data Management and why it is Important?
- Python Data Access Fundamentals
- SQL Server Database Design Best Practices
Stay connected
Subscribe to the GnoelixiAI Hub newsletter on LinkedIn for practical insights on AI, data and technology.
Watch more on YouTube: SQLNetHub TV and my personal channel.
Originally published on SQLNetHub.
© SQLNetHub
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.