> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lancedb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Branches

> Fork isolated, writable lines of table history in LanceDB. Run experiments, backfills, and index rebuilds without disturbing production reads on main.

A branch is an isolated, writable line of history forked from `main` (or from any
other branch). Anything you do on a branch (e.g., adding rows, changing the schema,
building an index) stays on that branch, so `main` keeps serving production
reads exactly as before. Branches are a natural fit when you want to:

* Experiment with a new index, schema change, or reprocessing step without
  affecting live queries on `main`.
* Run a backfill or migration you'd like to validate before applying it to
  `main`.
* Hand a collaborator a frozen point-in-time fork while you keep writing to `main`.

## How branches relate to versions and tags

Every LanceDB table already tracks a linear history of [versions](https://docs.lancedb.com/tables/versioning.md),
and you can [tag](https://docs.lancedb.com/tables/versioning.md#tag-based-versioning) a version or `checkout`
one to read it. Branches add the missing piece: a *separate, writable* line of
history. Where a tag is a read-only label and `checkout` is a read-only view, a
branch forks from a point in history and then evolves on its own. Creating or
checking out a branch hands you a new table handle whose reads and writes are
scoped to that branch. The [comparison table](#branches-vs-tags-vs-checkout) at
the end of this page lays out when to reach for each.

> [!NOTE]
>
> Branches are supported on local and namespace-backed tables in LanceDB OSS, as
> well as on LanceDB Enterprise (remote) tables.

## Connect to a table

The branch API is identical no matter how you connect — only the connection
itself differs between OSS and Enterprise. Establish a connection (`db`) and open
a `table` (see [Create a table](https://docs.lancedb.com/tables/create.md)), then use the same branch calls
in every example that follows.

### LanceDB OSS

Point LanceDB at a local directory (or an object-storage URI) to use it as an
embedded library.

import lancedb

uri = "ex\_lancedb"
db = lancedb.connect(uri)


import \* as lancedb from "@lancedb/lancedb";

async function connectExample(uri: string) \{
&#x20; const db = await lancedb.connect(uri);
&#x20; return db;
}


use lancedb::connect;



async fn connect\_example(uri: \&str) \{
&#x20;   let db = connect(uri).execute().await.unwrap();
&#x20;   let \_ = db;
}


### LanceDB Enterprise

Enterprise

Branching on LanceDB Enterprise works the same way as on OSS, but you connect to your
Enterprise deployment with a `db://` URI, an API key, and your
region. Once you have a connection, open a table and use the same branch calls in
every example that follows.

uri = "db://your-database-uri"
api\_key = "your-api-key"
region = "us-east-1"
host\_override = "https\://your-enterprise-endpoint.com"

db = lancedb.connect(
&#x20;   uri=uri,
&#x20;   api\_key=api\_key,
&#x20;   region=region,
&#x20;   host\_override=host\_override,
)


const uri = "db://your-database-uri";
const apiKey = "your-api-key";
const region = "us-east-1";
const hostOverride = "https\://your-enterprise-endpoint.com";

const db = await lancedb.connect(uri, \{
&#x20; apiKey,
&#x20; region,
&#x20; hostOverride,
});


let uri = "db://your-database-uri";
let api\_key = "your-api-key";
let region = "us-east-1";
let host\_override = "https\://your-enterprise-endpoint.com";


## Work with branches

The lifecycle of a branch is short and predictable: fork it, write to it, reopen
it whenever you need it, and delete it once you're done. The examples below use a
small `quotes` table with three rows on `main`.

### Create a branch

Forking from `main` returns a table handle scoped to the new branch. `main` is
the reserved default source, so `create` needs only a name; to fork from
somewhere else, pass a branch name, a specific version, or both.

\# Fork an isolated, writable branch from main's latest version.
\# \`create\` returns a table handle scoped to the new branch.
branch = table.branches.create("exp")


// Fork an isolated, writable branch from main's latest version.
// \`create\` returns a table handle scoped to the new branch.
const branch = await branches.create("exp");


// Fork an isolated, writable branch from main's latest version.
// \`create\_branch\` returns a table handle scoped to the new branch.
let branch = branches\_table
&#x20;   .create\_branch("exp", Ref::Version(None, None))
&#x20;   .await
&#x20;   .unwrap();


### Write to a branch

Writes go through the branch handle and stay there — the `main` handle keeps
reporting its original row count. Listing branches returns a mapping of each
branch name to its metadata, including the version it was forked from.

\# Writes land on the branch handle only; main is left untouched.
branch.add(\[\{"id": 4, "author": "Lancelot", "quote": "For the realm!"}])
print(branch.count\_rows())  # 4 rows on the branch
print(table.count\_rows())  # 3 rows; main is unaffected

\# List every branch, each mapped to its metadata (including its fork point).
print(table.branches.list())


// Writes land on the branch handle only; main is left untouched.
await branch.add(\[\{ id: 4, author: "Lancelot", quote: "For the realm!" }]);
console.log(await branch.countRows()); // 4 rows on the branch
console.log(await table.countRows()); // 3 rows; main is unaffected

// List every branch, each mapped to its metadata (including its fork point).
console.log(await branches.list());


// Writes land on the branch handle only; main is left untouched.
branch
&#x20;   .add(make\_quotes\_reader(vec!\[(4, "Lancelot", "For the realm!")]))
&#x20;   .execute()
&#x20;   .await
&#x20;   .unwrap();
println!("Branch rows: \{}", branch.count\_rows(None).await.unwrap()); // 4
println!("Main rows: \{}", branches\_table.count\_rows(None).await.unwrap()); // 3

// List every branch, each mapped to its metadata (including its fork point).
println!("Branches: \{:?}", branches\_table.list\_branches().await.unwrap());


### Reopen a branch

A branch outlives the handle that created it. Reopen it later by name — either
from an existing table handle or straight from the connection when you open the
table. Both routes give you a writable handle tracking the branch's latest state.

\# Reopen an existing branch by name from the table handle...
checked\_out = table.branches.checkout("exp")
\# ...or open it directly from the database connection.
branch\_handle = db.open\_table("quotes\_branches\_example", branch="exp")
print(checked\_out.count\_rows(), branch\_handle.count\_rows())  # both 4


// Reopen an existing branch by name from the table handle...
const checkedOut = await branches.checkout("exp");
// ...or open it directly from the database connection.
const branchHandle = await db.openTable(
&#x20; "quotes\_branches\_example",
&#x20; undefined,
&#x20; \{ branch: "exp" },
);
console.log(await checkedOut.countRows(), await branchHandle.countRows()); // both 4


// Reopen an existing branch by name from the table handle...
let checked\_out = branches\_table.checkout\_branch("exp", None).await.unwrap();
// ...or open it directly via the connection's builder.
let opened = db
&#x20;   .open\_table("quotes\_branches\_example")
&#x20;   .branch("exp")
&#x20;   .execute()
&#x20;   .await
&#x20;   .unwrap();
println!(
&#x20;   "Reopened rows: \{}, \{}",
&#x20;   checked\_out.count\_rows(None).await.unwrap(),
&#x20;   opened.count\_rows(None).await.unwrap()
); // both 4


### Delete a branch

Deleting a branch removes it and its branch-local history; `main` is untouched.
Before deleting a branch, make sure you've retained any results you need — see
[Apply branch-tested changes to `main`](#apply-branch-tested-changes-to-main)
below.

\# Delete the branch and its branch-local history. Data on main is safe.
table.branches.delete("exp")


// Delete the branch and its branch-local history. Data on main is safe.
await branches.delete("exp");


// Delete the branch and its branch-local history. Data on main is safe.
branches\_table.delete\_branch("exp").await.unwrap();


## Apply branch-tested changes to `main`

> [!WARNING]
>
> A branch has its own writable history. Outside of the [diff and merge
> APIs](#compare-and-merge-a-branch-into-main) — which are available on
> LanceDB Enterprise and promote added columns only — LanceDB does not reconcile
> one branch's history with another or detect conflicts between them. To carry
> other accepted work forward, rerun the validated operation against `main` or
> explicitly write selected results to it.

How you apply a validated change depends on the type of work:

* **Added columns (Enterprise):** review the branch with `diff`, then promote
  the new columns onto `main` with `merge`. See
  [Compare and merge a branch into `main`](#compare-and-merge-a-branch-into-main).
* **Backfill or transformation:** rerun the validated job against `main`.
* **Schema change:** apply the same reviewed schema operation to `main`.
* **Index change:** build the index on `main` using the configuration validated
  on the branch.
* **Selected row results:** upsert those rows into `main` using a stable unique
  key.

### Upsert selected branch rows into `main`

If the result you want to retain is a set of inserted or updated rows, use
[`merge_insert`](https://docs.lancedb.com/tables/update#merge-incoming-rows-by-key) to write them to
`main`. Despite its name, `merge_insert` is a row-ingestion operation: it
matches incoming rows by key and does not merge branch histories.

Read the rows you want from the reviewed branch, then upsert them into `main` on
your key column — `id` in this example. Here, `candidate` is the branch handle:

\# This is a row-level upsert, not a merge of branch histories.
\# \`merge\_insert\` updates matching rows and inserts new rows using a stable
\# unique key. Filter the branch read if you only want to apply some results.
rows\_to\_apply = candidate.to\_arrow()
(
&#x20;   table.merge\_insert("id")
&#x20;   .when\_matched\_update\_all()  # update rows that already exist on main
&#x20;   .when\_not\_matched\_insert\_all()  # insert rows that are new on the branch
&#x20;   .execute(rows\_to\_apply)
)


// This is a row-level upsert, not a merge of branch histories.
// \`mergeInsert\` updates matching rows and inserts new rows using a stable
// unique key. Filter the branch read if you only want to apply some results.
const rowsToApply = await candidate.toArrow();
await table
&#x20; .mergeInsert("id")
&#x20; .whenMatchedUpdateAll() // update rows that already exist on main
&#x20; .whenNotMatchedInsertAll() // insert rows that are new on the branch
&#x20; .execute(rowsToApply);


// This is a row-level upsert, not a merge of branch histories.
// \`merge\_insert\` updates matching rows and inserts new rows using a stable
// unique key. Filter the branch read if you only want to apply some results.
let schema = candidate.schema().await.unwrap();
let batches = candidate
&#x20;   .query()
&#x20;   .execute()
&#x20;   .await
&#x20;   .unwrap()
&#x20;   .try\_collect::\<Vec\<\_>>()
&#x20;   .await
&#x20;   .unwrap();
let rows\_to\_apply = RecordBatchIterator::new(batches.into\_iter().map(Ok), schema);

let mut merge = branches\_table.merge\_insert(&\["id"]);
merge
&#x20;   .when\_matched\_update\_all(None) // update rows that already exist on main
&#x20;   .when\_not\_matched\_insert\_all(); // insert rows that are new on the branch
merge.execute(Box::new(rows\_to\_apply)).await.unwrap();


This operation transfers only the inserted or updated rows in its input. It does
not transfer branch history, schema changes, indexes, or branch-local deletions,
and it does not determine which rows changed after the branch was created.

Reapplying an identical payload is idempotent on the key, but the operation is
not conflict-aware. If `main` has diverged, incoming branch rows can overwrite
newer values with the same key. Read and upsert the whole branch only when that
overwrite is intentional; otherwise, filter the branch read to the rows you
intend to apply.

## Compare and merge a branch into `main`

Enterprise

On LanceDB Enterprise, branches expose two review-and-land calls that let you
inspect what a branch has changed relative to `main` and then promote its new
columns onto `main` in place — without reissuing the branch's writes.

> [!NOTE]
>
> `diff` and `merge` are available on Enterprise (remote) tables only. On local
> tables both calls raise `NotSupported`. `merge` currently promotes added
> columns; use the [upsert](#upsert-selected-branch-rows-into-main) or rerun
> patterns above for row and index changes.

### Diff a branch

`diff` reads the branch and `main`, and returns a summary of what has changed:
which columns were added, removed, or altered; which indexes were added or
removed; row-count deltas; and — most importantly — a list of merge blockers
explaining why the branch cannot currently be merged, if any.

```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
diff = table.branches.diff("exp")

print(diff["addedColumns"])       # columns the branch introduced
print(diff["mergeable"])          # True when there are no blockers
print(diff["mergeBlockers"])      # list of {"code", "message"} entries
```

```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
const diff = await table.branches.diff("exp");

console.log(diff.addedColumns);   // columns the branch introduced
console.log(diff.mergeable);      // true when there are no blockers
console.log(diff.mergeBlockers);  // array of { code, message } entries
```

Common merge blocker codes include `BaseMoved` (the branch's parent no longer
matches `main`'s latest), `RowsChanged`, `ColumnRemoved`, `ColumnChanged`,
`NoMergeableChanges`, `NoColumnChanges`, `InputColumnDependency`, and
`ParentNotMain`. Newer server codes surface as `Unknown` so older clients
keep working.

### Merge a branch

`merge` promotes a branch's added columns onto `main`. It is a review-and-land
operation: the server re-evaluates the diff at request time, and either lands
the promotion or rejects it with the same blockers `diff` would report. A
rejected merge is not an exception — it resolves with `status="rejected"` so
you can inspect the blockers and decide what to do next.

Set `dry_run=True` (Python) or `dryRun: true` (TypeScript) to preview the
merge without landing it. The result includes a `preview.promoted_columns`
list showing which columns the merge would (or did) promote.

```python Python icon="python" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
# Preview first — this does not modify main.
preview = table.branches.merge("exp", dry_run=True)
print(preview["status"])                   # "ready" | "rejected" | ...
print(preview["preview"]["promotedColumns"])

# Land the merge.
result = table.branches.merge("exp")
if result["status"] == "merged":
    print("landed at main version", result["mainVersionAfter"])
elif result["status"] == "rejected":
    for blocker in result["diff"]["mergeBlockers"]:
        print(blocker["code"], blocker["message"])
```

```typescript TypeScript icon="square-js" theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
// Preview first — this does not modify main.
const preview = await table.branches.merge("exp", true);
console.log(preview.status);               // "ready" | "rejected" | ...
console.log(preview.preview.promotedColumns);

// Land the merge.
const result = await table.branches.merge("exp");
if (result.status === "merged") {
  console.log("landed at main version", result.mainVersionAfter);
} else if (result.status === "rejected") {
  for (const blocker of result.diff.mergeBlockers) {
    console.log(blocker.code, blocker.message);
  }
}
```

Possible `status` values are `ready` (returned by `dry_run` when the merge
would land), `merged` (a real merge that landed), `rejected` (server declined;
see `diff.mergeBlockers`), `notImplemented`, and `unknown` for forward
compatibility. Merge requests are not retried on rejection — the response
carries everything you need to decide next steps.

## Build indexes on a branch

One of the most useful things a branch buys you is a safe place to build and
validate an index without affecting what's in production on the `main` branch.
Fork a branch, create your vector (ANN) and full-text search (FTS)
indexes on it, and check recall and latency. Once you have selected a
configuration, build the corresponding index on `main` through your normal
deployment workflow. Because the indexes live on the branch, queries against
`main` never see a half-built index and are never slowed down by the branch's
build.

This pattern is especially valuable on Enterprise
deployments, where `main` is typically serving production traffic while you tune
an index configuration on the side.

\# Build and validate indexes on a branch before using the configuration on
\# main.
dev = products.branches.create("index-dev")

\# A vector (ANN) index and a full-text search index, both branch-scoped.
dev.create\_index(
&#x20;   "vector",
&#x20;   config=IvfPq(distance\_type="cosine", num\_partitions=1, num\_sub\_vectors=2),
)
dev.create\_index("text", config=FTS())

\# Both indexes live only on the branch; main still has none.
print(\[ix.name for ix in dev.list\_indices()])  # branch: two indexes
print(\[ix.name for ix in products.list\_indices()])  # main: \[] (untouched)


// Build and validate indexes on a branch before using the configuration on
// main.
const dev = await productBranches.create("index-dev");

// A vector (ANN) index and a full-text search index, both branch-scoped.
await dev.createIndex("vector", \{
&#x20; config: lancedb.Index.ivfPq(\{
&#x20;   distanceType: "cosine",
&#x20;   numPartitions: 1,
&#x20;   numSubVectors: 2,
&#x20; }),
});
await dev.createIndex("text", \{ config: lancedb.Index.fts() });

// Both indexes live only on the branch; main still has none.
console.log((await dev.listIndices()).map((ix) => ix.name)); // branch: two indexes
console.log((await products.listIndices()).map((ix) => ix.name)); // main: \[] (untouched)


use lancedb::index::scalar::FtsIndexBuilder;
use lancedb::index::Index;

// Build and validate indexes on a branch before using the configuration on
// main.
let dev = products
&#x20;   .create\_branch("index-dev", Ref::Version(None, None))
&#x20;   .await
&#x20;   .unwrap();

// A vector (ANN) index and a full-text search index, both branch-scoped.
dev.create\_index(&\["vector"], Index::Auto)
&#x20;   .execute()
&#x20;   .await
&#x20;   .unwrap();
dev.create\_index(&\["text"], Index::FTS(FtsIndexBuilder::default()))
&#x20;   .execute()
&#x20;   .await
&#x20;   .unwrap();

// Both indexes live only on the branch; main still has none.
println!("Branch indexes: \{}", dev.list\_indices().await.unwrap().len()); // 2
println!("Main indexes: \{}", products.list\_indices().await.unwrap().len()); // 0


Schema changes such as adding, altering, or dropping columns are branch-scoped in
the same way, so you can stage and review a larger reshaping of a table before
applying the same schema operations to `main`.

## Branches vs. tags vs. versions

Now that you're familiar with branches, you can see how they complement the other ways LanceDB
give you to work with table history. Choose these approaches based on whether you need to
*label*, *read*, or *write* data at a point in history:

| Feature | Writable? | Purpose |
| - | - | - |
| **[Branch](#work-with-branches)** | ✅ Yes | Write on top of a point in history without touching `main`. |
| **[Tag](https://docs.lancedb.com/tables/versioning.md#tag-based-versioning)** | ❌ No | Attach a human-readable label to an existing version; protects it from cleanup. |
| **[`checkout(version)`](https://docs.lancedb.com/tables/versioning#rollback-to-previous-versions)** | ❌ No | Read a historical version of `main` without forking. Read-only until you `restore`. |

> [!NOTE]
>
> For linear version history — creating versions, listing them, rolling back, and
> tagging — see the [Versioning and Reproducibility](https://docs.lancedb.com/tables/versioning.md) guide.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.