Sub topic 7
Target tables and schema inference
COPY INTO writes into a Delta table that already exists. This chapter covers what the target table has to look like, how the schema gets set (declared or inferred), and which mismatches cause wrong data or errors. It assumes you can run the basic statement from the earlier chapters, you know the common CSV, JSON and Parquet format options, and you can create Delta tables in Unity Catalog.
The target table must exist first
COPY INTO never creates a table for you. If the table name doesn't resolve, the statement fails before it reads any files. You have two ways to prepare the target:
- Create the table with an explicit schema.
- Create an empty placeholder table with no schema, and let the first load infer the columns.
Which one to use depends on how much you trust the source files and how much control you want over types.
Option 1: an explicit schema
A declared schema is the safer choice for production tables. The table definition documents what you expect, and COPY INTO converts incoming values to those types.
CREATE TABLE IF NOT EXISTS main.sales.orders (
order_id BIGINT,
customer_id BIGINT,
amount DECIMAL(10, 2),
order_ts TIMESTAMP
);
COPY INTO main.sales.orders
FROM '/Volumes/main/sales/landing/orders/'
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true');CSV fields arrive as text, so COPY INTO parses each value into the column's type. A value that can't be parsed, such as "N/A" in a BIGINT column, is a data problem you need to find. Whether it fails the load or becomes a null depends on the parser mode of the format. The chapter on VALIDATE shows how to find these rows before they reach the table.
How source columns map to target columns
The mapping rule depends on the format:
- Parquet and JSON carry or imply field names, so values are matched to target columns by name.
- CSV is the risky one. The CSV reader option
enforceSchemadefaults totrue, which applies the target schema to the files and ignores the header names. Columns are then matched by position, even ifheaderistrue.
Suppose the table is (order_id, customer_id, amount) and a new file arrives with the header customer_id,order_id,amount. With the defaults, the customer IDs load into order_id and the order IDs into customer_id. No error is raised if both columns are BIGINT.
If header order can change, make the reader check the header instead of ignoring it:
COPY INTO main.sales.orders
FROM '/Volumes/main/sales/landing/orders/'
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true', 'enforceSchema' = 'false');With enforceSchema set to false and header set to true, the reader compares the file header with the schema. A mismatch is then an error, not silent data corruption.
Missing and extra columns
If a file has fewer columns than the table, the missing columns are filled with NULL, provided the table doesn't forbid nulls. A NOT NULL constraint on a column the file doesn't supply makes the load fail. Files that have columns the table lacks are the schema evolution case, which is covered in its own chapter.
Option 2: an empty table with inferred schema
When you are exploring a new source, or the files have many columns, you can skip the column list entirely. Create the table with only a name, then load with mergeSchema turned on:
CREATE TABLE IF NOT EXISTS main.sales.orders_raw;
COPY INTO main.sales.orders_raw
FROM '/Volumes/main/sales/landing/orders/'
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true', 'inferSchema' = 'true')
COPY_OPTIONS ('mergeSchema' = 'true');Two things must both be in place for this to work:
- The table must be a Delta table with no columns yet. A placeholder table with no schema is what tells COPY INTO to build the schema from the data.
COPY_OPTIONS ('mergeSchema' = 'true')must be set. Without it, COPY INTO has no permission to change the table's schema, and the load fails because there are no columns to write into.
After the load, inspect the result:
DESCRIBE TABLE main.sales.orders_raw;Don't skip this check. Inferred schemas are a best guess, and the guess is often wrong in small ways.
What inference does for each format
Inference depends on the file format, so the same statement behaves differently for CSV, JSON and Parquet.
| Format | Where column names come from | Where types come from |
|---|---|---|
| Parquet | The file's own metadata | The file's own metadata, which is exact |
| JSON | The keys in the records | Inferred from sampled values |
| CSV with `header` = `true` | The first row of each file | All `STRING` unless `inferSchema` = `true` |
| CSV with `header` = `false` | Generated names such as `_c0`, `_c1` | All `STRING` unless `inferSchema` = `true` |
Parquet is the easiest case, because the types are stored in the file and no guessing takes place. CSV has no type information at all, so everything is a string by default. Setting inferSchema to true makes the reader sample the data and pick types such as INT, DOUBLE or TIMESTAMP.
Where inference goes wrong
Inference looks at the data it samples, not at what the column means. These are the common failures:
- A column of ZIP codes like
02134is inferred as an integer, and the leading zero is lost. - A column that is whole numbers in the sampled rows is inferred as
INT. A later file with a decimal in that column then fails or is mangled. - An identifier that fits in
INTin the sample overflows in later files. Order IDs are a typical case. - A column that is empty in the sampled rows is inferred as
STRING. - A date format that the reader doesn't recognise stays a string.
Inferring from a small sample and then trusting the result for years of files is the usual cause of these. A reasonable workflow is to infer once, read the output of DESCRIBE TABLE, and then freeze the schema:
- Load a representative sample into a scratch table with inference on.
- Run
DESCRIBE TABLEand note which types are wrong. - Create the real table with an explicit schema that fixes them.
- Load the production files into the real table.
Checking what the table looks like
Use these statements to see the current schema and how it changed over time:
DESCRIBE TABLE main.sales.orders_raw;
DESCRIBE HISTORY main.sales.orders_raw;DESCRIBE HISTORY lists each write to the Delta table. A load that added columns through mergeSchema appears as a table version, so you can confirm when the schema changed and which operation did it.
Choosing between the two options
| Question | Explicit schema | Inferred schema |
|---|---|---|
| Types are guaranteed to be what you want | Yes | No, review needed |
| Setup effort | Higher, you write the columns | Minimal |
| Survives a changed CSV column order | Only with `enforceSchema` = `false` | Depends on the files |
| Good for | Production tables, shared tables | Exploration, wide files, one-off loads |
| Risk | Load failures on bad values | Wrong types that go unnoticed |
A good default is to infer while you explore and declare when you ship.
Common errors in this area
- Table or view not found. The target wasn't created, or the three-part name has a typo. Create the table first.
- A load into a schemaless table fails. The
mergeSchemacopy option is missing, so COPY INTO can't build the schema. - Everything is a string.
inferSchemawasn't set for CSV, so the types weren't guessed. - Columns named
_c0,_c1. The CSV has a header row butheaderwasn't set totrue, and the header was loaded as data in the first row. - Values in the wrong columns. A CSV file's column order changed and
enforceSchemawas left at its default. - Parse failures on a column. A value in the files can't convert to the declared type. Find those rows with VALIDATE before you load.
Exercise
You create main.sales.events with columns (event_id BIGINT, user_id BIGINT, event_name STRING). A new CSV file arrives with the header user_id,event_id,event_name. You run COPY INTO with 'header' = 'true' and no other format options. What happens, and what would you change?
Show answer
With enforceSchema at its default of true, the reader applies the table schema by position and ignores the header names. The user IDs load into event_id and the event IDs into user_id. Both are BIGINT, so no error is raised and the data is silently swapped. Add 'enforceSchema' = 'false' to FORMAT_OPTIONS, with header still true. The reader then checks the header against the schema and the load fails on the mismatch, instead of loading swapped values.
Exercise
You run COPY INTO against a table created with CREATE TABLE IF NOT EXISTS main.raw.clicks; and the load fails because no schema can be written. Which copy option is missing, and which format option would make CSV columns come in as numbers and timestamps instead of strings?
Show answer
The missing option is COPY_OPTIONS ('mergeSchema' = 'true'), which lets COPY INTO build the schema of a table that has no columns. For typed CSV columns, add 'inferSchema' = 'true' to FORMAT_OPTIONS. After the load, run DESCRIBE TABLE main.raw.clicks to check the inferred types.