Home / Databricks on Azure

Databricks on AzureCheat sheetIntermediate

Columns swapped or shifted after Delta inserts on Azure Databricks: by-position vs by-name writes cheat sheet

insertInto and INSERT INTO ... SELECT match columns by position, so a reordered DataFrame or a new column can load data into the wrong columns without an error. Which writes match by name, and how to repair a table.

Deepak Bhardwaj7 min read

Applies toAzure Databricks, Delta tables in Unity Catalog or the Hive metastore, Databricks Runtime 13.3 LTS and above (INSERT ... BY NAME), PySpark DataFrameWriter and DataFrameWriterV2, Databricks SQL

Symptom

A load job succeeded, but the target table has values in the wrong columns:

  • country holds dates, or first_name and last_name are reversed.
  • A numeric column is unexpectedly NULL, or values look multiplied (amount and quantity swapped).
  • After someone added a column, a job that ran for months starts failing with [INSERT_COLUMN_ARITY_MISMATCH.NOT_ENOUGH_DATA_COLUMNS]. Or worse, it keeps running and every column after the new one is shifted by one.

The cause is nearly always a write that matches source and target columns by position. Spark takes the first source column into the first table column, the second into the second, and so on. Column names are ignored. If two swapped columns have compatible types, nothing fails.

Which writes match by position and which by name

Write Matching Notes
df.write.insertInto("t") Position The PySpark docs state that insertInto ignores column names
INSERT INTO t SELECT ... / INSERT OVERWRITE t SELECT ... Position SELECT * from a source with a different column order is the classic trap
INSERT INTO t (a, b, c) SELECT ... Column list The SELECT list must be in the order of the column list. Omitted table columns get their default value or NULL
INSERT INTO t BY NAME SELECT ... Name DBR 13.3 LTS and above. Also matches struct fields by name. An extra source column fails with INSERT_COLUMN_ARITY_MISMATCH.TOO_MANY_DATA_COLUMNS
df.write.mode("append").saveAsTable("t") Name For an existing Delta table. Extra source columns fail with a schema mismatch unless schema evolution is enabled
df.writeTo("t").append() Name DataFrameWriterV2
MERGE ... UPDATE SET * / INSERT * Name Explicit SET t.a = s.a lists are also safe
COPY INTO from Parquet/JSON/Avro Name For CSV, matching depends on the header and options; test with your files

Tip

If you're not sure, use saveAsTable with mode("append"), writeTo(...).append() or INSERT ... BY NAME. Use positional writes only when you build the column list from the target table yourself.

How a correct job starts writing to the wrong columns

The code doesn't need to change for this to happen. Common triggers:

  • Someone added a column in the middle of the table. Delta supports ALTER TABLE t ADD COLUMNS (region STRING AFTER country) and FIRST. Every positional writer that already supplies the right number of columns now loads its values shifted, starting at that column.
  • An upstream source changed its column order. For example, a view was rewritten, a JDBC source table was rebuilt, or a CSV export changed its header order. SELECT * passes the new order straight through.
  • A refactor reordered select() or withColumn() calls. withColumn adds new columns at the end, so moving a derived column changes the position of every column after it.
  • A table was recreated from DDL kept in a different repo, with the same columns in a different order.

Mismatched types don't always save you. Under ANSI store assignment (the default), a swap between incompatible types such as string into INT fails with a cast error, and the error name varies by runtime. Swaps between STRING and STRING, INT and BIGINT, DATE and TIMESTAMP, or DECIMAL and DOUBLE succeed silently.

Check: was this table written by position?

Find which writes added the suspect data and what produced them:

DESCRIBE HISTORY main.sales.customers LIMIT 30;

Look at operation (WRITE, CREATE OR REPLACE TABLE AS SELECT, MERGE), operationParameters, job and notebook. Compare the timestamp of the first bad row with any ADD COLUMNS or CHANGE COLUMN entries.

Compare the column order of the table with the source:

SELECT column_name, ordinal_position, data_type
FROM main.information_schema.columns
WHERE table_schema = 'sales' AND table_name = 'customers'
ORDER BY ordinal_position;

In the job code, search for the risky patterns:

grep -rnE "insertInto\(|INSERT (INTO|OVERWRITE) [^ ]+ (SELECT|TABLE)" --include=*.py --include=*.sql .

Isolate the rows a single bad append added by comparing it with the version before it:

-- Version 412 is the bad append from DESCRIBE HISTORY
SELECT * FROM main.sales.customers VERSION AS OF 412
EXCEPT ALL
SELECT * FROM main.sales.customers VERSION AS OF 411;

Fix the table

Caution

Stop or pause the job that writes by position before you repair anything. Otherwise the next run adds more shifted rows on top of your fix.

If the bad write is the latest version, restore to the version before it:

RESTORE TABLE main.sales.customers TO VERSION AS OF 411;

RESTORE also undoes any good writes that came after the target version. If other jobs have written since, don't restore. Delete the bad rows and reload them with corrected column order instead:

-- Remove exactly the rows added by version 412
MERGE INTO main.sales.customers AS t
USING (
  SELECT * FROM main.sales.customers VERSION AS OF 412
  EXCEPT ALL
  SELECT * FROM main.sales.customers VERSION AS OF 411
) AS bad
ON t.customer_id = bad.customer_id AND t.first_name <=> bad.first_name AND t.last_name <=> bad.last_name
WHEN MATCHED THEN DELETE;

Adjust the ON clause to a set of columns that identifies a row uniquely. <=> is null-safe equality. Then re-run the load for that period with a by-name write. If you can't reload, swap the columns in place using an UPDATE that matches the same rows:

UPDATE main.sales.customers
SET first_name = last_name, last_name = first_name
WHERE load_batch_id = '2026-11-28';

In a single UPDATE, every SET expression reads the old row values, so both columns swap correctly.

Warning

Check delta.deletedFileRetentionDuration and the VACUUM schedule before you depend on time travel to version 411. If VACUUM has already removed those files, the VERSION AS OF queries fail. In that case, identify bad rows with a batch column or load timestamp instead.

Make positional writes safe

Switch to by-name writes. Two changes cover most jobs.

SQL:

INSERT INTO main.sales.customers BY NAME
SELECT customer_id, last_name, first_name, country, load_batch_id
FROM main.staging.customers_raw;

PySpark, when you must keep insertInto (for example, for its dynamic partition overwrite behaviour), select the columns in the target's order first:

def insert_into_by_name(df, table: str, overwrite: bool = False):
    target_cols = spark.table(table).columns
    extra = set(df.columns) - set(target_cols)
    missing = set(target_cols) - set(df.columns)
    if extra or missing:
        raise ValueError(f"{table}: extra={sorted(extra)} missing={sorted(missing)}")
    df.select(*target_cols).write.insertInto(table, overwrite=overwrite)

insert_into_by_name(clean_df, "main.sales.customers")

Otherwise use a by-name append:

clean_df.write.mode("append").saveAsTable("main.sales.customers")
# or
clean_df.writeTo("main.sales.customers").append()

Prevent it next time

  • Ban insertInto and INSERT INTO ... SELECT * in code review, or wrap them in a helper like the one above. The grep in the checks section works as a CI lint.
  • Add new columns at the end of tables. Use AFTER or FIRST only when you have confirmed that no writer uses positional inserts.
  • Treat a column order change as a schema change. Announce it to downstream owners the same way as a rename.
  • Add a cheap post-load check on columns that are easy to recognise, such as country being a valid ISO code or order_date falling in the load window. Fail the task if the check fails.
  • Keep a batch ID or load timestamp column in every table so you can find and repair one bad load without time travel.