Sub topic 12
Choosing between COPY INTO and Auto Loader
This chapter assumes you can write a basic COPY INTO statement, you know how COPY INTO skips files it has already loaded, and you have seen a Delta table and a Unity Catalog volume. You don't need to have used Structured Streaming. The chapter explains the parts of Auto Loader you need for the decision.
Two tools for the same job
Both tools load new files from cloud storage into a Delta table and avoid loading the same file twice. They differ in how they find new files, where they record progress, and how they handle schema changes.
- COPY INTO is a SQL command. Each run lists the source location, compares the files with the load history stored with the target table, and loads the files it hasn't seen.
- Auto Loader is a streaming source called
cloudFiles. It finds new files incrementally and records progress in a checkpoint, which is a storage location the stream owns. You use it from Python or Scala, or from SQL in pipelines.
Auto Loader is a streaming source, but that doesn't mean it must run continuously. With the availableNow trigger it processes all pending files and then stops, so it fits a scheduled batch job.
How each tool finds new files
COPY INTO
Each execution lists the source path (narrowed by PATTERN or FILES) and checks the listing against what the table has already loaded. The cost of discovery grows with the number of files in the location. Idempotency is a property of the target table, not of a job or a query. Two different COPY INTO statements writing to the same table share the same history. A new table starts with no history, so it loads everything again.
Auto Loader
Auto Loader supports two discovery modes:
| Mode | How it finds files | Typical use |
|---|---|---|
| Directory listing | Lists the directory and uses its own state to skip known files. This is the default. | Simple setups, no cloud event configuration |
| File notification | Uses cloud storage events and a queue service that Auto Loader can set up for you | Very large directories where listing is slow |
Progress lives in the checkpoint. If you delete the checkpoint or point the stream at a new one, Auto Loader treats the source as new and reprocesses every file. The checkpoint is therefore the counterpart of the target table's history in COPY INTO, and you must treat it as state worth protecting.
The same load in both tools
The COPY INTO version:
COPY INTO main.sales.orders_raw
FROM '/Volumes/main/sales/landing/orders/'
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true', 'inferSchema' = 'true')
COPY_OPTIONS ('mergeSchema' = 'true');The Auto Loader version, run as a batch job that stops when no files are left:
(spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "csv")
.option("cloudFiles.schemaLocation", "/Volumes/main/sales/state/orders_schema")
.option("header", "true")
.load("/Volumes/main/sales/landing/orders/")
.writeStream
.option("checkpointLocation", "/Volumes/main/sales/state/orders_checkpoint")
.option("mergeSchema", "true")
.trigger(availableNow=True)
.toTable("main.sales.orders_raw"))Differences to notice:
- Auto Loader needs two extra locations:
cloudFiles.schemaLocationfor inferred schemas andcheckpointLocationfor progress. Keep both outside the source directory so they are never read as data. - Auto Loader infers column types as strings for CSV and JSON unless you set
cloudFiles.inferColumnTypestotrue.COPY INTOwithinferSchemainfers types directly. - The
COPY INTOstatement is a single self-contained piece of SQL. The Auto Loader job is a small program.
Schema handling
Both tools can add new columns, but they behave differently when a file doesn't match.
COPY INTOwithmergeSchemaadds new columns it finds to the target table. Without it, a file with extra columns doesn't load cleanly, and you debug it from the error message.- Auto Loader defaults to
addNewColumnsevolution mode. When it meets a new column, the stream stops with an error after updating the stored schema, and the next run picks up the new column. This is deliberate. You usually run Auto Loader under a job with retries, so the second attempt succeeds. - Auto Loader can also keep unexpected data in a
_rescued_datacolumn, which holds values that didn't fit the schema (wrong type, extra column) instead of failing or dropping them.COPY INTOhas no equivalent column.
Plan for this difference if you move a pipeline from one tool to the other. A job that ran cleanly under COPY INTO can fail once on the first new column under Auto Loader.
Scale and cost
Databricks guidance puts the boundary roughly here: COPY INTO suits sources with thousands of files, and Auto Loader suits sources with millions of files or more, or sources that keep growing. Treat these as rough guides, not hard limits. What matters is how long file discovery takes relative to the actual load.
- Few new files in a large directory.
COPY INTOstill lists the whole location every run. Auto Loader in file notification mode only works on files the events announce. - Many new files per run. Auto Loader processes files in bounded batches and can resume after a failure from its checkpoint. A single large
COPY INTOis one statement that must complete as a whole. - A one-off backfill of a modest set of files.
COPY INTOis simpler, because there is no checkpoint to manage and no state to clean up afterward.
Control and transformation
COPY INTO gives you a SQL SELECT source for casting and for adding _metadata.file_path. It also gives you VALIDATE to preview a load and force to reload files on demand. Those make it convenient for analysts who work in SQL and want explicit, repeatable control.
Auto Loader gives you the full DataFrame API between the read and the write, so you can use foreachBatch, joins, or custom logic. It has no VALIDATE option. To preview, you write to a scratch table or display the stream's output in a notebook. To reload everything, you reset the checkpoint, which is a bigger operation than setting force.
Decision guide
Use this table to check the result:
| Question | COPY INTO | Auto Loader |
|---|---|---|
| Interface | SQL statement | `cloudFiles` stream in Python, Scala, or pipeline SQL |
| Progress stored in | Target table's load history | Checkpoint location |
| Discovery cost | Lists the location each run | Incremental, with optional file notification |
| New columns | `mergeSchema` copy option | Schema evolution modes plus `_rescued_data` |
| Preview before writing | `VALIDATE n ROWS` | No direct equivalent |
| Reload files | `force = true` | New checkpoint |
| Extra state to manage | None | Schema location and checkpoint |
Gotchas when switching
- Starting Auto Loader on a directory
COPY INTOalready loaded. The new checkpoint is empty, so Auto Loader loads every file again and you get duplicates. Either load into a new table, or use thecloudFiles.includeExistingFilesoption set tofalseso the stream only reads files that arrive after it starts. Check that no files arrived between the lastCOPY INTOrun and the first stream run. - Moving from Auto Loader back to
COPY INTO. The table has noCOPY INTOhistory for those files, so the first run loads everything again. Plan the cutover so only new files remain in the source path, or usePATTERNto select only the new ones. - Treating
forceas a fix.force = truemakesCOPY INTOreload every matching file and duplicate rows. Use it only after you have emptied or deliberately rebuilt the target. - Putting state inside the source directory. Schema and checkpoint files in the landing path can be picked up as data or cleaned up by retention rules for the landing area.
Putting it together
Take three workloads.
- A finance team drops 20 CSV files a day into a volume. Analysts maintain the pipeline in SQL. Choose
COPY INTO, because the volume is small, the work is SQL, andVALIDATEhelps before each month-end load. - A clickstream feed writes hundreds of thousands of small JSON files per day, and the event format changes often. Choose Auto Loader with file notification and
_rescued_data, because listing is costly and schema drift is expected. - A partner delivers a one-time archive of 5,000 Parquet files. Choose
COPY INTO, because there is nothing to keep running and no state to maintain afterward.
Exercise
A landing directory holds about 3 million JSON files and gains more every hour. Each run of your COPY INTO job now spends most of its time before loading any data. Which tool should you move to, which discovery mode would you consider, and what must you do to avoid loading existing files twice?
Show answer
Move to Auto Loader, because COPY INTO lists the whole location on every run and that listing cost grows with the file count. Consider file notification mode, which uses cloud storage events instead of listing the directory. To avoid duplicates, load into a new table, or start the stream with cloudFiles.includeExistingFiles set to false after confirming that no files arrived between the last COPY INTO run and the first stream run. The new checkpoint has no record of the files COPY INTO already loaded, so without one of these steps Auto Loader would load them all again.
Exercise
A teammate says, "Auto Loader is streaming, so it can't be used in a nightly batch job." Is that correct? Show the setting that makes a stream stop after processing pending files.
Show answer
No. Auto Loader can run as a batch job by using the availableNow trigger, which processes all files that are pending and then stops. In the writeStream call, add .trigger(availableNow=True). The checkpoint still records progress, so the next nightly run only reads files that arrived since the last run.