Schema drift

Part of the free LogicWiz Data Engineering course, Module 7: Data quality and testing. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 7:50 on Wednesday. Tess's product report lists every item at $0, and its category filter is full of brand names. Overnight the catalogue team changed their export: price is now called unit_price_usd, and a new brand column sits in the middle. Nobody told you. Both loaders ran without an error.

You'll learn to

  • Spot an added column, a changed type and a rename
  • Compare a file's columns with the expected schema before loading
  • Decide per change: evolve, map or reject
  • Say where Parquet, Avro, Delta and Iceberg keep their schema

Learn

The file changed shape overnight

Sources change without asking you. A team adds a column, renames one to be clearer, turns an id from a number into text, or drops a field nobody seemed to use. This is called schema drift. Three kinds matter.

  • An added column. Usually harmless, often useful: brand.
  • A changed type. qty was a number and now sometimes says "2 units". Casts fail or, worse, values quietly become NULL.
  • A renamed or removed column. price became unit_price_usd. To a loader that is one column that vanished and another that appeared.

The danger is never the change itself. It is a change nobody notices. So the first step is cheap: compare the column names before loading anything.

Compare the old and new exports

import csv

def header(path):
    with open(path, newline='') as f:
        return next(csv.reader(f))

old = header('data/products.csv')
new = header('data/products_v2.csv')
print('old:', old)
print('new:', new)
print('added:', [c for c in new if c not in old])
print('removed:', [c for c in old if c not in new])

next(csv.reader(f)) reads only the first line, the header. Comparing names costs almost nothing and should run before anything is loaded.

The drift, column by column

Columnproducts.csvproductsv2.csvWhat it isResponse
brand(none)textaddedEvolve: add a nullable column
pricenumber(none)removed...Reject, unless...
unitpriceusd(none)number...added...the source confirms it is the rename of price: map it
all the otherssamesameunchangedLoad as usual

A name comparison sees "price removed, unit_price_usd added". Only a person (or a note from the source team) can say it is one rename.

A position lies, a name tells

Why did the two loaders fail in different ways?

The first reads columns by position: "the fourth column is the category, the fifth is the price". When brand was inserted in the middle, every later value moved one place to the right. The loader kept reading the same positions. Nothing failed, and the values it loaded look plausible.

The second reads by name. It asked for price, found no such column, and got nothing. That is wrong too, but it is honest: an empty price is easy to catch with a not-null check.

So keep the expected schema next to the loader (the contract of Lesson 7.2), read by name, and compare every file with it before loading.

A new column lands in the middle

The first product of the catalogue file, before and after a brand column is inserted. A loader reading by position then puts the brand into category and the category into price; a loader reading by name gets the right category and an empty price.

  1. Yesterday's file. The fourth column is the category and the fifth is the price. Both loaders load Electronics and 59.99.

  2. Today's file. brand is inserted in fourth place, so the category and the price each move one place to the right. The price column also has a new name.

  3. Read by position. The loader still takes the 4th and 5th columns. The brand lands in category and the category lands in price. No error: wrong values that look plausible.

  4. Read by name. The category is right, wherever its column moved to. There is no column called price, so the price comes back empty. A not-null check catches that at once.

Compare the two loader boxes in the last step: red values are wrong and silent, the amber one is missing and loud. The example below runs both loaders on the real file.

By position the data shifts; by name it goes missing

import csv

with open('data/products_v2.csv', newline='') as f:
    rows = list(csv.reader(f))[1:]
print('by position (the old layout: 3 = category, 4 = price):')
for r in rows[:2]:
    print('  ', {'product_id': r[0], 'category': r[3], 'price': r[4]})

with open('data/products_v2.csv', newline='') as f:
    named = list(csv.DictReader(f))
print('by name:')
for r in named[:2]:
    print('  ', {'product_id': r['product_id'], 'category': r['category'], 'price': r.get('price')})

By position, the brand lands in category and the category in price. By name, the category is right and the missing price is visibly None. Always read by name.

Evolve, map or reject

Once you can see the drift, decide on purpose, kind by kind.

  • Evolve, for an added column: add it to the target as a column that may be empty (ALTER TABLE ... ADD COLUMN brand TEXT). Old rows get NULL. Most tools can do this by themselves.
  • Map, for a rename: tell the loader that unit_price_usd is the new name of price. Never guess a rename automatically. A missing column plus a new one is as likely to be two unrelated changes.
  • Reject, for a missing required column or a type that no longer fits: fail the load and tell the source team.

