Why does a number, a date or an empty field break my pipeline? Data types, schemas and formats
TL;DR
Difficulty: Beginner
Most pipeline failures are a value quietly converted by the wrong type, and none of them raises an error.
- Money never touches a float: use numeric with a currency column, or whole cent, and write down the rounding rule.
- Integers have a ceiling: 2,147,483,647 for 4 bytes, so time stamps in microseconds and big identifiers need bigint.
- Store moments as timestamptz in UTC, derive the local day once, and ask every partner for an offset: the October hour happens twice and PostgreSQL and Python resolve it an hour apart.
- NULL means unknown, not zero: decide and write down what it means for each column.
- Parse files explicitly (1.234,50, 03/04/2026), land raw data as text, quarantine what fails.
- Add columns freely, rename only by expand and contract, and let constraints and dbt contracts turn assumptions into tests.
What to read first
A price a cent short, a delivery on the wrong day, phone numbers without their leading zero, an average that improved because two parcels had not arrived. None of these raises an error, and all of them come from data types, schemas and formats. This chapter explains each mechanism on an invented shop's real looking data, with the SQL and Python to catch it, and ends with an orders table built so most of them cannot happen.
The details that break pipelines are small ones
Ask anyone who has run a data pipeline for a year what broke it, and you rarely hear about the clever parts. You hear about a price that came out a cent short, a delivery that landed on the wrong day, a column of phone numbers that lost its leading zeros, an empty field that turned an average upside down. Each one is tiny. Each one is enough to make a report wrong without a single error message.
This chapter answers one question: why does a number, a date or an empty field break my pipeline? The answer sits in three ideas that the rest of this series leans on.
- A data type says what kind of value a column may hold (a whole number, a decimal, a piece of text, a date) and what you can do with it. Choose the wrong type and the value is changed the moment it is stored, quietly.
- A schema is the list of columns in a table, with their names, types and rules. It is the contract between the system that writes the data and everyone who reads it.
- A format is how a value is written down outside a database: "1,234.50" or "1.234,50", "03/04/2026" or "2026 04 03", a file in comma separated text or in JSON.
Most pipeline failures are a mismatch between two of those three. The previous chapter, where raw data comes from and why it is never clean, showed where the dirt enters. This one shows the exact mechanisms, with the SQL and Python to catch each, and ends with an orders table built so that most of these failures cannot happen.
Example: one Monday at Shannonside Home
Shannonside Home is the invented online homeware shop in Limerick that runs through this whole series (shannonsidehome.example). Niamh owns it. Callum is her developer and data engineer. The shop runs on Ruby on Rails and Solidus with PostgreSQL, sells about 1,980 orders a month at an average order value of about €84, and keeps five years of order history.
On one Monday morning in November, three things go wrong in Callum's pipeline, and none of them raises an error:
- The returns report shows a €1.23 refund on a sofa, where the warehouse file said "1.234,50". The file came from the third party logistics provider (3PL) and wrote the amount the continental way.
- The returns scanned on the night the clocks went back appear an hour apart depending on whether Callum converts them in Python or in PostgreSQL.
- The average delivery time in the dashboard drops from 2.8 days to 1.9 days overnight, because a new export writes "not delivered yet" as an empty field and the dashboard treats it as zero.
By the end of this chapter you will be able to explain each one, find it with a query, and design the column so it cannot happen again. All figures about Shannonside Home are invented for the example.
What a data type is, and why it is your first test
A data type is a promise about a column. A column of type integer promises that every value is a whole number within a fixed range. A column of type date promises a real calendar date. The database checks the promise on every write and refuses anything that breaks it.
That refusal is the lowest cost data quality check you will ever get. It runs on every row, costs nothing to maintain and cannot be forgotten. The flip side is that a type also converts. Put "087 123 4567" into a number column and the leading zero is gone, because a number has no leading zeros. Nothing failed. The value is simply different now.
So choosing a type is two decisions at once: which values to refuse, and which conversions you are willing to accept silently. The rule that follows from it is short. Choose the type by what the value means, not by what it looks like. A phone number looks like a number and means a piece of text. An order number looks like a number and is an identifier you will never add up. A price looks like a decimal and is an exact amount of money.
Example: three columns that look numeric at Shannonside Home
Callum reviews three columns in the newsletter tool's export, which arrives as a spreadsheet:
| Column | Sample value | Looks like | Means | Right type |
|---|---|---|---|---|
| phone | 087 123 4567 | a number | text you dial | text |
| eircode | V94 E5K2 | text | text | text |
| loyalty_points | 1,250 | a number | a count you add up | integer |
The phone column had been loaded as a number in the old dashboard. Every phone number that started with 0 had lost it, and every number with a space had failed to load at all. Stored as text, both survive, and a later chapter on standardising values turns them into one international format.
Integers have a ceiling, and some systems wrap around when they hit it
An integer is a whole number. Computers store it in a fixed number of bits (binary digits), so every integer type has a largest value. PostgreSQL offers three sizes1:
| Type | Bytes | Range |
|---|---|---|
smallint | 2 | minus 32,768 to 32,767 |
integer | 4 | minus 2,147,483,648 to 2,147,483,647 |
bigint | 8 | about minus 9.2 to 9.2 quintillion |
The largest value follows directly from the number of bits. One bit holds the sign, the rest hold the value. The background on powers and logarithms is in Foundations: logarithms.
where is the largest value a signed integer can hold and is the number of bits it is stored in.
For a 4 byte integer, :
So for a 4 byte integer is about 2.1 billion. It sounds enormous until a counter reaches it. In December 2014 the BBC reported that the Gangnam Style video had been viewed more than 2,147,483,647 times, the most a 32 bit counter could show, and YouTube had to upgrade its counter2.
What happens at the ceiling depends on the system. PostgreSQL refuses: SELECT 2147483647::int + 1 fails with "integer out of range". Many programming languages and some file tools instead wrap around to the most negative number and carry on, which is far worse, because the pipeline keeps running with nonsense.
Three places where this bites a shop:
- Event time stamps. The GA4 export to BigQuery stores
event_timestampas microseconds since 1970 in UTC3. A value from October 2026 is about 1,792,003,327,123,456, roughly 834,000 times the 32 bit ceiling. Load it into anintegercolumn and it fails, or in a tool that wraps, it becomes garbage. - Identifiers in JSON. JavaScript stores every number as a 64 bit floating point value, and only integers up to 9,007,199,254,740,991 are exact4. A 64 bit identifier above that, sent as a JSON number to a JavaScript front end, is rounded.
JSON.parse('{"id": 9007199254740993}').idgives 9007199254740992. That is why many APIs send large identifiers as strings. - Old primary keys. The original Solidus base migration created most identifier columns, such as
user_idandvariant_idon orders and line items, asinteger5. For a shop with 23,760 orders a year that ceiling is centuries away. For an events table with millions of rows a day it is not.
Example: the GA4 time stamp that would not load
Callum copies the GA4 purchases into the shop's PostgreSQL for a quick check, into a table he creates by hand:
-- PostgreSQL: the wrong type
CREATE TABLE ga4_purchase_check (
transaction_id text,
event_timestamp integer -- 4 bytes: far too small
);
INSERT INTO ga4_purchase_check VALUES ('R482913', 1792003327123456);
-- ERROR: integer out of range
The fix is bigint, whose ceiling of about 9.2 quintillion microseconds lasts until roughly the year 294,000. Better still, convert the microseconds into a real time stamp on the way in, so nobody downstream has to remember the unit:
-- PostgreSQL: keep the raw number, add the meaning
CREATE TABLE ga4_purchase_check (
transaction_id text NOT NULL,
event_timestamp_us bigint NOT NULL,
event_at timestamptz GENERATED ALWAYS AS
(to_timestamp(event_timestamp_us / 1000000.0)) STORED
);
The _us suffix in the name says the unit. A unit in the column name is a small habit that prevents a whole class of mistakes, the same class that turns millimetres into centimetres in supplier feeds.
Floating point numbers are fast, approximate, and wrong for money
Most programming languages and databases have a second kind of number for values with a fractional part: floating point. PostgreSQL calls them real (4 bytes) and double precision (8 bytes), BigQuery calls the 8 byte kind FLOAT64, Python calls it float. They follow the IEEE 754 standard6.
Floating point stores a number in binary, as a fraction times a power of two. That makes it fast and able to hold huge and tiny values. It also means that most decimal fractions cannot be stored exactly, for the same reason that one third cannot be written exactly in decimal: 0.333 goes on for ever. In binary, 0.1 goes on for ever. The computer stores the nearest value it can.
PostgreSQL's own documentation calls these types "inexact": some values "cannot be converted exactly to the internal format and are stored as approximations"1. David Goldberg's classic paper explains the mathematics in full7. The everyday consequences:
# Python 3.13
>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 == 0.3
False
>>> round(2.675, 2) # you expect 2.68
2.67
>>> int(19.99 * 100) # cent, by truncation
1998
None of these is a bug in Python. The Python documentation says so in as many words, and explains round(2.675, 2) the same way: 2.675 is stored as a value a hair below 2.67589. You get the same results in Ruby, JavaScript, Java and in the database.
Two further traps catch experienced engineers.
- The display hides the error. PostgreSQL prints a
realcolumn holding 72.95 as72.95, because it shows the shortest text that reads back to the same stored value. Cast the same value todouble precisionand you see what is really stored:72.94999694824219. What you see in a query result is not always what you have. - The same code can give different answers. Since Python 3.12, the built in
sum()adds floats with a more accurate algorithm9.sum([0.1] * 10)now returns exactly 1.0, while a plain loop adding 0.1 ten times still gives 0.9999999999999999. Upgrade the interpreter and a reconciliation that used to fail by a fraction now passes, or the other way round.
Spreadsheets are floating point too. Microsoft documents that Excel follows IEEE 754 and keeps 15 significant digits of precision10. Type a 16 digit reference number into a cell and the last digit becomes a zero.
How far apart two neighbouring floats are
Every floating point number has a fixed number of significant binary digits, : 24 for real, 53 for double precision. So the gap between one representable number and the next grows with the size of the number. That gap is called the unit in the last place (ULP), and you can work it out with logarithms (see Foundations: logarithms):
where is the distance from to the next representable number, is the power of two just below (rounded down to a whole number), and is the number of significant binary digits of the type.
Any value you store is rounded to the nearest point on that grid, so the error of a single stored value can be up to half a ULP. Every addition rounds again.
Example: the legacy prices at Shannonside Home
Shannonside Home moved to Solidus from an older platform. One of the known problems of the shop's data is that the legacy import stored prices as floating point numbers. Callum reconstructs what happened, step by step, with an invented but faithful simulation of one year: 1,400 products priced between €5.00 and €76.99 ending in .00, .50, .95 or .99, 1,980 orders a month, 39,791 order lines, €1,973,696.02 of revenue.
Step 1: the stored price. The old platform kept prices in a real column. €84.95 was stored as 84.94999694824219.
Step 2: the conversion to cent. The import script converted to whole cent with (price * 100).to_i in Ruby. to_i cuts off the fraction, it does not round. So 8494.999694824219 became 8494, and the line lost a cent. Of the 1,400 catalogue prices, 298 (21.3%) lose a cent this way, all of them ending in .95 or .99.
Step 3: the orders. Over the year, 8,196 of the 39,791 lines (20.6%) carry a price one cent short. The lost cent add up to €97.82. That is small money. The damage is elsewhere: 7,416 of the 23,760 orders (31.2%) no longer match the amount Stripe actually settled. Every one of them shows up as a difference in the payment reconciliation, and Callum spends days chasing differences that are not real.
Step 4: the running total. The old platform's sales report kept a year to date total in a real column too, adding each line as it came. With , work out the gap at January's total of €164,313.33:
So in January every stored total sits on a grid with steps of , about 1.6 cent. By December the total is €1,973,696.02, and the gap has grown:
So with , from about €1,048,576 upwards the total can only move in steps of 12.5 cent, and every one of the 3,300 or so additions a month is rounded to the nearest step. The errors no longer cancel out. By December the report's total is €202.73 higher than the true total.
The lesson is not that the amounts are large. They are not. The lesson is that two different errors, one systematic and one that drifts, turn a set of books that should agree to the cent into a set that never quite agrees, and nobody can tell real differences from noise any more. The migration of the old orders is covered in depth in migrating order and purchase history. For this chapter, the rule is simple: money never touches a floating point type, not in the database, not in the import script, not in the report.
Money belongs in NUMERIC, or in whole cent
There are two correct ways to store money, and one popular wrong one.
Correct, option one: an exact decimal type. PostgreSQL's numeric(p, s) (also spelled decimal) stores digits exactly. p is the total number of digits, s the digits after the decimal point. The documentation recommends it explicitly: "If you require exact storage and calculations (such as for monetary amounts), use the numeric type instead."1 Solidus itself stores order totals, line item prices and catalogue prices as decimal with precision 10 and scale 2, so up to €99,999,999.995. BigQuery's NUMERIC has precision 38 and scale 911.
Correct, option two: integers in the minor unit. Store 8495 cent instead of €84.95. Integer arithmetic is exact, fast and identical in every language. Stripe's API works this way: to charge 10 US dollars you send 1000, and for a currency without a minor unit, such as the Japanese yen, the amount is the whole number itself12. The price is that every reader must know the unit, so the column name says it: amount_cent or amount_minor, with the currency next to it.
Wrong: PostgreSQL's money type. It looks tailor made and is not. The PostgreSQL wiki's list of things not to do explains why: it does not store a currency, assumes the one set in the server's lc_monetary setting, and if that setting changes, every stored amount changes meaning with it13.
Whichever you choose, store the currency in its own column, as a three letter ISO 4217 code such as EUR or GBP. Solidus does exactly this with a currency column on orders and prices5. A number without its currency is not an amount of money.
Exact storage does not end the job, because money is still rounded whenever you divide it: VAT out of a gross price, a discount spread over lines, a refund split across payments. Three rounding decisions belong in writing, because a different choice gives a different cent:
- Where you round: per line, or once per order.
- How you round ties: PostgreSQL's
numericrounds ties away from zero (2.5 becomes 3), while floating point rounds ties to the nearest even number (2.5 becomes 2)1. Python'sDecimallets you choose. - Where the leftover cent goes when an amount does not divide evenly.
Example: VAT and a discount at Shannonside Home, to the cent
Prices at Shannonside Home include VAT at the standard rate of 23%. The VAT inside a gross price follows from the rate (see Foundations: percentages):
where is the VAT contained in the price, is the gross price including VAT and is the VAT rate as a fraction ( at the Irish standard rate).
With the fraction is , about 18.7% of the gross price. One basket holds a candle at €4.99, a vase at €14.95 and a set of coasters at €3.45, €23.39 in total.
Rounded per line, half up:
| Line | Gross | VAT unrounded | VAT rounded |
|---|---|---|---|
| Candle | €4.99 | 0.933089 | €0.93 |
| Vase | €14.95 | 2.795528 | €2.80 |
| Coasters | €3.45 | 0.645122 | €0.65 |
| Total | €23.39 | €4.38 |
Rounded once on the order: €23.39 × 0.23 ÷ 1.23 = 4.373740, which rounds to €4.37.
A cent apart, from identical data. Neither is wrong, but the shop, the accounting export and the warehouse must all use the same rule, or they will never reconcile. Callum writes the rule down (Solidus calculates tax per line, so the warehouse does too) and adds a test for this exact basket.
Now a €5.00 discount spread over three lines of €10.00 each. Each line's share is €1.666667. Rounded half up, that is €1.67 three times, which adds up to €5.01: the shop has given away a cent it never offered. The fix is the largest remainder method: round every share down to €1.66 (total €4.98), then hand the 2 missing cent, one each, to the lines with the largest remainders. All three remainders are equal, so a fixed tie rule (first line first) decides. Result: €1.67, €1.67, €1.66, exactly €5.00.
# Python 3.13, standard library only
from decimal import Decimal, ROUND_DOWN
def allocate(total: Decimal, weights: list[Decimal]) -> list[Decimal]:
"""Split a money amount over weights so the parts add up exactly."""
cent = Decimal("0.01")
raw = [total * w / sum(weights) for w in weights]
parts = [r.quantize(cent, rounding=ROUND_DOWN) for r in raw]
leftover = int((total - sum(parts)) / cent) # whole cent still to place
by_remainder = sorted(range(len(raw)), key=lambda i: raw[i] - parts[i], reverse=True)
for i in by_remainder[:leftover]:
parts[i] += cent
return parts
print(allocate(Decimal("5.00"), [Decimal("10.00")] * 3))
# [Decimal('1.67'), Decimal('1.67'), Decimal('1.66')]
Note Decimal("5.00") with quotes. Decimal(0.1) without quotes copies the float's error into the decimal: it gives 0.1000000000000000055511151231257827021181583404541015625.
Text is not as simple as it looks: length, bytes and invisible differences
Text columns cause fewer crashes and more silent mismatches than any other type. Four details matter.
Length limits. PostgreSQL has text, varchar(n) and char(n). Its documentation states there is no performance difference between them, apart from the padding of char(n) and a small cost for checking the length14. So a length limit is a business rule, not a speed trick. Use text unless a real rule exists, and then write the rule as a check constraint, which can test the format and not only the length13.
Padding. char(n) pads values with spaces to the full width, and then ignores trailing spaces when comparing. In PostgreSQL, 'abc'::char(5) = 'abc '::char(5) is true, and length('abc'::char(5)) is 3. That surprises everyone who meets it. The PostgreSQL wiki recommends never using char(n), even for fixed length codes13.
Characters versus bytes. Modern databases store text as UTF 8, where a character takes 1 to 4 bytes. "Seán" is 4 characters and 5 bytes, because á takes two. Any limit set in bytes (some file formats and older tools) cuts names in the middle of a letter.
The same word in two spellings. Unicode can write á as one character, or as a plain a followed by a combining acute accent, the fada. Both look identical on screen. To the database they are different strings. The forms are called NFC (composed) and NFD (decomposed), and macOS file names, some form inputs and some exports produce the decomposed form. PostgreSQL's normalize() function converts a string to one form15, and nondeterministic collations can compare strings in different normal forms as equal, at the cost of some features16.
Case and white space. "Niamh@Example.com", "niamh@example.com" and "niamh@example.com " (with a space at the end) are three different strings. This is exactly how 3.1% of Shannonside Home's customer accounts became duplicates. A later chapter on duplicates and entity resolution goes all the way. The type lesson here is to normalise on the way into the clean layer, and to keep the original next to it.
Example: one customer, two strings
A customer called Seán Ó Briain has an account created on the website and a guest order placed through a form that sends decomposed text. Callum runs:
-- PostgreSQL
SELECT 'Seán' = E'Sea\u0301n' AS raw_equal,
'Seán' = normalize(E'Sea\u0301n', NFC) AS nfc_equal,
length(E'Sea\u0301n') AS chars_decomposed,
octet_length('Seán') AS bytes_composed;
| raw_equal | nfc_equal | chars_decomposed | bytes_composed |
|---|---|---|---|
| false | true | 5 | 5 |
The two names only match after normalising. In the staging model Callum therefore builds a comparison key next to the original, and never overwrites the original:
-- PostgreSQL: clean comparison keys, original kept
SELECT id,
email AS email_original,
lower(btrim(normalize(email, NFC))) AS email_key,
firstname AS firstname_original,
normalize(btrim(firstname), NFC) AS firstname_clean
FROM raw_shop.spree_users;
NULL means "I do not know", and it changes the logic
NULL is how SQL says a value is missing. It is not zero. It is not an empty string. It is the absence of a value, and SQL treats it as unknown. That single idea explains most of the surprises.
Ordinary comparisons with NULL give NULL, not true or false. PostgreSQL's documentation is explicit: 7 = NULL yields null, and "NULL is not equal to NULL"17. So SQL runs on three valued logic: true, false and unknown. A WHERE clause keeps a row only when the condition is true, so unknown rows quietly disappear.
| A | B | A AND B | A OR B | NOT A |
|---|---|---|---|---|
| true | unknown | unknown | true | false |
| false | unknown | false | unknown | true |
| unknown | unknown | unknown | unknown | unknown |
Read it like a person who does not know B. "True and I do not know" could be either, so it is unknown. "True or anything" is true whatever B is.
To compare two values where either may be NULL, use IS NOT DISTINCT FROM. It behaves like = except that two NULLs count as equal and a NULL never equals a value17. This matters in change detection, where you compare yesterday's row with today's and a NULL that stayed NULL must not count as a change.
Aggregates ignore NULL: avg, sum and count(column) only look at the rows that have a value, while count(*) counts all rows. The chapter on SQL traps later in this series covers the counting traps in full.
Different systems also disagree about what empty means:
- In PostgreSQL an empty string
''and NULL are different things. - Oracle Database treats a text value of length zero as NULL18. Migrate between the two and empty strings change meaning.
- pandas reads the empty string, "NaN", "N/A", "NULL" and other common spellings as missing by default, even in a column you asked to be text, unless you turn that off with
keep_default_na=False19.
And "missing" itself has at least three meanings, which the type cannot tell apart: unknown (the customer has a phone but did not give it), not applicable (a gift card has no weight) and not yet (the parcel has not been delivered). About 2% of Shannonside Home's orders have a missing or invalid phone number, and those are the first kind. If the difference matters to a report, store it in a separate status column instead of hoping NULL carries it.
Example: the delivery time that improved overnight
The 3PL changes its export. Parcels not yet delivered used to be left out of the file. Now they appear with an empty delivery date. Take five parcels shipped on Monday, with delivery times of 2, 3, 4 days and two not yet delivered.
- Leaving the undelivered parcels out (NULL, ignored by
avg): days. - Treating empty as zero, as the old dashboard did with
coalesce(days, 0): days.
The dashboard reported faster deliveries because two parcels had not arrived. Both numbers are wrong for the question "how long do deliveries take?", because the two missing parcels will take longer than the ones already delivered. The honest answer is the average over parcels shipped long enough ago that nearly all have arrived (for example, those shipped 10 or more days ago), with the share still in transit shown next to it. A later chapter on missing data covers these choices properly.
-- PostgreSQL: the honest version
SELECT avg(delivered_on - shipped_on) AS avg_days_delivered,
count(*) FILTER (WHERE delivered_on IS NULL) AS still_in_transit,
count(*) AS shipped
FROM staging.tpl_shipments
WHERE shipped_on <= current_date - 10;
Booleans: true, false, and the strings that pretend to be them
A boolean is a yes or no value, and in SQL it has a third state, NULL, for unknown20. Files rarely carry real booleans. They carry text: "true", "TRUE", "Y", "yes", "1", "on", "Ja", or an empty cell. PostgreSQL's boolean input accepts true, yes, on and 1 for true (and their opposites), unique prefixes such as t and n, in any case, ignoring white space20. That generosity is handy and also dangerous, because a column you meant to be strict accepts "n" from a typo.
The safe pattern is an explicit mapping in the staging layer, which turns every known spelling into true or false and every unknown spelling into an error you see:
-- PostgreSQL: map the newsletter export's opt in column explicitly
SELECT email_key,
CASE lower(btrim(opt_in_raw))
WHEN 'yes' THEN true
WHEN 'y' THEN true
WHEN '1' THEN true
WHEN 'no' THEN false
WHEN 'n' THEN false
WHEN '0' THEN false
WHEN '' THEN NULL -- not answered: unknown, not "no"
END AS opted_in,
opt_in_raw
FROM raw_newsletter.contacts;
-- Any spelling not listed becomes NULL too, so a test checks for
-- opt_in_raw values outside the known list and fails loudly.
Example: the consent column at Shannonside Home
The newsletter export for the 38,000 contacts has an opt_in column. Callum counts its distinct values: "Yes" 31,214, "yes" 2,040, "No" 3,910, "" (empty) 828, "Y" 6, "subscribed" 2. Without a mapping, a naive cast fails on "subscribed" and turns "" into an error too. With the mapping above, 33,260 contacts map to true, 3,910 to false, 828 to unknown, and the test flags the 2 "subscribed" rows, and any new spelling that appears tomorrow, for a person to decide. For a consent field, unknown must never be treated as yes.
Dates and times: a moment, or a picture of a clock
Time is where pipelines fail most often, because one word, "time", hides two different things.
- A moment: the instant an order was paid. It is the same instant everywhere on Earth. In Limerick it was 2.30pm, in Vienna 3.30pm, and it is still one moment.
- A wall clock reading: "14:30 on 1 July". Without knowing where the clock hung, you do not know which moment it means.
PostgreSQL has a type for each. timestamp with time zone (short: timestamptz) stores a moment: input with a zone is converted to UTC, input without one is read in the session's time zone, and "in either case, the value is stored internally as UTC"21. timestamp without time zone stores the picture of the clock, and "PostgreSQL will silently ignore any time zone indication" in its input21. The PostgreSQL wiki puts it plainly: don't use timestamp for points in time, and don't use it to store UTC either, because the database cannot know the values are UTC13.
Here is the trap that follows for every Rails shop. Rails creates datetime columns as timestamp without time zone by default "for legacy reasons", and you have to opt in to timestamptz with the datetime_type setting22. Rails then writes UTC into those columns and converts on reading, because Active Record's default time zone is UTC23. The Solidus tables, such as spree_orders.completed_at, were created this way5. So the values are UTC, but only the application knows it. Any other tool that reads the table, a BI tool, an extract script, a colleague in psql, sees a wall clock reading and may interpret it in its own time zone.
For date formats outside the database, use ISO 8601, in the profile that RFC 3339 defines for the internet: 2026-07-01T13:30:00Z or 2026-07-01T14:30:00+01:00, always with the offset24. It sorts correctly as text, it is unambiguous, and every serious library reads it.
Example: the order that changed date
An order at Shannonside Home is completed at 11.30pm on 30 June 2026, Irish time. Solidus stores completed_at as 2026-06-30 22:30:00 in a timestamp without time zone column, which is UTC by convention.
Callum's extract reads the column and loads it into BigQuery as TIMESTAMP, which "represents an absolute point in time"11. If the extract treats the value as UTC, the order lands on 30 June, correctly. If a tool reads it as local time, there is no visible error at all, but every time stamp is one hour off during Irish summer time.
He also checks the opposite case in PostgreSQL, where the session time zone decides how a picture of a clock is understood:
-- PostgreSQL: the same input, two types
SET TimeZone = 'Europe/Dublin';
CREATE TEMP TABLE t (a timestamp, b timestamptz);
INSERT INTO t VALUES ('2026-07-01 12:00', '2026-07-01 12:00');
SET TimeZone = 'UTC';
SELECT a, b FROM t;
| a | b |
|---|---|
2026-07-01 12:00:00 | 2026-07-01 11:00:00+00 |
Column b understood "12:00" as noon in Ireland, a moment, and shows it in UTC. Column a kept the picture of the clock and has no idea where it hung. In the warehouse Callum converts explicitly, once, in the staging model: completed_at AT TIME ZONE 'UTC' turns the Solidus value into a timestamptz, and from then on every column holding a moment has a type that knows it.
The "day" of an order is a separate decision. For the report, Niamh wants days as her customers lived them, in Irish time. So the clean model stores the moment in UTC and derives the local date in one named column, order_date_dublin, instead of letting every query truncate in whatever zone the session happens to be in. The GA4 export makes the same split: event_date is the date in the property's time zone, while event_timestamp is UTC3.
Daylight saving: the hour that does not exist and the hour that happens twice
Twice a year, local clocks in Ireland, the UK, Germany and Austria jump. EU law sets the moments for every member state: 1am Greenwich Mean Time on the last Sunday in March and on the last Sunday in October25. In 2026 that is 29 March and 25 October. In 2027, 28 March and 31 October.
Ireland has a twist that matters to software. Under the Standard Time (Amendment) Act 1971, Irish standard time is the summer time, and Greenwich Mean Time is legally a period of "winter time"26. The IANA time zone database, which almost every system uses, has modelled this since 2018 as standard time in summer with a negative daylight saving offset in winter, and keeps a second form for software that cannot handle negative offsets27. The UTC offsets are the same either way. What changes is which period a library calls "daylight saving", so never infer the offset from a daylight saving flag. Ask for the offset itself.
So in Limerick on 29 March 2026, no clock ever shows 1.30am: the hour from 1am to 2am does not exist. And on 25 October 2026, every clock shows 1.30am twice, once in Irish summer time and once in Greenwich Mean Time. That day has 25 hours. A wall clock reading from that night, without an offset, is genuinely ambiguous.
Databases and languages must still pick an answer, and they do not all pick the same one.
- PostgreSQL: a time in the missing hour gets the offset in force just before the jump. An ambiguous time in the repeated hour gets the offset in force just after the change back28. In Ireland that is Greenwich Mean Time, the legal winter time, so describing the rule as "standard time", as many guides do, is wrong here, while the result is right.
- Python:
zoneinfofollows PEP 495. For an ambiguous time it uses the offset from before the transition whenfold=0, the default, and the offset after it only whenfold=129.
So for the repeated hour, PostgreSQL and Python disagree by exactly one hour, and neither raises an error.
Example: the returns scanned on the night the clocks went back
The 3PL's daily file gives scan times as local time with no zone, one of the known problems of Shannonside Home's data. On the night of 25 October 2026 the warehouse night shift scanned returns through the repeated hour. Callum converts one row both ways:
-- PostgreSQL
SELECT timestamp '2026-10-25 01:30' AT TIME ZONE 'Europe/Dublin';
-- 2026-10-25 01:30:00+00 (read as GMT, the second 1.30am)
# Python 3.13
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
scan = datetime(2026, 10, 25, 1, 30, tzinfo=ZoneInfo("Europe/Dublin"))
print(scan.astimezone(timezone.utc))
# 2026-10-25 00:30:00+00:00 (fold=0: read as Irish summer time, the first 1.30am)
The same scan lands at 00:30 UTC in one system and 01:30 UTC in the other. Joined to the refunds in Stripe by time window, some returns now appear to have been refunded before they were scanned.
The day length shows up in the arithmetic too. In PostgreSQL, the difference between 3am on 24 October and 3am on 25 October is 1 day 01:00:00 with timestamptz and 1 day with plain timestamp. Only the first is true.
Callum counts the scans per clock hour that night:
The 1am bar holds two real hours, roughly 13 and 14 scans. Nothing in the file says which scan belongs to which. Callum has three options, in order of preference:
- Fix it at the source. Ask the 3PL to send UTC, or the local time with its offset (
2026-10-25T01:30:00+01:00). Most warehouse systems can. - Use the order of the rows. If the file is strictly in scan order, the scans whose time goes backwards (from 01:59 to 01:00) mark the switch to GMT. That works only while the order can be trusted, so it needs a test.
- Flag what stays ambiguous. Mark rows in the repeated hour as
ambiguous_local_time = true, convert them by one stated rule, and let reports that depend on the exact hour exclude or widen them.
The missing hour in March needs the mirror rule: a scan stamped 1.30am on 29 March cannot be right, so it is flagged as invalid and checked, not silently shifted.
Day before month, or month before day
"03/04/2026" is 3 April in Ireland, the UK, Germany and Austria, and 4 March in the United States. Both readings are valid dates, so nothing fails. PostgreSQL's date input documentation notes exactly this, that day, month and year order "is ambiguous" for some formats, and lets you set the expected order with the DateStyle setting21. The same string gives two dates depending on that one setting:
-- PostgreSQL
SET DateStyle = 'ISO, DMY'; SELECT '03/04/2026'::date; -- 2026-04-03
SET DateStyle = 'ISO, MDY'; SELECT '03/04/2026'::date; -- 2026-03-04
Never rely on a session setting for a file. Parse with an explicit format, to_date(value, 'DD/MM/YYYY'), and better, ask for ISO 8601 in every interface you control.
Spreadsheets add their own twist. Excel stores dates as serial numbers counted from 1900, and Microsoft documents that it wrongly treats 1900 as a leap year, a choice made for compatibility with Lotus 1 2 330. Serial dates before March 1900 are therefore off by a day, and a column of dates exported as numbers needs the right starting point to convert.
Example: how many supplier dates are ambiguous?
A supplier feed sends availability dates as "dd/mm/yyyy" without saying so. Callum wants to know how often the order cannot be detected from the value alone. A date is ambiguous when both its day and its month are 12 or less, and day and month differ (3 April versus 4 March; 5 May reads the same either way). If dates are spread evenly over the year, the share follows from counting (see Foundations: probability):
where is the probability that a date reads as a valid but different date with day and month swapped, counts the day and month pairs where both are 12 or less, the subtracted removes the pairs where day equals month, and is the number of days in the year.
So : about 36% of dates cannot tell you their own format. The other 64% can, because a day of 13 or more cannot be a month. That gives Callum a test: in any batch from this supplier, if a value has a first part above 12, the format must be day first, and if a value has a second part above 12, the feed has switched to month first. One such row fails the batch.
-- PostgreSQL: detect the date order of a batch from its own values
SELECT count(*) FILTER (WHERE split_part(available_raw, '/', 1)::int > 12) AS proves_day_first,
count(*) FILTER (WHERE split_part(available_raw, '/', 2)::int > 12) AS proves_month_first
FROM raw_suppliers.feed_rows
WHERE batch_id = 'b_2026_11_16';
-- proves_month_first must be 0 for a day first feed, or the load stops.
Numbers written the local way
In Ireland and the UK, one thousand two hundred and thirty four euro and fifty cent is written 1,234.50. In Germany and Austria the same amount is 1.234,50. The comma and the full stop swap jobs. A parser expecting one convention, fed the other, does one of three things: it fails ("1.234,50" is not a number), it stops early ("1.234,50" read as 1.234), or worst, it succeeds with a wrong value ("1,234" in German means one point two three four, and an English parser reads one thousand two hundred and thirty four). The last case is a factor of 1,000 with no error.
Files written the continental way usually use a semicolon as the column delimiter, precisely because the comma is busy as the decimal mark. That is why the 3PL file is semicolon delimited.
The tools can be told about the convention. pandas' read_csv has decimal and thousands parameters19. polars' read_csv has decimal_comma, which, in the documentation's words, parses floats using a comma as the decimal separator31. And there is the catch: both give you floating point numbers. For money, that throws away the exactness you just fought for. The safe way is to read the column as text and convert it yourself, with a strict pattern, into an exact type.
Example: the sofa refund of €1.23
The 3PL's returns file at Shannonside Home (in this invented example its export follows a continental locale) contains refund_amount;1.234,50 for a returned sofa. The old loader used Python's float() after replacing nothing, failed on the comma, and a "fix" added later replaced the comma with a full stop: "1.234.50", which a lenient parser read as 1.234. The report showed a refund of €1.23.
Callum replaces it with a parser that knows exactly one format and refuses everything else:
# Python 3.13, standard library only
import re
from decimal import Decimal
CONTINENTAL = re.compile(r"^-?\d{1,3}(\.\d{3})*,\d{2}$|^-?\d+,\d{2}$")
def parse_continental_amount(text: str) -> Decimal:
"""'1.234,50' -> Decimal('1234.50'). Anything else raises ValueError."""
value = text.strip()
if not CONTINENTAL.match(value):
raise ValueError(f"not a continental amount: {text!r}")
return Decimal(value.replace(".", "").replace(",", "."))
And the tests that pin it down, written first:
# test_amounts.py, run with pytest
import pytest
from decimal import Decimal
from amounts import parse_continental_amount
@pytest.mark.parametrize("raw, expected", [
("1.234,50", Decimal("1234.50")),
("84,95", Decimal("84.95")),
("0,29", Decimal("0.29")),
("-15,00", Decimal("-15.00")),
("1234,50", Decimal("1234.50")),
])
def test_valid_amounts(raw, expected):
assert parse_continental_amount(raw) == expected
@pytest.mark.parametrize("raw", ["1,234.50", "1.234", "1.234.50", "", "12,5", "€84,95"])
def test_ambiguous_or_foreign_amounts_are_refused(raw):
with pytest.raises(ValueError):
parse_continental_amount(raw)
"1.234" is refused on purpose: it could be 1,234 or 1.234, and a guess is how the €1.23 sofa happened. A refused row goes to a quarantine table with the reason, and the load carries on with the rest. Working this way, test first, is the same discipline I use for application code, explained in test driven development explained.
Codes and enums: small closed lists that keep growing
Many columns hold one value from a short, known list: an order state, a country, a currency, a return reason. Getting these right is mostly about deciding how strict to be.
Solidus keeps the order state as a plain string column, state, driven by a state machine in the application: cart, address, delivery, payment, confirm, complete, canceled, returned, awaiting_return and resumed532. The database itself would accept any text there. The rule lives in the code.
In your own warehouse tables you have three ways to make a list strict:
| Option | How | Strength | Weakness |
|---|---|---|---|
| Enum type | CREATE TYPE order_state AS ENUM (...) | compact, ordered, refuses unknown values | values cannot be removed or reordered without recreating the type32 |
| Check constraint | CHECK (state IN ('cart', ...)) | simple, easy to change in a migration | the list lives in the table definition |
| Lookup table | a table of valid codes plus a foreign key | the list is data, can carry labels and translations | one more join |
PostgreSQL documents that enum values are case sensitive and are ordered by the order they were listed when the type was created, and that existing values cannot be removed32. For a list that changes with the business (return reasons, sales channels), a lookup table ages best. For a list that only changes with the law or a standard, a check constraint is enough.
Where a standard code exists, use it. Countries as ISO 3166 two letter codes (Ireland is IE, the United Kingdom is GB)33, currencies as ISO 4217 three letter codes. Free text is how the same country ends up spelled five ways.
Example: one country, five spellings
Old addresses at Shannonside Home, imported from the previous platform, hold the country as free text. Callum counts the 52,400 old addresses (invented figures):
| Raw value | Rows | Maps to |
|---|---|---|
| IE | 31,000 | IE |
| Ireland | 12,300 | IE |
| Republic of Ireland | 6,900 | IE |
| ROI | 1,800 | IE |
| Irl | 400 | IE |
All five mean the same delivery country, so a report "orders by country" showed five rows for one country. And the opposite trap sits next to it: a few hundred old addresses in Northern Ireland were typed as "Ireland" by customers in Derry and Belfast. They belong to GB, with a different VAT treatment and different carriers, so the mapping is a business decision that looks at the whole address, not only at the country word. Callum stores the mapping as a small lookup table, country_aliases(raw_value, iso_code), so that a sixth spelling tomorrow appears as an unmapped value in a test, not as a sixth row in a report.
JSON columns are flexible until somebody reads them
A JSON column stores a whole document in one field: a webhook from Stripe, the raw response of an API, a product's changing attributes. It is a fine place to keep data you received. It is a poor place to use data from, because the type checks that protect the rest of the table stop at its edge.
PostgreSQL has two JSON types. json stores the text exactly as received. jsonb stores a parsed form that is faster to query, but "does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys", keeping only the last value when a key repeats34. Two lines show the difference:
-- PostgreSQL
SELECT '{"price": 72.95, "price": 80.00}'::jsonb; -- {"price": 80.00}
SELECT '{"price": 72.95, "price": 80.00}'::json; -- {"price": 72.95, "price": 80.00}
For a raw archive where you may need to prove what a partner sent, json (or the original text) is the honest choice. For a working copy, jsonb.
Numbers inside JSON have no declared type. The JSON standard allows any precision but warns that good interoperability comes from expecting no more than IEEE 754 double precision35. So a JSON price can lose exactness in any software that reads it as a float, and a large identifier can lose its last digits in JavaScript, as shown earlier4.
Values extracted with the ->> operator come out as text, so the type is your job:
-- PostgreSQL: extract with an explicit, checked type
SELECT payload ->> 'id' AS stripe_event_id,
(payload -> 'data' -> 'object' ->> 'amount')::bigint AS amount_minor,
upper(payload -> 'data' -> 'object' ->> 'currency') AS currency
FROM raw_stripe.webhook_events
WHERE payload ->> 'type' = 'charge.refunded';
If one event ever sends "amount": "7295" as a string, the cast still works. If it sends "72.95", the cast to bigint fails, loudly, which is what you want.
Example: the GA4 value that lived in two columns
The GA4 BigQuery export is schema on read in miniature. Event parameters arrive as a list of keys and values, and each value sits in whichever field matches how it was sent: string_value, int_value or double_value3. At Shannonside Home, purchases sent from the server carry value as a decimal, but a few test purchases sent from a tag carried a whole number, 84, which lands in int_value. A query that reads only double_value silently drops them.
-- BigQuery (GoogleSQL)
SELECT
ecommerce.transaction_id,
ecommerce.purchase_revenue,
(SELECT COALESCE(CAST(p.value.int_value AS FLOAT64),
p.value.double_value,
SAFE_CAST(p.value.string_value AS FLOAT64))
FROM UNNEST(event_params) AS p
WHERE p.key = 'value') AS value_param
FROM `shannonside-analytics.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261001' AND '20261031'
AND event_name = 'purchase';
Note that both fields, and ecommerce.purchase_revenue, are FLOAT in the export3. GA4 revenue is therefore approximate by type as well as by consent, which is one more reason the shop database stays the source of truth for money. The purchase event done right covers how the event itself should be sent.
Schema on write, or schema on read
There are two places to enforce the shape of data.
Schema on write means the table's types and rules are checked when data is stored. A PostgreSQL table with typed columns and constraints works this way. Bad rows are refused at the door. The cost: you must know the shape in advance, and a source that changes its shape stops the load.
Schema on read means data is stored as it arrives (files, JSON documents, a text column) and a shape is applied only when someone queries it. A folder of CSV files in cloud storage, read by a query engine, works this way. Nothing is refused at the door. The cost: every reader applies their own interpretation, and errors surface late, in someone's report.
| Schema on write | Schema on read | |
|---|---|---|
| When errors appear | at load time | at query time, often in a report |
| A source changes shape | the load stops | the load succeeds, readers break |
| Keeps the raw original | only if you store it separately | yes |
| Best for | clean, trusted tables | landing raw data exactly as received |
You do not choose one. You use both, in layers. The raw layer is schema on read: land exactly what arrived, as text or JSON where in doubt, so nothing is lost and anything can be replayed. The staging layer applies the schema on write: explicit types, explicit parsing, constraints, and a quarantine for rows that do not fit. A later chapter in this series covers the raw, staging and clean layers in full.
Example: the 3PL file in two layers
Callum lands the 3PL file in raw_tpl.returns_rows with every column as text, plus the file name, the row number and the load time. Nothing in that table can fail to load. The staging model then parses each column with the rules from this chapter: the amount with the continental parser, the scan time with the explicit zone rule and the ambiguity flag, the SKU as text with the 3PL's prefix stripped into a separate column. Rows that fail any rule go to staging.tpl_returns_rejected with the reason. On the Monday from the start of this chapter, 3 of 1,212 rows were rejected, each with a reason a person could act on, and the other 1,209 reached the report correctly.
Schema evolution: why adding is easy and renaming hurts
Sources change. A field is added, renamed, given a new type, or dropped. How much that hurts depends on the kind of change.
Adding a column is the safe change, as long as it allows NULL or has a default. Readers that select columns by name do not notice. In PostgreSQL, adding a column with a non volatile default does not even rewrite the table: the default is stored in the table's metadata and returned for existing rows36. BigQuery load jobs can add new columns, and relax required columns to nullable, when you allow it with the schema update options ALLOW_FIELD_ADDITION and ALLOW_FIELD_RELAXATION37.
Changing a type is heavier. In PostgreSQL it normally rewrites the whole table and its indexes, unless the old type converts to the new one without changing the stored bytes36. Widening (integer to bigint) is safe for the data and costly for a large table. Narrowing can fail or lose values.
Renaming is the dangerous one, because the systems involved see a rename as "one column removed, one column added":
- A reader that selects by name fails loudly. That is the good case.
- A file read by position (column 7 is the reason) carries on silently with the wrong data in the wrong column if the source inserts or reorders a column.
- In Avro, a reader schema field that the writer no longer has takes its default value, or raises an error if it has no default, and the writer's value under the new name is ignored38. A rename without an alias can therefore silently turn real values into defaults.
- An incremental dbt model with
on_schema_changeleft at its default,ignore, keeps loading into the old columns and does not add the new one39.
dbt adds a useful guard here: a model contract. With contract: enforced: true, dbt checks before building the model that its columns match the names and data types declared in YAML, and stops if they do not40. One detail matters: the comparison does not include size, precision or scale, so numeric(10,2) and numeric(12,4) count as the same type40. A contract catches a price that became text. It does not catch a price that lost its scale, so that needs its own test.
# models/staging/_tpl.yml (dbt Core)
models:
- name: stg_tpl_returns
config:
materialized: incremental
on_schema_change: fail # a changed source stops the build
contract:
enforced: true
columns:
- name: return_id
data_type: text
constraints:
- type: not_null
- name: sku
data_type: text
- name: refund_amount
data_type: numeric(12,2) # the contract checks numeric, not (12,2)
- name: scanned_at
data_type: timestamptz
- name: ambiguous_local_time
data_type: boolean
For renames you control, the safe method is expand and contract, also called parallel change: add the new column, write to both, move every reader across, and only then remove the old column41. Each step is small and reversible.
Example: the column that moved one place to the right
The 3PL adds a column, carrier, to its returns file, in fourth place, without telling anyone. Callum's old loader read the file by position. From that day, column four, which the loader thought was reason, contained carrier names, and the reason landed in the column the loader called condition. Nothing failed. The returns report showed that 41% of returns were for the reason "DPD".
The new loader reads by header name, and a test compares each day's header with the expected list. An added column is logged and loaded into the raw layer. A missing or renamed column stops the staging build with a message naming the column. The surprise becomes a two minute fix instead of a month of wrong reports.
Choosing the type for a column
Everything above condenses into a short sequence of questions, asked for every new column in the clean layer.
Two notes on the flow. "Will you ever do arithmetic with it?" is the question that keeps phone numbers, Eircodes, order numbers, EAN barcodes and SKUs out of number types, where they would lose leading zeros or digits. And the last branch, floating point, is right for genuine measurements such as a conversion rate in a model or the weight of a parcel in grams, where a difference in the fifteenth digit means nothing.
An orders table, done right
Here is how Callum defines the clean orders table in the warehouse's PostgreSQL. It is not a copy of spree_orders. It is the shape the business reads, with every lesson of this chapter in a type or a constraint.
-- PostgreSQL: clean layer, one row per completed order
CREATE TABLE clean.orders (
order_id bigint PRIMARY KEY, -- spree_orders.id, widened
order_number text NOT NULL UNIQUE, -- 'R482913': an identifier, never a number
customer_id bigint, -- NULL for guest checkouts, on purpose
email_key text, -- lower(btrim(normalize(email)))
completed_at timestamptz NOT NULL, -- a moment, stored as UTC
order_date_dublin date NOT NULL, -- the business day, derived once
currency text NOT NULL
CHECK (currency ~ '^[A-Z]{3}$'), -- ISO 4217, e.g. EUR
item_total numeric(12,2) NOT NULL CHECK (item_total >= 0),
shipment_total numeric(12,2) NOT NULL CHECK (shipment_total >= 0),
promo_total numeric(12,2) NOT NULL CHECK (promo_total <= 0),
included_tax_total numeric(12,2) NOT NULL CHECK (included_tax_total >= 0),
total numeric(12,2) NOT NULL,
ship_country text CHECK (ship_country ~ '^[A-Z]{2}$'), -- ISO 3166
state text NOT NULL
REFERENCES ref.order_states (state),
is_test_order boolean NOT NULL DEFAULT false,
source_updated_at timestamptz NOT NULL, -- when Solidus last changed it
loaded_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT total_adds_up
CHECK (total = item_total + shipment_total + promo_total)
);
What each choice buys:
bigintidentifiers: no ceiling to worry about, and safe to join with any other system's 64 bit keys.order_numberas text: Solidus order numbers such as R482913 carry a letter, and even all digit references keep their leading zeros as text.timestamptzforcompleted_at: the moment is unambiguous, whatever time zone any tool or person reads it in. The business date is a separate column, derived once by one rule.numeric(12,2)for every amount, with the currency beside it: exact, and wide enough for a group of shops, not just one. The check constraints refuse negative item totals and positive promotions, two signs that a sign got flipped somewhere.total_adds_up: the table refuses an order whose parts do not add up to its total. Whether Solidus's adjustments fit this exact sum in your setup (tax included in prices, as usual for Irish consumers, versus added on top) is something to confirm against your own data before switching the constraint on, which is precisely the point: it turns an assumption into a test.stateas a foreign key to a small table of valid states: a new state in a Solidus upgrade stops the load with a clear error instead of appearing as an unexplained row.is_test_order: the 40 or so test and staff orders a year stay in the table, marked, instead of being deleted. A later chapter on business rule cleaning covers how they are found.customer_idNULL for guests: here NULL has exactly one meaning, written in the comment.
Example: what the constraints caught on the first load
Callum loads five years of orders, 118,800 rows (invented figures), into the new table. The load refuses 214 rows, and each refusal has a reason:
| Constraint | Rows refused | Cause found |
|---|---|---|
total_adds_up | 163 | legacy orders with float prices, a cent out |
currency format | 37 | legacy orders with currency "€" instead of EUR |
state foreign key | 11 | orders stuck in the old platform's "pending_review" state |
promo_total <= 0 | 3 | promotions imported with the wrong sign |
Every one of those rows was already wrong in the old reports. The difference is that now they are visible, counted and fixable, with the original rows still in the raw layer. Callum fixes the 37 currency rows with a mapping, decides with Niamh that the 11 stuck orders are not sales, and keeps the 163 cent differences as a documented, explained adjustment rather than hiding them.
A checklist for every new column
| Question | If the answer is yes |
|---|---|
| Is it money? | numeric or integer minor units, currency beside it, rounding rule written down |
| Could it ever pass 2.1 billion? | bigint |
| Does it look numeric but is never added up? | text (phones, Eircodes, order numbers, barcodes) |
| Is it a moment? | timestamptz, UTC, offset in every file you exchange |
| Is it a calendar day? | date, with the time zone that defines the day named in the column |
| Could a value be missing? | decide what NULL means, write it down, store a status if there is more than one meaning |
| Is it a closed list? | check constraint, enum or lookup table, plus a test for unknown values |
| Does it come from a file? | land as text, parse explicitly in staging, quarantine what fails |
| Does it carry a unit? | put the unit in the name: _cent, _us, _mm |
| Could the source rename it? | read by name, test the header, change by expand and contract |
Conclusion
Pipelines rarely break on the clever parts. They break on a type that converts quietly: a price stored as a float, an Eircode or phone number stored as a number, a time stamp stored without its zone, an empty field read as zero, a continental number read the English way, a column that moved one place to the right. None of these raises an error, which is exactly why they last for months.
The defence is to choose every type by what the value means, to keep money exact (numeric or whole cent, with the currency and a written rounding rule), to store moments as timestamptz in UTC and derive the local day once, to give NULL a single written meaning, to parse every file explicitly and quarantine what does not fit, and to let constraints and contracts turn assumptions into tests. Land raw data as it arrived, apply the schema in staging, and change schemas by expanding first and contracting later. The next chapter builds on these columns and asks how to arrange them into tables that answer business questions quickly and correctly: grain, keys, facts and dimensions.
