Sub topic 14
Doing the Same Ingestion in SQL
This chapter shows how to write the orders ingestion from earlier chapters as a SQL streaming table. It assumes you know the Python cloudFiles stream, checkpoints, schema inference and the rescued data column, and that you can read basic SQL against Unity Catalog tables.
Why a SQL version exists
The Python version needs a readStream, a writeStream, a checkpoint path and a schema location. That is a lot of plumbing for analysts who only know SQL, and for pipelines where the platform can manage state for you.
Databricks offers the same behavior in SQL through two pieces:
read_filesis a table-valued function that reads files from a path. InsideSTREAM read_files(...)it runs on Auto Loader.- A streaming table is a Delta table that is kept up to date by a streaming query. The platform creates and manages the checkpoint and the schema location for you.
You write what you want, and the platform decides where the state lives.
The basic statement
This statement ingests the same landing folder as the first Python example.
CREATE OR REFRESH STREAMING TABLE orders_bronze AS
SELECT *, _metadata.file_path AS source_file
FROM STREAM read_files(
'/Volumes/main/raw/landing/orders',
format => 'json'
);Compare it with the Python version:
| Python Auto Loader | SQL streaming table |
|---|---|
| `format("cloudFiles")` | `STREAM read_files(...)` |
| `cloudFiles.format` option | `format => 'json'` argument |
| `cloudFiles.schemaLocation` option | Managed by the platform |
| `checkpointLocation` option | Managed by the platform |
| `trigger(availableNow=True)` | Each refresh processes pending files, then stops |
| `.toTable("main.bronze.orders")` | The `CREATE ... STREAMING TABLE` name |
| `withColumn("source_file", col("_metadata.file_path"))` | `_metadata.file_path AS source_file` in the `SELECT` |
The STREAM keyword is what makes the read incremental. Without it, read_files is a plain batch read that scans every file each time the query runs. That is the full-listing problem from the start of this tutorial. If a refresh keeps reprocessing old files, check for a missing STREAM first.
What a refresh does
A streaming table does not run continuously by default. You trigger a refresh, and it behaves like an availableNow run:
- It lists or discovers files that are not yet recorded in its checkpoint.
- It reads those files and appends their rows to the table.
- It records the files as processed and stops.
You can refresh on demand or on a schedule.
REFRESH STREAMING TABLE orders_bronze;You can also attach a schedule when you create the table.
CREATE OR REFRESH STREAMING TABLE orders_bronze
SCHEDULE EVERY 1 HOUR
AS
SELECT *, _metadata.file_path AS source_file
FROM STREAM read_files(
'/Volumes/main/raw/landing/orders',
format => 'json'
);Rows already ingested are not read again, for the same reason as in Python: the checkpoint remembers which files were processed.
Passing Auto Loader options
Most cloudFiles options you used in Python have a counterpart. You pass format-specific reader options as named arguments to read_files.
CREATE OR REFRESH STREAMING TABLE events_bronze AS
SELECT *, _metadata.file_path AS source_file
FROM STREAM read_files(
's3://my-bucket/landing/events',
format => 'csv',
header => true,
schemaHints => 'event_id BIGINT, event_ts TIMESTAMP',
schemaEvolutionMode => 'addNewColumns'
);Notes on the options:
formatis required for anything other than a case where the format can be deduced. State it explicitly.schemaHintsplays the role ofcloudFiles.schemaHints. Use it to pin types you do not want inferred.schemaEvolutionModeplays the role ofcloudFiles.schemaEvolutionMode.- Reader options such as
headeruse the same names as in the batch CSV reader. - Option names in
read_filesdrop thecloudFiles.prefix. If an option you need is not accepted under that short name, check theread_filesreference for your runtime version.
Schema behavior in SQL
Schema inference works as in Python. The first refresh samples files, infers a schema and stores it. Later refreshes compare incoming files with the stored schema.
Two points matter in practice:
- The rescued data column still exists. Values that do not match the schema, and columns that are not in the schema, land in
_rescued_datawhen evolution does not add them. Query it to find drift. - With
addNewColumns, a file that has an unknown column makes the refresh fail once. The schema is updated, and the next refresh succeeds with the new column. Schedule retries or rerun the refresh after such a failure. This matches the behavior of the Python stream, which stops and expects a restart.
A quick drift check looks like this.
SELECT source_file, _rescued_data
FROM orders_bronze
WHERE _rescued_data IS NOT NULL
LIMIT 20;Choosing between SQL and Python
| Question | Prefer SQL streaming table | Prefer Python Auto Loader |
|---|---|---|
| Who maintains the pipeline? | Analysts or SQL engineers | Data engineers comfortable with Spark |
| Need to manage checkpoint paths yourself? | No | Yes |
| Need a continuous trigger or custom `foreachBatch` logic? | No | Yes |
| Transformations | Simple projections and filters | Arbitrary code, custom merge logic |
| Rate limits and fine-grained options | Limited to what `read_files` exposes | All `cloudFiles` options |
Streaming tables suit plain bronze ingestion well. If you need to merge into a target with foreachBatch, or tune a lower-level option, use the Python API.
Limits to know
- A streaming table is append-oriented. Auto Loader reads each file once, so changing the query does not rewrite old rows. A full refresh (
REFRESH STREAMING TABLE orders_bronze FULL) clears the table and its checkpoint and reprocesses everything. Do not run it casually on sources whose old files have been deleted, because the data would be lost. - Only the table owner or a user with the right privileges can refresh it.
- Streaming tables run on Databricks SQL warehouses or in a pipeline. Check your workspace for the compute it supports.
Summary of the mapping
STREAM read_files(...)is the Auto Loader source in SQL.- The streaming table owns the checkpoint and schema location.
- Each refresh behaves like an
availableNowrun. - Schema hints, evolution modes,
_rescued_dataand_metadatacarry over unchanged. - Leaving out
STREAMturns the read into a full batch scan.
Exercise
A teammate writes CREATE OR REFRESH STREAMING TABLE t AS SELECT * FROM read_files('/Volumes/main/raw/landing/orders', format => 'json'); and notices every refresh takes longer as the folder grows. What is wrong, and how do you fix it?
Show answer
The query omits the STREAM keyword, so read_files runs as a batch read and scans all files on every refresh instead of only new ones. Change the source to FROM STREAM read_files(...) so Auto Loader uses the checkpoint to process only files it has not seen.
Exercise
Translate this Python option set into a read_files call: format JSON, schema hints order_id BIGINT, order_ts TIMESTAMP, evolution mode addNewColumns, path /Volumes/main/raw/landing/orders.
Show answer
SELECT * FROM STREAM readfiles('/Volumes/main/raw/landing/orders', format => 'json', schemaHints => 'orderid BIGINT, order_ts TIMESTAMP', schemaEvolutionMode => 'addNewColumns') used inside a CREATE OR REFRESH STREAMING TABLE statement.