Sub topic 1
How a Delta table is stored
Every later technique in this tutorial changes how rows are arranged in files. OPTIMIZE, Z-ordering and liquid clustering all rewrite files, and VACUUM deletes them. To see what these commands do, you first need to know what a Delta table physically is. This chapter covers the files, the transaction log, and the statistics that the rest of the tutorial relies on.
Prerequisites
This chapter assumes you have the following:
- Basic SQL:
CREATE TABLE,SELECT,WHERE. - Some familiarity with Databricks notebooks or SQL warehouses.
- A basic idea of Parquet files and columnar storage.
- Awareness of what a Spark job and a Spark partition are.
You do not need to know the Delta log format beforehand. The chapter introduces it step by step.
A table is files plus a log
A Delta table is a directory in cloud object storage (S3, ADLS or GCS) that holds two things:
- Data files. These are ordinary Parquet files that hold the rows.
- A transaction log. This is a subdirectory named
_delta_logthat records which data files make up the table at each version.
The log decides which files belong to the table. A Parquet file sitting in the directory is not part of the table unless the log says it is. This is why a table can have extra files on disk that queries never read, and it is the reason VACUUM exists (covered in a later chapter).
A typical directory looks like this:
events/
part-00000-1a2b...-c000.snappy.parquet
part-00001-3c4d...-c000.snappy.parquet
_delta_log/
00000000000000000000.json
00000000000000000001.json
00000000000000000002.json
00000000000000000010.checkpoint.parquet
_last_checkpointOn a partitioned table, the data files sit in subdirectories such as event_date=2024-01-01/. The log stays at the top level.
Data files are immutable
Parquet files are never edited in place. Every change to the table follows the same pattern:
- An
INSERTwrites new files. - A
DELETEorUPDATErewrites the files that contain affected rows. It writes new files with the changed content and marks the old ones as removed. - A
MERGEdoes the same for every file that contains a matching row.
The old files are not deleted when they are marked as removed. They stay in storage so that earlier table versions remain readable (time travel) and so that queries already running do not lose their files. VACUUM removes them later.
Immutability has a direct layout consequence. Each write operation produces its own new files, and a table that gets many small writes accumulates many small files. The next chapter looks at that problem.
The transaction log
Each write operation ends with a commit: a new JSON file in _delta_log, numbered with a zero-padded version, such as 00000000000000000007.json. A commit contains a list of actions. The ones you will meet most often are:
| Action | What it records |
|---|---|
| `add` | A data file joined the table. Includes its path, size, partition values, and statistics. |
| `remove` | A data file left the table. The file stays in storage until VACUUM deletes it. |
| `metaData` | The schema, partition columns, and table properties. |
| `protocol` | The reader and writer features a client must support to use the table. |
| `commitInfo` | Audit information: the operation name, parameters, user, and metrics. |
The table at version N is defined as the result of replaying commits 0 through N. Every add puts a file into the set, and every remove takes one out. The files left in the set are the active files. A reader that wants an older version stops the replay earlier. That is how SELECT ... VERSION AS OF works.
Checkpoints
Replaying thousands of JSON files would be slow. By default, Delta writes a checkpoint every 10 commits. A checkpoint is a Parquet file that stores the full set of active files and metadata at that version. A reader loads the latest checkpoint, then replays only the JSON commits after it. The _last_checkpoint file tells readers where to find it.
Concurrent writers
Delta uses optimistic concurrency. A writer prepares its files, then tries to create the next numbered commit file. Object stores or the Delta client guarantee that only one writer can create a given version. If two writers collide, the loser checks whether the winner's changes conflict with its own. If they do not, it retries on the next version. If they do, it fails with a conflict exception. This is why two jobs rewriting the same files (for example, OPTIMIZE and a MERGE touching the same partition) can fail while jobs on separate partitions usually do not.
Statistics in the log
An add action also carries per-file statistics, stored as a JSON string. They include:
numRecords: the number of rows in the file.minValuesandmaxValues: the smallest and largest value of each indexed column in that file.nullCount: the number of nulls per indexed column.
By default, Delta collects statistics for the first 32 columns of the table. The table property delta.dataSkippingNumIndexedCols changes this limit. Long string columns are poor candidates for statistics, because min and max values are truncated and rarely prune anything. Put columns that you filter on near the front of the schema, or adjust the property.
These statistics enable data skipping. For a query such as WHERE user_id = 42, the engine reads the log, finds the files whose minValues/maxValues range for user_id cannot contain 42, and never opens them. Skipping works from the log alone, before any Parquet data is read. How well it works depends on how values are spread across files, which is the central theme of this tutorial.
Looking at a real table
You can inspect all of this from a notebook. Start with the table-level summary:
DESCRIBE DETAIL events;The result includes location (the directory), numFiles, sizeInBytes, partitionColumns, clusteringColumns and properties. Dividing sizeInBytes by numFiles gives the average file size, a quick check for the small-files problem.
The commit history shows what each version did:
DESCRIBE HISTORY events;Each row has a version, timestamp, operation (such as WRITE, MERGE, OPTIMIZE), and operationMetrics. These metrics include the number of files and rows added and removed.
To look at the raw log, list the directory and read a commit:
location = spark.sql("DESCRIBE DETAIL events").first()["location"]
for f in dbutils.fs.ls(f"{location}/_delta_log"):
print(f.name, f.size)
# Change the version number to a commit that wrote data.
commit = spark.read.json(f"{location}/_delta_log/00000000000000000001.json")
commit.where("add IS NOT NULL").select("add.path", "add.size", "add.stats").show(truncate=False)The stats column holds the JSON string with numRecords, minValues, maxValues and nullCount. Reading raw log files is useful for learning and debugging. In day-to-day work, rely on DESCRIBE DETAIL and DESCRIBE HISTORY. The log format can gain features over time, and Databricks documents the SQL commands as the supported interface.
Edge cases to know
- Files not in the log are invisible. Files copied into the directory by hand are ignored. Deleting data files directly in storage corrupts the table, because the log still lists them and queries then fail.
- Missing statistics. Files written before statistics were configured, or columns beyond the indexed limit, have no min/max values. Queries filtering on those columns cannot skip files.
- Small commits are cheap, small files are not. Many tiny commits make the log longer, but checkpoints keep reads fast. The real cost is the number of data files each query must open.
- Table size in storage can exceed
sizeInBytes.DESCRIBE DETAILreports only active files. Removed files still occupy storage until VACUUM deletes them. - Retention limits time travel. Once VACUUM deletes a removed file, any version that needed it can no longer be read.
What comes next
The pieces in this chapter explain the rest of the tutorial:
- Many small writes create many small immutable files, so reads slow down (small files and OPTIMIZE).
- Min/max statistics in the log let queries skip files, but only if similar values are stored together (partitioning, Z-ordering, liquid clustering).
- Rewriting files leaves old ones behind until VACUUM runs.
Exercise
A table has 40 active data files according to DESCRIBE DETAIL, but the storage directory holds 150 Parquet files. Name two likely explanations and say which command would clear one of them.
Show answer
The extra 110 files are either files marked as removed in the log (left behind by UPDATE, DELETE, MERGE or OPTIMIZE rewrites and kept for time travel), or files that were never added to the log, for example from a failed write or from files copied in by hand. VACUUM deletes unreferenced files that are older than the retention period, which clears the first case.
Exercise
A query filters on a column that is the 45th column of a wide table, and it opens every file. Why might data skipping not help here, and what setting could change that?
Show answer
By default, Delta collects min/max statistics only for the first 32 columns. A column beyond that limit has no statistics, so the engine cannot prove any file is irrelevant. Raising delta.dataSkippingNumIndexedCols, or moving the column earlier in the schema, makes statistics available for it. Statistics apply to files written after the change.