≈ The Lake

Part 5 · Apache Iceberg spec · Chapter 19

Schemas, field IDs and sort orders

Why Iceberg tracks columns by ID, the schema evolution rules that follow, type promotion and how old statistics are decoded, default values, reading files that have no IDs, and sort orders and how Spark uses them when writing.

complete ~35 min

After this chapter you should be able to:
  • Explain why add, drop, rename and reorder are safe with field ids, and what goes wrong by name or position.
  • List the type promotions per format version and what the Java library implements.
  • Resolve a column missing from a data file using the spec's four rules.
  • Explain initial-default and write-default.
  • Describe sort orders, and how Spark derives distribution and ordering from the spec and sort order.

A Hive table finds a column in a data file by name or by position. Both break under ordinary changes. Reading by position breaks when a column is dropped or reordered. Reading by name breaks when a column is renamed, and silently returns old data when a dropped column’s name is reused. Iceberg gives every column a permanent integer id and stores it in each data file, so the table schema and the file schema are matched by id. This chapter covers what that buys, the rules it imposes, and the two schema-adjacent pieces of table metadata: default values and sort orders.

Links point to apache/iceberg at 9d2bf51.

Field IDs

“Each field in the tuple is named and has an integer id that is unique in the table schema.” List elements, map keys and map values have ids too.[spec] Table metadata keeps every schema (schemas, current-schema-id) and last-column-id, “the highest assigned column ID for the table … used to ensure columns are always assigned an unused ID when evolving schemas”.[spec] SchemaUpdate assigns new ids by incrementing it:[src]

private int assignNewColumnId() {
  int next = lastColumnId + 1;
  this.lastColumnId = next;
  return next;
}

An id is never reused. If column a (id 1) is dropped and a new a is added, the new one gets a fresh id, and files that only contain id 1 return null for it. A reader matching by name would return the dropped column’s old values.

Ids above Integer.MAX_VALUE - 200 (2147483447) are reserved for metadata columns: _file (2147483646), _pos, _deleted, _spec_id, _partition, the position-delete columns file_path and pos, the changelog columns, and the row-lineage columns _row_id and _last_updated_sequence_number.[spec]

Quiz Field IDsAnswers are scheduled for spaced review on the Review page.

Q1. How does an Iceberg reader find a table column inside a data file?

How sure are you?

Q2. Column a (id 1) is dropped, then a new column a is added. What does a by-id reader return for a in files written before the drop?

How sure are you?

Q3. What does last-column-id in table metadata guarantee?

How sure are you?

Q4. Which field ids are reserved for metadata columns such as _file and _pos?

How sure are you?

Column projection

“Columns in Iceberg data files are selected by field id. The table schema’s column names and order may change after a data file is written, and projection must be done using field ids.” The spec’s example: a file written with 1: a int, 2: b string, 3: c double, read with 3: measurement, 2: name, 4: a, “must select file columns c (renamed to measurement), b (now called name), and a column of null values called a; in that order.”[spec]

When a field id is not in a file, the value is resolved in this order:

  1. The value from partition metadata, if an identity transform exists for the field and the partition struct in the manifest entry has it. “This allows for metadata only migrations of Hive tables”, whose files don’t contain their partition columns.
  2. The name mapping in schema.name-mapping.default, for files written without ids.
  3. The field’s initial-default.
  4. null.
Reading an old file after rename, reorder and re-add
ReaderSELECT measurement, name, ametadata.jsoncurrent-schema-idManifest entrypartition, statsParquet filewritten with 1: a, 2: b, 3: c1. current schema: 3: measurement, 2: name, 4: a2. read footer: field_id on each column3. match by id: 3 → c, 2 → b4. id 4 missing: identity partition value?5. name mapping? initial-default?6. a = null
  1. current schema: 3: measurement, 2: name, 4: a. The projection schema comes from the table, by id. Column c was renamed to measurement and moved first; a was dropped and a new a (id 4) added. Schema Evolution ↗
  2. read footer: field_id on each column. Iceberg writers store each column's field id in the Parquet schema. ReadConf checks hasIds; a file with ids is pruned to the requested ids. ReadConf ↗
  3. match by id: 3 → c, 2 → b. Names in the file are ignored. The renamed and reordered columns resolve correctly, in the projection's order. Column Projection ↗
  4. id 4 missing: identity partition value?. First rule for a missing id: if an identity partition field has the value in the manifest entry, use it. This is what allows metadata-only migrations of Hive tables.
  5. name mapping? initial-default?. Next, for files without ids, schema.name-mapping.default maps names to ids. Then the field's initial-default. Here none applies. Default values ↗
  6. a = null. The old column a (id 1) is never read for the new a (id 4). A reader that matched by name would have returned it.
