Sub topic 13
Running COPY INTO on a Schedule and Reading Its Results
This chapter assumes you can write a basic COPY INTO statement, know that it skips files it has already loaded, and can run SQL in a Databricks workspace. You should also know what a Delta table is. Here you will move from running a load by hand to running it on a schedule, and you will learn how to read what each run reports.
Why scheduling works well with COPY INTO
A load that runs by hand is easy to forget. Most batch pipelines run on a timer instead, for example every hour or once each night. COPY INTO suits this well because it is idempotent. Idempotent means that running the same statement twice gives the same final table as running it once. The command records which files it has loaded, so each scheduled run picks up only the files that arrived since the last run.
This gives you a simple design. You write one statement and never edit it. A scheduler runs it on a timer. New files appear in the landing folder, and each run loads only those.
Scheduling with Lakeflow Jobs
In Databricks, the usual scheduler is a job. A job is a named set of tasks that Databricks runs on a trigger. Lakeflow Jobs is the current name of the feature that was earlier called Databricks Workflows. In the workspace you will find it under Jobs & Pipelines in the sidebar. Your workspace may use either name, but the steps are the same.
To run a COPY INTO statement on a schedule:
- Save the statement in a SQL file or a SQL notebook.
- Create a job and add a task. Choose the task type that matches where you saved the statement. A SQL task runs on a SQL warehouse. A notebook task runs on a cluster or serverless compute.
- Point the task at the file or notebook, and select the compute it should use.
- Add a schedule trigger. You can pick a simple interval or write a cron expression. A cron expression is a short text pattern that describes times, such as
0 0 * * * ?for the start of every hour in the Quartz format Databricks uses. - Save the job and run it once by hand to confirm it works.
Here is a statement that is suitable for a scheduled task. It has no run-specific values, so it behaves the same on every run.
COPY INTO main.sales.orders
FROM '/Volumes/main/sales/landing/orders/'
FILEFORMAT = CSV
PATTERN = '*.csv'
FORMAT_OPTIONS ('header' = 'true', 'delimiter' = ',');Notice that the PATTERN is a broad glob and not a date. A date-based pattern such as 2026-12-*.csv would stop matching new files when the month changes, and the job would quietly load nothing. Because COPY INTO skips files it has seen, a broad pattern costs little in correctness, and it removes a source of silent failure.
Choosing compute
The compute you pick affects both cost and speed.
| Option | Good fit | Trade-off |
|---|---|---|
| SQL warehouse (SQL task) | Plain SQL loads, small to medium batches | Startup time if the warehouse is stopped |
| Serverless compute (notebook task) | Short, frequent runs | Billing model differs from classic clusters |
| Job cluster (notebook task) | Heavy loads that need tuning | Cluster startup adds minutes to each run |
For a load that takes seconds and runs every few minutes, startup time can be longer than the load itself. In that case, prefer compute that starts quickly, or lengthen the interval between runs.
How often to run
Running more often does not make the load faster. Each run must list the source folder and compare it with the table's record of loaded files. If the folder holds many thousands of files, that listing becomes the main cost. When a folder grows that large and you need low delay, consider Auto Loader instead. The earlier chapter on choosing between the two covers this decision.
Reading the result of a run
Every COPY INTO statement returns a result table with one row. You can read it in the SQL editor, in the output of a notebook cell, or in the output of a job task run.
The columns are:
| Column | Meaning |
|---|---|
| `num_affected_rows` | Number of rows the statement changed in the table |
| `num_inserted_rows` | Number of rows added by this run |
| `num_skipped_corrupt_files` | Number of files skipped because they were corrupt |
A healthy run on a day with new files shows a positive num_inserted_rows. A healthy run on a day with no new files shows 0. Both are normal. Zero rows means "nothing new", not "something broke".
If you used VALIDATE, the result looks different. It returns the preview rows themselves, and nothing is written to the table. Do not leave VALIDATE in a scheduled statement, because the job would succeed every time while loading nothing.
Checking the table history
Delta keeps a log of every change to a table. You can read it with DESCRIBE HISTORY. Each COPY INTO that writes data appears as an operation, along with metrics.
DESCRIBE HISTORY main.sales.orders;Look at these columns in the output:
version: the table version created by the write.timestamp: when the commit happened.operation: the type of change. Loads fromCOPY INTOappear as a write or merge-style operation, depending on the runtime version.operationMetrics: counts such as rows and files written.
A run that found no new files does not create a new version. If you expect a load and see no new version at the expected time, the run either found nothing or failed before committing.
Confirming which files arrived
If your statement captures _metadata.file_path in a SELECT source, you can count rows per file. This tells you which files each load brought in.
SELECT source_file, COUNT(*) AS row_count
FROM main.sales.orders
GROUP BY source_file
ORDER BY source_file;This works only if the target table has a source_file column filled by the load, as in the earlier chapter on casting columns and capturing file metadata. It is a cheap way to confirm that a particular file was loaded, and it helps when someone asks why a row is missing.
Making a schedule dependable
A scheduled job needs more than a timer. These settings turn a working query into a pipeline you can trust.
- Retries. Set a retry count on the task, with a delay between tries. A transient storage error or a stopped warehouse will often succeed on the second attempt. Because
COPY INTOis idempotent, a retry cannot double-load files that already committed. - Timeout. Set a maximum run time. A load that hangs should fail so that someone sees it.
- Concurrency. Limit the job to one active run at a time. Two overlapping runs of the same statement against the same table can conflict. If a run takes longer than the interval, the next one should wait or be skipped, not start alongside it.
- Notifications. Add email or webhook alerts on failure. You can also alert on a long duration.
- Parameters. If the source path differs between environments, pass it as a job parameter. Keep the statement itself free of values that change from run to run.
A freshness check
Because success does not prove data arrived, add a second task that checks freshness. This task runs after the load and fails if the newest data is too old.
SELECT
CASE
WHEN MAX(order_ts) < current_timestamp() - INTERVAL 6 HOURS
THEN raise_error('orders table has no data newer than 6 hours')
ELSE 'ok'
END AS freshness
FROM main.sales.orders;When the check fails, the job reports a failure and your notification fires. The thresholds depend on how often data should arrive. For a source that delivers files hourly, six hours leaves room for a few missed runs before anyone is paged.
Common problems with scheduled loads
| Symptom | Likely cause | What to do |
|---|---|---|
| Run succeeds, zero rows inserted, files exist | Files were already loaded earlier, or `PATTERN` does not match | Check the pattern, and check whether the same file names were reused |
| New data in an old file name is ignored | `COPY INTO` tracks files by path, so it treats a rewritten file as already loaded | Write new data to new file names |
| Duplicates appear after a fix | `force` was set to true and files were reloaded | Remove `force` from the scheduled statement |
| Run fails on one bad file | A file does not match the format options or schema | Run the statement with `VALIDATE` by hand, fix the options, then restore the schedule |
| Two runs overlap and one fails | The job allows concurrent runs | Set maximum concurrent runs to 1 |
Keep force out of scheduled statements. It is meant for a one-time repair run by hand, because it defeats the file tracking that makes the schedule safe.
Putting it together
A dependable scheduled load has these parts:
- A fixed
COPY INTOstatement with a broadPATTERNand noforce. - A job task on suitable compute, with retries, a timeout, and one concurrent run.
- A reading of the result row,
DESCRIBE HISTORY, and per-file counts when you need to confirm what loaded. - A freshness check and a failure alert, so silence is never mistaken for success.
Exercise
A nightly job runs a COPY INTO statement with PATTERN = '2026-12-*.csv'. On 1 January the job still shows Succeeded every night, but the table gets no new rows. Why does this happen, and what are two changes that would prevent it from going unnoticed?
Show answer
The pattern only matches file names that start with 2026-12-, so files named 2027-01-... no longer match. COPY INTO finds no files to load and returns zero inserted rows, which counts as a successful run. To prevent it, use a broad pattern such as '*.csv' (or a parameter that is updated), and add a freshness check task that fails when the newest order_ts is older than an agreed limit, with a failure alert attached to the job.
Exercise
Why is it a mistake to leave COPY_OPTIONS ('force' = 'true') in a statement that runs every hour?
Show answer
force makes COPY INTO load every matching file again, ignoring its record of loaded files. On each hourly run, the same files are inserted again, so the table fills with duplicate rows. Force is for a deliberate one-time reload by hand.