Some tools rescue where you would reject: they load the row and put the unexpected values into a JSON column such as _rescued_data, to sort out later.

One decision for each kind of drift

A file arrives and its columns are compared with the expected schema. An added column leads to evolve, a confirmed rename leads to map, and a missing column or wrong type leads to reject.

Follow one branch at a time from the comparison to its answer. The next example is a loader that takes all three branches.

A loader with a rename map and a drift check

import csv

EXPECTED = ['product_id', 'sku', 'name', 'category', 'price', 'active', 'updated_at']
RENAMES = {'unit_price_usd': 'price'}        # agreed with the catalogue team

def load_products(path):
    with open(path, newline='') as f:
        reader = csv.DictReader(f)
        columns = [RENAMES.get(c, c) for c in reader.fieldnames]
        missing = [c for c in EXPECTED if c not in columns]
        if missing:
            raise ValueError(f'reject {path}: missing {missing}')
        added = [c for c in columns if c not in EXPECTED]
        rows = [{RENAMES.get(k, k): v for k, v in r.items()} for r in reader]
    return rows, added

rows, added = load_products('data/products_v2.csv')
print(len(rows), 'rows; columns to evolve:', added)
print(rows[0]['name'], rows[0]['price'], rows[0]['brand'])
try:
    load_products('broken.csv')
except ValueError as e:
    print(e)

The rename is mapped, so price is back. brand is reported as added, for the target to evolve. A file with no price at all (broken.csv, shown below) is rejected before a single row is loaded.

Evolve and map in Postgres

-- 1. Evolve: the new column, nullable, so the rows already there stay valid
ALTER TABLE dw.products ADD COLUMN brand TEXT;

-- 2. Map: load v2 by name, unit_price_usd into price
INSERT INTO dw.products (product_id, sku, name, category, price, active, brand)
SELECT product_id, sku, name, category, unit_price_usd, active, brand
FROM staging.products_v2
ON CONFLICT (product_id) DO UPDATE
SET price = EXCLUDED.price, category = EXCLUDED.category, brand = EXCLUDED.brand;

SELECT product_id, name, category, price, brand
FROM dw.products
ORDER BY product_id
LIMIT 5;

staging.products_v2 holds the new export. The insert names every column on both sides, so the order of columns in the file no longer matters.

A type change hides inside a cast

The third kind of drift is the quietest. The column is still there, under the same name. Only its values changed: qty used to say 2, and one line now says 2 units.

A strict cast would fail, which is at least loud. But many loaders are told to be forgiving: "make it a number, whatever it takes". Then the value that does not parse becomes empty, and the load is green.

So never cast blind. Count how many values the cast turned into NULL, and fail if that count is not zero.

A type change, and how it hides

import pandas as pd
from io import StringIO

csv_text = 'order_id,line_no,qty\n1009,1,1\n1009,2,2 units\n1010,1,3\n'
df = pd.read_csv(StringIO(csv_text))
print('qty is read as:', df['qty'].dtype)           # object means text

qty = pd.to_numeric(df['qty'], errors='coerce')     # "make it a number, whatever it takes"
print(qty.tolist(), '| values turned into NaN:', int(qty.isna().sum()))

One bad value turns the whole column into text (object). errors='coerce' then makes it numeric by replacing what does not parse with NaN, silently. The last line counts them: that count is your check.

Remember: read by name, compare the columns before loading, and count what a cast turned into NULL.

Where the schema lives decides how it can change

A CSV has only a header line. The formats a lake is built on keep a real schema, and each keeps it in a different place. That place decides which changes are cheap.

  • Parquet: every file carries its own schema in its footer. There is no schema for the table, so one folder can hold several, and each reader settles the differences its own way.
  • Avro: the writer's schema travels with the data, and the reader lines it up with its own by field name (Lesson 4.2).
  • Delta Lake: one schema for the table, in the transaction log. Files are matched to it by column name.
  • Iceberg: schemas in the table's metadata, where every column has a permanent field id. Data files are read by id, not by name.

Where each format keeps its schema

Four containers: a Parquet file with its own schema in the footer, an Avro file with the writer schema in its header, a Delta table with one schema in its log, and an Iceberg table whose metadata gives every column a field id.

Look for the amber box in each container: that is where the schema is kept. Parquet has one per file. Delta and Iceberg have one for the whole table.

Three Parquet files, three schemas, one reader

import duckdb