Follows the spec's Column Projection rules and the Parquet ReadConf at 9d2bf51.

Iceberg writers put the field id in each Parquet column’s schema. In the Java Parquet reader, ReadConf picks one of three paths:[src]

if (ParquetSchemaUtil.hasIds(fileSchema)) {
  typeWithIds = fileSchema;
  this.projection = ParquetSchemaUtil.pruneColumns(fileSchema, expectedSchema);
} else if (nameMapping != null) {
  typeWithIds = ParquetSchemaUtil.applyNameMapping(fileSchema, nameMapping);
  this.projection = ParquetSchemaUtil.pruneColumns(typeWithIds, expectedSchema);
} else {
  typeWithIds = ParquetSchemaUtil.addFallbackIds(fileSchema);
  this.projection = ParquetSchemaUtil.pruneColumnsFallback(fileSchema, expectedSchema);
}

The last path is the trap. addFallbackIds numbers top-level columns 1, 2, 3 by position.[src] For a file imported without ids into a table that has since dropped or reordered columns, that is reading by position. The name mapping is the fix. It is a JSON list of { "names": [...], "field-id": n } objects, can list several names per id (old names and aliases), and can give an Iceberg-only field an empty names list.

Quiz Column projectionAnswers are scheduled for spaced review on the Review page.

Q1. A field id is not in a data file. In what order does the spec resolve its value?

How sure are you?

Q2. A Parquet file has no field ids and the table has no name mapping. What does the Java Parquet reader do?

How sure are you?

Q3. What is schema.name-mapping.default for?

How sure are you?

Evolution rules

“Any struct, including a top-level schema, can evolve through deleting fields, adding new fields, renaming existing fields, reordering existing fields, or promoting a primitive using the valid type promotions.” Every change produces a new schema with a new schema id, which becomes current. Renames change the name and never the id. Two kinds of change are not allowed: moving fields between a struct and a nested struct, and turning a primitive into a struct or back.[spec]

SchemaUpdate implements the API: addColumn, deleteColumn, renameColumn, updateColumn (type), moveFirst, moveAfter, requireColumn and makeColumnOptional. Its commit() makes a single call to ops.commit(base, update), with no retry loop (chapter 17).[src] Adding a required column needs a default:[src]

Preconditions.checkArgument(
    defaultValue != null || isOptional || allowIncompatibleChanges,
    "Incompatible change: cannot add required column without a default value: %s", fullName);

Making a column required, or adding a required one with allowIncompatibleChanges(), means old files have nulls that the new schema says can’t exist. So these need the explicit opt-in.

Type promotion

