Sub topic 8
Casting columns and capturing source file metadata while loading
This chapter assumes you can write a basic COPY INTO statement, set FORMAT_OPTIONS, and create a Delta table with typed columns. It covers the SELECT form of COPY INTO. You use it to cast columns to the right types, to rename or drop columns, and to record which file each row came from.
Why transform during the load
Text formats such as CSV carry no type information. Without schema inference, every column is read as a string. With inferSchema, Spark samples the data and guesses types, and the guesses can be wrong. A column of zip codes may become an integer and lose its leading zeros. A column that is mostly numeric may become a string because of one bad value.
You could load the raw strings into a staging table and clean them in a second step. The SELECT form of COPY INTO lets you do the cleanup in the same statement. Rows reach the target table already typed, and you can add columns that do not exist in the files, such as the source file name.
The SELECT source form
Instead of a path, the FROM clause takes a parenthesized SELECT. The SELECT reads from the path, and the rest of the statement (FILEFORMAT, FORMATOPTIONS, COPYOPTIONS) stays the same.
COPY INTO main.sales.orders
FROM (
SELECT
CAST(order_id AS BIGINT) AS order_id,
CAST(amount AS DECIMAL(10, 2)) AS amount,
CAST(order_ts AS TIMESTAMP) AS order_ts,
_metadata.file_path AS source_file
FROM '/Volumes/main/sales/landing/orders/'
)
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true');Read it in three parts:
- The
FROM '/Volumes/...'inside the parentheses names the source location. It is a path, not a table. - The select list decides which columns are written and in what order and type.
- The outer clauses tell COPY INTO how to parse the files.
Here the CSV files contain order_id, amount, and order_ts as text. The SELECT casts each one. source_file does not exist in the files. It comes from the _metadata column, described below.
Matching the select list to the target table
COPY INTO writes the select list into the target table, so the result must fit the table. Two rules cause most errors.
- The output column names and types must be compatible with the target columns. Use
ASto give every expression the name of the target column it should fill. - A column that is in the select list but not in the table causes an error, unless you load with
mergeSchemaenabled. The schema evolution chapter covers that option.
For this chapter's example, the target table could look like this:
CREATE TABLE IF NOT EXISTS main.sales.orders (
order_id BIGINT,
amount DECIMAL(10, 2),
order_ts TIMESTAMP,
source_file STRING
);Columns in the table that you leave out of the select list are filled with NULL. This is useful for columns that a later step fills in.
Choosing casts
CAST is the usual tool. Know how it behaves on bad data, because a load can silently produce NULLs.
| Expression | Behavior on a value that cannot be converted |
|---|---|
| `CAST(x AS BIGINT)` | Returns NULL when ANSI mode is off. Raises an error when ANSI mode is on. |
| `TRY_CAST(x AS BIGINT)` | Always returns NULL. |
| `to_timestamp(x, 'yyyy-MM-dd HH:mm:ss')` | Uses the format you give. Unparsable values follow the same ANSI rule as `CAST`. |
SQL warehouses run with ANSI mode on by default, so a bad value makes CAST fail the statement. Clusters may behave differently depending on configuration. Check the setting before you rely on either behavior.
Choose by what you want to happen to a bad row:
- Use
CASTwhen a bad value means the file is broken and you want the load to stop. - Use
TRY_CASTwhen you want the load to continue and handle NULLs afterward. Add a check on the target table for unexpected NULLs.
When a timestamp uses a non-default format, pass the format explicitly:
COPY INTO main.sales.orders
FROM (
SELECT
CAST(order_id AS BIGINT) AS order_id,
CAST(amount AS DECIMAL(10, 2)) AS amount,
to_timestamp(order_ts, 'dd/MM/yyyy HH:mm') AS order_ts,
_metadata.file_path AS source_file
FROM '/Volumes/main/sales/landing/orders/'
)
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true');The `_metadata` column
Every file-based read in Databricks exposes a hidden column named _metadata. It is a struct, and it does not show up in SELECT *. You must name it. Its fields describe the file a row was read from.
| Field | Type | Meaning |
|---|---|---|
| `file_path` | STRING | Full path of the file |
| `file_name` | STRING | File name without the directory |
| `file_size` | BIGINT | Size of the file in bytes |
| `file_modification_time` | TIMESTAMP | When the file was last modified |
Reference a field with dot notation, as in _metadata.file_path. Always give it an alias, because the default column name is awkward and may clash with the target.
Capturing the file name is useful for several reasons:
- Lineage. When a number looks wrong, you can find the file that produced it.
- Debugging. You can find all rows from one bad file and fix or remove them.
- Late-arriving data.
file_modification_timeshows when a file was written, which can differ from the business timestamp inside it. - Auditing. You can show which files contributed to a report.
A query to find the files that contributed rows to a table:
SELECT
source_file,
COUNT(*) AS row_count
FROM main.sales.orders
GROUP BY source_file
ORDER BY source_file;Adding constants and derived columns
The select list is ordinary SQL, so you can add more than casts.
COPY INTO main.sales.orders
FROM (
SELECT
CAST(order_id AS BIGINT) AS order_id,
UPPER(TRIM(country_code)) AS country_code,
CAST(amount AS DECIMAL(10, 2)) AS amount,
to_date(order_ts) AS order_date,
'landing' AS source_system,
current_timestamp() AS loaded_at,
_metadata.file_name AS source_file
FROM '/Volumes/main/sales/landing/orders/'
)
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true');This statement cleans a text column, derives a date, tags rows with a constant, and records the load time and file name. The target table must have columns with these names.
Keep the select list simple. The SELECT form supports expressions over each row. It does not support joins, aggregations, or window functions, because each file row is transformed independently. If you need those, load the raw rows first and transform them in a later step.
How the SELECT form interacts with other options
- PATTERN and FILES. They still go in the outer clause and still choose which files are read. Put them after FILEFORMAT, as in a normal load.
- Idempotency. COPY INTO still tracks loaded files. A file loaded once is skipped on later runs, whatever the select list says. If you change a cast and re-run, old files are not reloaded unless you set
force. - VALIDATE. You can combine it with the SELECT form. This is a good way to test casts before writing any data.
- Header handling. With
'header' = 'true', the column names in the select list are the names in the file's first row. With no header, columns are named_c0,_c1, and so on.
The third point is the most common source of surprise. If you fix a bad cast and re-run, nothing happens because the files are already recorded as loaded. Either use force and remove the earlier rows first, or delete the bad rows and reload the files with force.
Try the cast before you load
Combine the SELECT form with VALIDATE to see whether the casts work on real data. This reads the first 10 rows and writes nothing.
COPY INTO main.sales.orders
FROM (
SELECT
CAST(order_id AS BIGINT) AS order_id,
CAST(amount AS DECIMAL(10, 2)) AS amount,
CAST(order_ts AS TIMESTAMP) AS order_ts,
_metadata.file_path AS source_file
FROM '/Volumes/main/sales/landing/orders/'
)
FILEFORMAT = CSV
VALIDATE 10 ROWS
FORMAT_OPTIONS ('header' = 'true');If a value cannot be cast and ANSI mode is on, the statement fails here, before any data is written. Validation only samples the first rows, so a bad value deeper in the files can still appear in the real load.
How it fits together
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error that a column cannot be resolved | A name in the select list does not match a header in the file | Check spelling and case against the file header. Check that `header` is `true`. |
| Error that the table has no such column | The select list has a column the target lacks | Add the column to the table, or enable `mergeSchema`. |
| Casts fail with a parse error | Bad values and ANSI mode on | Fix the data, or use `TRY_CAST` and check for NULLs. |
| Many NULLs in a typed column | `TRY_CAST` or a timestamp format mismatch | Compare the format string with the actual values. |
| Re-run loads nothing after a fix | The files are already recorded as loaded | Remove the bad rows, then reload with `force`. |
| `_metadata` is not found | The field is spelled wrong or not named in the select | Use `_metadata.file_path`. It is not part of `SELECT *`. |
Exercise
A CSV load with CAST(zip AS INT) drops the leading zero from the zip code 02134. You change the select list to CAST(zip AS STRING) AS zip and re-run the same COPY INTO statement on the same folder. The statement reports zero rows loaded. Why, and what do you do?
Show answer
COPY INTO records each file it has loaded and skips it on later runs, no matter what the select list says. The earlier rows, with the wrong zip values, are still in the table. Change the target column to STRING if needed, delete the affected rows from the table, then re-run with COPY_OPTIONS ('force' = 'true') so the files are loaded again. Without deleting the old rows first, you would get duplicates.
Exercise
Write the select list fragment that records the file name and the time of the load, with aliases that match target columns named sourcefile and loadedat.
Show answer
metadata.filename AS sourcefile, currenttimestamp() AS loaded_at