# Three days of the catalogue, written by three versions of the exporter
duckdb.sql("COPY (SELECT 105 AS product_id, 'Coffee Mug' AS name, 12 AS price) TO 'p_day1.parquet' (FORMAT PARQUET)")
duckdb.sql("COPY (SELECT 118 AS product_id, 'Hand Cream' AS name, 8.75 AS price) TO 'p_day2.parquet' (FORMAT PARQUET)")
duckdb.sql("COPY (SELECT 121 AS product_id, 'Acme' AS brand, 'Phone Stand' AS name, 16.0 AS unit_price_usd) TO 'p_day3.parquet' (FORMAT PARQUET)")
for f in ['p_day1.parquet', 'p_day2.parquet', 'p_day3.parquet']:
    print(f, [(col, typ) for col, typ, *_ in duckdb.sql(f"DESCRIBE SELECT * FROM '{f}'").fetchall()])

# 1. The first file decides the types: 8.75 is read into an INTEGER column
print(duckdb.sql("SELECT product_id, price FROM read_parquet(['p_day1.parquet', 'p_day2.parquet']) ORDER BY 1").fetchall())

# 2. A later file that lacks a column of the first file is an error
try:
    duckdb.sql("SELECT * FROM read_parquet(['p_day1.parquet', 'p_day3.parquet'])").fetchall()
except duckdb.Error as e:
    print(type(e).__name__, '|', str(e).splitlines()[0][:110])

# 3. union_by_name: every column of every file, a common type, NULL where a file has none
print(duckdb.sql("SELECT * FROM read_parquet(['p_day1.parquet', 'p_day2.parquet', 'p_day3.parquet'], union_by_name = true) ORDER BY product_id").fetchall())

Each file is valid on its own; the trouble is the set. Read the default way, the first file's INTEGER wins and the Hand Cream costs $9, so the answer depends on which file happens to come first. union_by_name lines the columns up by name and widens price to a decimal, but it still cannot know that unit_price_usd is price. Spark reads the schema the same way unless spark.sql.parquet.mergeSchema (default false) is on.

Schema changes, format by format

ChangeParquet filesAvroDelta LakeIceberg
Add a columnNew files have it; read with unionbyname or mergeSchemaAdd it with a defaultmergeSchema or ADD COLUMNSMetadata only
Drop a columnOld files still hold itNew readers ignore it; old readers need a defaultNeeds column mappingMetadata only
RenameLooks like a drop plus an addaliases in the reader schemaNeeds column mapping (name)Metadata only: same field id
Widen a typeEvery reader must accept both typesint to long, float or double; float to doubleType widening table featureint to long, float to double, decimal precision up
ReorderHarmless when read by nameHarmless (by name)ALTER COLUMN ... AFTERMetadata only

The pattern: the more a format identifies columns by something other than their position and current name, the more changes become cheap metadata edits, not rewrites. The picture below shows the Avro column of this table at work.

Avro: an old file read with a new schema

Writer fields from an old Avro file on the left are matched to reader fields on the right: product_id widens from int to long, name reaches title through an alias, price widens to double, legacy_code is ignored, and brand takes its default.

Follow each arrow from the old file on the left to the reader on the right: every arrow is one Avro rule from Lesson 4.2. Remove the alias and title has no source and no default, so the read fails. A product_id written as long cannot be read as int either: Avro widens, it never narrows.

Delta and Iceberg: change the label, not the files

Delta checks every write against the table's schema. A DataFrame with an extra column, or a different type, fails with A schema mismatch detected when writing to the Delta table. You allow new columns on purpose, with .option("mergeSchema", "true").

A rename is harder. Delta matches files to the schema by column name, so renaming price would orphan the values in every old file. Delta refuses until you turn on column mapping. Each column then gets a hidden physical name inside the files, and a rename only changes the log.

Iceberg gives every column a field id from the start. Add, drop, rename and reorder are all edits to metadata, and no data file is rewritten.

Rename and widen a Delta column without rewriting it

Runs on Databricks:

-- Columns get physical names in the files; renames and drops become log entries
ALTER TABLE swiftkart.silver.products
  SET TBLPROPERTIES ('delta.columnMapping.mode' = 'name');
ALTER TABLE swiftkart.silver.products RENAME COLUMN price TO unit_price_usd;

-- Let product_id grow from INT to BIGINT without rewriting the data files
ALTER TABLE swiftkart.silver.products SET TBLPROPERTIES ('delta.enableTypeWidening' = 'true');
ALTER TABLE swiftkart.silver.products ALTER COLUMN product_id TYPE BIGINT;

DESCRIBE HISTORY swiftkart.silver.products LIMIT 4;