Fromv1, v2v3+
intlonglong
floatdoubledouble
decimal(P, S)decimal(P', S), P' > Psame
datenonetimestamp, timestamp_ns (not the tz types)
unknownnoneany type
[spec]

The Java check at the pin, TypeUtil.isPromotionAllowed, implements the first three rows only. updateColumn therefore rejects date → timestamp even in a v3 table, with “Cannot change column type”.[src][src]

Two constraints come from other parts of the format:

  • Partitions. A promotion is not allowed for a partition source column “if the partition transform would produce a different value after promoting the type.” The spec’s example uses the bucket hash from chapter 18. 34 and 34L both hash to 2017239379, but "34" hashes to -427558391. So int to long is fine for a bucket source, and int to string would not be.
  • Statistics. Manifests don’t store the type of lower and upper bounds, and promotion doesn’t rewrite them. A reader infers the type the file was written with from the bound’s length. Under a long column, a 4-byte bound means int. Under double, 4 bytes means float. Under timestamp, 4 bytes means date.
Quiz Evolution rulesAnswers are scheduled for spaced review on the Review page.

Q1. Which type changes does SchemaUpdate.updateColumn accept at the pinned commit? (select all that apply)

How sure are you?

Q2. Why can an int column that is the source of a bucket[N] partition be promoted to long but not to string?

How sure are you?

Q3. A float column was promoted to double. A manifest has a 4-byte upper bound for it. How is it decoded?

How sure are you?

Q4. What does SchemaUpdate require to add a required column to an existing table?

How sure are you?

Default values

Format v3 adds two defaults per field:[spec]

  • initial-default “is used to populate the field’s value for all records that were written before the field was added”. It is set when the field is added and never changes.
  • write-default “is used to populate the field’s value for any records written after the field was added … if the writer does not supply the field’s value”. It starts equal to initial-default and may change.

Together they give SQL DEFAULT behavior “without rewriting data files”. Writers always write every known field (“Omitting a known field when writing a data file is never allowed”), so write-default ends up in data files and initial-default is only ever read from metadata. A required field’s write must fail if its default is missing or null. Non-null defaults are rejected in tables below v3: Schema reports “non-null default … is not supported until v3”.[src] In the v4 draft, write-default may be an expression such as current_timestamp().

Two defaults serve two generations of files
File from before the field
  1. Value missing in the file The field did not exist when this file was written.
  2. Reader uses initial-default The value comes from schema metadata.
File written with the field
  1. Value omitted by the caller The writer fills in the field.
  2. Writer stores write-default The value is written to the file.
A later change to write-default affects subsequent writes. The initial-default for files from before the field was added stays fixed.[Iceberg spec]
Quiz DefaultsAnswers are scheduled for spaced review on the Review page.

Q1. A column is added with initial-default 1, then its write-default is changed to 5. What do rows from files written before the column existed read as?

How sure are you?

Sort orders

A sort order is an id and a list of sort fields. Each field has a source column (or columns), a transform (the partition transforms), a direction (asc or desc) and a null order (nulls-first or nulls-last). Order id 0 is reserved for unsorted. Each data or delete file records the sort_order_id it was written with in its manifest entry, so a table must keep every order it has used. The default order is a hint: “Writers should use this default sort order to sort the data on write, but are not required to if the default order is prohibitively expensive, as it would be for streaming writes.” It “is not used when reading”.[spec][spec]

Spark sets it with the SQL extensions:[grammar][grammar]

ALTER TABLE db.events WRITE ORDERED BY category, id;
ALTER TABLE db.events WRITE DISTRIBUTED BY PARTITION LOCALLY ORDERED BY id;
ALTER TABLE db.events WRITE UNORDERED;

On write, Spark asks the engine for a distribution and an ordering. With no write.distribution-mode, the default is range if the table has a sort order, hash if it is partitioned, and none otherwise. An explicit hash on an unpartitioned table becomes none.[src] The ordering is the sort order with any partition fields it doesn’t already cluster by prepended. SortOrderUtil.buildSortOrder makes the result “cluster by partition and still produce the same order within each partition”.[src] With the fanout writer enabled and no sort order, no ordering is requested.[src]

Sorted files have tight, non-overlapping column bounds, so the metrics pruning of chapter 16 skips more of them. Chapter 26 covers why this matters and what Z-order adds.

Quiz Sort ordersAnswers are scheduled for spaced review on the Review page.

Q1. Does default-sort-order-id affect how a table is read?

How sure are you?

Q2. A partitioned Iceberg table has a sort order and no write.distribution-mode set. Which distribution does Spark request for an INSERT?

How sure are you?

Try it

The lab keeps every file written so far and reads all of them with the current schema. Switch the read strategy to compare Iceberg’s by-id reads with by-name and by-position reads; cells that differ turn red.

  • Rename price to cost, then read by name: old files lose the column.
  • Drop name, add a new name, write a file, and read by name: old files bring back the dropped values.
  • Move name first and read by position.
  • Import a Hive file (no ids), drop name, and see the fallback ids read the wrong column. Turn on the name mapping to fix it.
  • Upgrade to v3, add a required qty with default 1, change its write default, and write a file.
Read files

Current schema 0 · v2 · last-column-id 3

  • 1: id int required
  • 2: name string
  • 3: price float
column
rename to
change type to
add
  1. CREATE TABLE (1: id int, 2: name string, 3: price float); one file written.

SELECT * · every file, current schema

fileid #1name #2price #3
00000.parquet s01pen2
00000.parquet2ink3

Hover a cell to see how it was resolved. Red cells differ from the by-id read. Files list their columns by field id; a Hive file has names only.

Column Projection ↗ · ReadConf ↗ · isPromotionAllowed ↗

Comparison with Delta

Delta reads Parquet by column name unless the table enables column mapping. With column mapping, each column has a physical name and an id (delta.columnMapping.physicalName, delta.columnMapping.id), and readers resolve by physical name (name mode) or by Parquet field id (id mode). Chapter 15 covers it. Iceberg has had field ids since v1 and has no by-name mode for its own files; names matter only through the name mapping for imported files. Delta’s type widening (chapter 15) is a table feature with its own list of allowed changes. Iceberg’s promotions are part of the format and apply to every table.[protocol]

Quiz DeltaAnswers are scheduled for spaced review on the Review page.

Q1. What plays the role of Iceberg field ids in Delta?

How sure are you?

Concepts in this chapter

Explained here

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 15 quiz questions.

Review this chapter's cards → Review all due cards