Sub topic 2
Choosing Files with `COPY INTO` in Databricks
Assume you know basic SQL, Delta tables, cloud storage, and Databricks volumes. This chapter shows how to control which files COPY INTO reads and how to make the load repeatable.
Choose files with `PATTERN` or `FILES`
PATTERN selects files whose paths match a regular expression. Use it for repeatable rules, such as loading one day's files. FILES names specific files directly. Use it for a small, controlled batch.
Choose one method for each load:
COPY INTO main.sales.orders
FROM '/Volumes/main/sales/landing/orders/'
FILEFORMAT = CSV
PATTERN = '2026-12-.*[.]csv'
FORMAT_OPTIONS ('header' = 'true', 'delimiter' = ',');To load only named files:
COPY INTO main.sales.orders
FROM '/Volumes/main/sales/landing/orders/'
FILEFORMAT = CSV
FILES = ('orders_2026-12-01.csv', 'orders_2026-12-02.csv')
FORMAT_OPTIONS ('header' = 'true');The source location must be readable by the SQL warehouse or cluster. In Unity Catalog, this usually means access through a volume or external location with the required permissions.
Why rerunning the load is safe
COPY INTO tracks files that it has already loaded. A later run skips those files and processes only new matching files. This makes a normal rerun idempotent: repeating the command does not normally duplicate rows.
This tracking applies to the files, not to individual rows. If a source file changes after loading, COPY INTO does not automatically reload it.
Target tables and schema inference
The target table defines the destination schema. For predictable production loads, create the table with explicit column types. You can also create an empty table and use inferSchema with mergeSchema when the source controls the schema.
New columns may be added through schema evolution, but type inference can produce unexpected types. Review the resulting schema before relying on it.
Cast data and capture file metadata
A SELECT source lets you cast strings and add the originating file path:
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');Exercise
Which option should you use to load every CSV file for a date, and which should you use for two named files?
Show answer
Use PATTERN for the date-based rule and FILES for the two explicit filenames.