Each statement is one commit in _delta_log, and no data file is rewritten. Both are table features: they raise the reader and writer protocol versions, so older clients that do not support them can no longer read the table. Check every reader before turning them on.

The trap: defaults and positions hide drift. row.get('price', 0) turns a missing column into free products. Reading by position shifts values into the wrong columns. And INSERT INTO ... SELECT * matches columns by position, not by name. Read by name, give required columns no default, and compare the schema before loading.

Auto Loader with schema evolution

Runs on Databricks:

products = (spark.readStream
    .format("cloudFiles")
    .option("cloudFiles.format", "csv")
    .option("header", "true")
    .option("cloudFiles.schemaLocation", "/Volumes/swiftkart/raw/_schemas/products")
    .option("cloudFiles.schemaEvolutionMode", "addNewColumns")
    .load("/Volumes/swiftkart/landing/products/"))

(products.writeStream
    .option("checkpointLocation", "/Volumes/swiftkart/raw/_checkpoints/products")
    .option("mergeSchema", "true")
    .trigger(availableNow=True)
    .toTable("swiftkart.raw.products"))

Auto Loader stores the schema it inferred in schemaLocation. When brand appears, the stream stops once with an error that names the new column. On restart it carries on with the evolved schema, and mergeSchema lets the Delta table add the column. The rename still needs a person. Other tools offer the same choice: dbt incremental models have on_schema_change, and Fivetran and Airbyte detect source schema changes and let you propagate or block them.

Numbers to remember

WhatSetting or ruleGood to know
Auto Loader cloudFiles.schemaEvolutionModeaddNewColumns (the default), rescue, failOnNewColumns, nonerescue sends new fields to rescueddata
dbt onschemachangeignore, fail, appendnewcolumns, syncallcolumnsFor incremental models
Spark spark.sql.parquet.mergeSchemadefault falseSpark 4's vectorized reader can widen types such as int to long or double, where Spark 3 failed with a column-cannot-be-converted error
Delta write optionsmergeSchema adds new columnsoverwriteSchema replaces the schema during an overwrite
Delta column mapping'delta.columnMapping.mode' = 'name'Without it: Column rename is not supported for your Delta table
Delta type wideningdelta.enableTypeWideningFully supported from Delta Lake 4.0: int becomes long, or a decimal gains precision, with no file rewritten
Iceberg type promotionint to long, float to double, decimal(P, S) to a larger PMetadata only

What changed at SwiftKart

The catalogue loader now reads by name and compares each file's header with the expected schema before it loads a row. brand was added to the warehouse as a new column. The rename was confirmed with the catalogue team and written into the loader as an explicit mapping, so price is filled again. A file with no price column at all is rejected with a message that names it. No product costs $0.

Checks, contracts, reconciliation and drift all guard the data coming in. One thing is still untested: your own transformation code. Lesson 7.5 tests it on small made-up tables, and keeps watching the pipeline after it ships.

In one line

Schemas drift: read by name, compare each file with the expected schema before loading, then evolve added columns, map confirmed renames and reject what is missing or no longer fits.

Interview corner

What is schema drift and how do you handle it?

Schema drift is a source changing its structure: added, removed or renamed columns, or changed types. I read by name and compare each batch with the expected schema before loading; added columns are evolved as nullable (or reviewed), missing required columns fail the load with an alert, renames are mapped explicitly once confirmed, and type changes are caught by counting values that do not parse.

Should a pipeline evolve the schema automatically?

For added columns, usually yes: adding a nullable column breaks nothing downstream. For removals, renames and type changes, no: they change the meaning of data people already use, so the pipeline should stop or quarantine and a person should decide. Tools reflect this, for example Auto Loader's addNewColumns or rescue modes and dbt's on_schema_change.

Your lake has three years of Parquet files; `price` was INT32 until March and DOUBLE since. Some queries fail and some return rounded prices. Why, and how do you fix it?

Parquet has no table schema: each file has its own, and each engine reconciles them its own way. One that takes the first file's type rounds the doubles into integers; Spark 3's vectorized reader fails on files whose physical type does not match the table type. Short term I read with an explicit schema of DOUBLE and an engine that widens (Spark 4's reader promotes int to double; DuckDB with union_by_name). The lasting fix is a table format: on Delta or Iceberg the table has one schema, widening is a metadata change, and the writers are checked against it on every commit.

Why is reading CSV columns by position dangerous?

Because a new column inserted in the middle shifts every value after it into the wrong field, and the load still succeeds with plausible-looking wrong data. Reading by header name makes the loader immune to reordering and turns a missing column into a visible error.