> ## 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.

# Choose how to compute a column

> Choose SQL expressions or Python Functions, use supported signatures and captures, and configure models, dependencies and hardware.

Enterprise only

Use a SQL expression for a value derived from existing columns when SQL can
express the calculation. Use a Python Function for models, media decoding,
external services, or other code that SQL cannot express. Both declare stored
columns that a refresh fills.

For a Function that calls an external service, follow the
[Python Secrets walkthrough](https://docs.lancedb.com/oss/v0-42-0/enterprise/function-secrets.md) to create a
credential, grant access, fill a column, and alter the Secret value.

Use the [Function signature matrix](https://docs.lancedb.com/oss/v0-42-0/curation/create-function.md#signature-types)
before choosing input/output schemas. The Function type grammar is narrower
than a table's Arrow schema: it names scalar primitives, lists, structs, maps
and decimals, and a timestamp or duration declares its unit (plus an optional
timezone for a timestamp) through the SQL spelling or exact Arrow JSON. See
[timestamp and duration values](#declare-timestamp-and-duration-values) and
[map and decimal values](#declare-map-and-decimal-values). Blob v2 can be
top-level or nested in a struct; list/large-list Blob values are output-only on
matching releases, and row-ID fetch helpers do not fetch Blob payloads inside
lists.

For module-level `OUT_TYPE` or other constants, see
[supported global captures](https://docs.lancedb.com/oss/v0-42-0/management/function.md#captures). Scalar literals and
nested tuples can be captured; Arrow schemas/types, mutable containers and
NumPy arrays must be constructed inside the Function body or a class's
`__init__`. Decorator schema arguments are handled separately as the signature.
The improved unsupported-global error is not additional serialization support.

Model placement, query-time initialization and refresh queue behavior are
covered in [Function operations](https://docs.lancedb.com/oss/v0-42-0/enterprise/function-operations.md). Functions
can load models once per instance, but a cached image does not guarantee an
initialized model for the next SQL query. For interactive search, prefer an
[already initialized query-embedding model](https://docs.lancedb.com/oss/v0-42-0/enterprise/function-operations.md#query-embeddings).

## Prefer SQL for expressions over existing columns

Arithmetic, comparisons, casts, and built-in SQL functions do not need a
registered Python Function. SQL computed columns avoid the Python environment
and Function worker overhead. See the available
[SQL functions](https://docs.lancedb.com/oss/v0-42-0/sql/dql/functions.md).

For an existing Enterprise table with an integer `value` column:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
table.add_columns(
    computed={"doubled": "value * 2"},
    auto_refresh_enabled=False,
)
job = table.refresh_column_async("doubled")
job.wait()
```

`computed=` saves the expression and declares an empty column. This example
disables automatic refresh so that the explicit `refresh_column_async` job fills it.
Automatic refresh is enabled by default where the deployment supports it.

To compute existing rows immediately in one call, use an eager SQL transform
instead:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
table.add_columns({"doubled": "value * 2"})
```

These are alternative ways to create the same column; run only one on a given
table. Eager transforms compute existing rows once. A `computed=` declaration
retains the expression for later refreshes. See
[Create a computed column](https://docs.lancedb.com/oss/v0-42-0/feature-engineering/add-computed-column.md) and
[Refresh a column](https://docs.lancedb.com/oss/v0-42-0/feature-engineering/refresh-column.md).

## Declare Function bindings

These declarations apply to ordinary tables. A materialized view's defining
`SELECT` owns its schema; put the Function call in that query, compute it on
the source table first, or create an independent ordinary table. Do not attach
a separate Function binding to the view with `view.table.add_columns(...)`.
See [materialized-view alternatives](https://docs.lancedb.com/oss/v0-42-0/feature-engineering/materialized-views.md#schema-changes).

A Function binding applies one registered Function version to its inputs.
With a Python SDK and Enterprise server that support batch declaration, pass
several applications in one mapping. The table gains every binding in one
schema version. If any application is invalid, the whole declaration fails.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
from lancedb import col

table.add_columns({
    "embedding": embed_text(text=col("text")),
    "category": classify_text(text=col("text")),
})
```

Use separate calls on older releases. Use a separate `computed=` mapping
for SQL-expression columns.

One binding can still produce several output columns: return a named struct
from one Function and pass its application directly to `add_columns` to expand
the fields. See the
[multi-output Function example](https://docs.lancedb.com/oss/v0-42-0/management/function.md#multi). Function columns
start empty and need a refresh, just like SQL computed columns.

## Reuse stored Function results in SQL

> [!NOTE]
>
> Available in the next server release.

When a table column stores a Function's complete result, a SQL call can read
that column for rows with a recorded, current freshness certificate. The call
must use the exact bound Function version, initialization values, and input
columns. Assigned `NULL` results are reused too. Rows with missing or stale
results are computed during the query.

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
SELECT COUNT(slow_function(frame_index)) FROM frames;
SELECT frame_index FROM frames
WHERE slow_function(frame_index) > 790 LIMIT 5;
```

`EXPLAIN` includes `stored_rows` and `computed_rows` for the pinned table
snapshot. For 800 current rows and 10 newly appended rows, these counts are
800 and 10. Filters and limits can reduce the work performed during execution;
the counts describe the snapshot's reuse eligibility. Query-time computation
does not fill the stored column; use a column refresh to persist those results.

Calls with different inputs or initialization values, bindings that store only
selected result fields, Secret-dependent Functions, and Functions with side
effects continue to compute their results. Reuse currently applies to direct
table reads and column projections or aliases; WAL-backed reads retain their
existing execution behavior.

## Preview UDFs with per-row error handling

A UDF error fails its query by default. Submit a distributed job with
`error_policy = 'skip'` to keep successful results and return NULL for each
failing scalar UDF input:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
SUBMIT JOB WITH (error_policy = 'skip') AS
SELECT id, embed_text(text) AS embedding
FROM documents
ORDER BY id;

EXECUTE JOB 'returned-job-id';
```

`SUBMIT JOB` returns a job ID immediately. `EXECUTE JOB 'job-id'` waits for that
job and reads its saved result. To submit and wait in one statement, use:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
EXECUTE JOB WITH (error_policy = 'skip') AS
SELECT COUNT(embed_text(text)) FROM documents;
```

Without an `ON` clause, the job uses the deployment's configured SQL job
compute. CPU or GPU job execution must be enabled for the UDF's compute class.
Named clusters and compute integrations retain their existing placement options
and native CPU query restrictions.

Put the policy before `AS`; it applies to UDF calls in the job's projection,
filters, aggregates, CTEs, and subqueries. NULLs follow normal SQL semantics:
`COUNT(fn(x))` counts successful non-NULL results, and a NULL filter condition
excludes the row. A failing UDTF input produces no output rows. Worker startup,
transport, and other statement-level failures still fail the job.

The default is `error_policy = 'fail'`. Unknown and duplicate job options are
rejected. The policy and UDF versions are saved with the job, so worker
replanning and result retrieval use the submitted execution contract. These
query jobs do not persist skipped-row diagnostics for `SHOW ERRORS`;
materialized view refresh and computed column refresh manage their own error
records.

## Return struct values by field name

A struct output keeps the named-struct pattern: each field declares its own
nullability and the struct column itself is non-nullable. A single value can
also be a nullable scalar; see
[nullable scalar outputs](#nullable-scalar-outputs). See the
[type matrix](https://docs.lancedb.com/oss/v0-42-0/curation/create-function.md#signature-types) and the
[failure-handling workflow](https://docs.lancedb.com/oss/v0-42-0/management/function-failures.md).

For a struct output, return a Python dictionary with exactly the declared field
names. This also applies to structs nested inside structs or lists.
For example, an output declared as
`struct<precision: float64, recall: float64>` accepts:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
def compute_metrics(text: str):
    return {"precision": 0.9, "recall": 0.1}
```

Dictionary values bind by name, so reordering the output fields preserves their
meaning. Positional tuples such as `(0.9, 0.1)` and lists of field-value pairs
are rejected. Convert a named tuple with `_asdict()` or a dataclass instance
with `dataclasses.asdict()` before returning it.

Vectorized Functions can return a sequence of dictionaries, one per input row,
or a typed Arrow array or RecordBatch matching the declared output schema.
Typed Arrow struct scalars are also accepted as row values. `None` is accepted
where the declared output is nullable. Tuples remain supported for list-valued
outputs.

## Declare a nullable scalar output

A scalar output declares its nullability explicitly. Python uses a nullable
annotation such as `-> float | None` or `pa.field("$value", pa.float64(),
nullable=True)`; SQL appends `NULL` to `RETURNS <type>`. A returned `None` then
becomes a computed `NULL` that the refresh assigns, so `SHOW COLUMN STATUS`
reports the row as fresh. A row that has not been refreshed, was deferred
because a required input was null, or was skipped by `error_policy = 'skip'`
stays unassigned. Leaving the declaration out keeps the non-nullable contract,
where a `NULL` return is a row error instead of a value.

## Declare map and decimal values

The Python declaration forms below require the SDK support introduced in
[lancedb/lancedb#5031](https://github.com/lancedb/lancedb/pull/5031).
The SDK revision currently pinned by this server does not include that support;
use the SQL declaration forms until an SDK package containing it is available.

Maps use canonical Arrow map JSON; Python declarations use `entries`, `key`,
and `value` child names, while explicit Arrow schemas may preserve custom child
names. The key must be non-null `utf8`; the value field keeps its declared
nullability. For example, `map<utf8, int64>` in SQL produces a map whose value is
nullable. The SDK preserves the value nullability from `dict[str, T]` and
`dict[str, Optional[T]]`.
`keys_sorted=true` and Blob v2 nested inside a map are not supported.

Decimals require an explicit precision and scale. SQL accepts
`decimal128(precision, scale)` and `decimal256(precision, scale)` (and
`decimal(...)` as a decimal128 spelling); the SDK uses an explicit
`pa.decimal128`/`pa.decimal256` schema or an `Annotated[Decimal, ...]` type.
Canonical Arrow JSON encodes the pair as `length = precision * 1000 + scale`,
including negative scales. A bare `Decimal` annotation is not a valid
declaration.

## Declare timestamp and duration values

A timestamp carries a unit and optionally a timezone; a duration carries a
unit. The bare names are the legacy microsecond, no-timezone spellings. SQL
uses the existing Lance precision spelling `timestamp(0|3|6|9)` for seconds,
milliseconds, microseconds, and nanoseconds, and accepts bare `timestamp` and
`duration`:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
CREATE FUNCTION observed(value int64) RETURNS timestamp(9) NULL
LANGUAGE python AS 'def observed(value): return None'
```

The `NULL` modifier makes the returned `None` an assigned value rather than a
row error; see [nullable scalar outputs](#nullable-scalar-outputs).

An explicit timezone, or a duration unit other than microseconds, has no SQL
spelling. Declare it with exact Arrow JSON through the SDK's explicit
`output_schema`/`Annotated` form or a registration request:

```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
pa.timestamp("ns", tz="UTC")  -> {"type":"timestamp:ns:UTC"}
pa.timestamp("s")             -> {"type":"timestamp:s:-"}
pa.timestamp("us")            -> {"type":"timestamp"}
pa.duration("ms")             -> {"type":"duration:ms"}
pa.duration("us")             -> {"type":"duration"}
```

The compound timestamp form always includes the timezone segment, and `-`
means no timezone. The declared unit is part of the type: a nanosecond column
is not coerced to microseconds, and a unit or timezone mismatch is rejected at
binding rather than converted. SQL rejects `timestamp(<precision>, '<tz>')`
and `duration(<unit>)` instead of guessing either parameter.

## Read a field from a Function result in SQL

For a registered Function `ego_activity_label` that returns a struct with an
`activity` field, select that field directly:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
SELECT ego_activity_label(embedding).activity FROM clips;
```

For a Function in a namespace, qualify its name, for example
`models.ego_activity_label(embedding).activity`.

Bracket access and `get_field` also work without a CTE:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
SELECT ego_activity_label(embedding)['activity'] FROM clips;
SELECT get_field(ego_activity_label(embedding), 'activity') FROM clips;
```

Quote field names that contain spaces or require preserved capitalization, for
example `ego_activity_label(embedding)."Activity Label"`.

## Stream a Blob v2 output with `BlobWriter`

Use `BlobWriter` when a Function can produce a large value in chunks. The
LanceDB Python SDK declares the output and a compatible Enterprise server
provides the writer during computed column refresh.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
from lancedb.functions import BlobWriter, function


@function
def render_document(text: str) -> BlobWriter:
    with BlobWriter.open() as output:
        for line in text.splitlines():
            output.write(data=line.encode("utf-8") + b"\n")
    return output
```

Open one writer per value. `write(data=...)` accepts bytes-like data and returns
its accepted byte count. Leaving the context normally seals the value, including
an empty Blob. Leaving it with an exception aborts the write. Return the sealed
writer once, from the same Function invocation.

Use `BlobWriter.field("preview")` in the Function's `output_schema` to mark
an output field within a named result, including a list or large-list item.
A marked field also accepts ordinary `bytes` and accepts `None` when nullable.
A Function with a writer-capable result schema runs through computed column
refresh. Use `REFRESH COLUMN` in SQL to materialize it. An ordinary `bytes`
result declared with `lancedb.blob(...)` can also be used in `SELECT`.

## Read the byte size of a Blob in SQL

Use `BYTE_LENGTH` for binary and Blob values:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
SELECT BYTE_LENGTH(mp4) AS video_bytes FROM clips;
```

Blob values are represented as structs during SQL planning. `LENGTH`,
`OCTET_LENGTH`, and `BIT_LENGTH` do not accept Blob descriptors; use
`BYTE_LENGTH(mp4)`. A descriptor's `mp4.size` field exposes its stored size,
which can be unknown for an external Blob reference. `BYTE_LENGTH` resolves
unknown external sizes for stored Blob columns.

## Allocate multiple GPUs to one Function worker

Use `@function(gpu=True, gpu_class="h100", gpu_count=2)` to allocate two
GPUs together to each Function worker. SQL registration uses
`CREATE FUNCTION ... WITH (gpu = true, gpu_class = 'h100', gpu_count = 2)`.
`gpu_count` defaults to one. Omitting `gpu_class` is equivalent to
`gpu_class="any"`: either accepts any eligible configured pool. Set
`gpu_class="default"` to select the deployment's default pool explicitly.
Omit `gpu` or set `gpu=False` for CPU execution; `gpu_class` and `gpu_count`
require `gpu=True`.

Class names identify operator-configured pools and must be lowercase. For an
`any` request, selection uses configured per-worker limits and stays fixed for
the worker cohort. An `any` Function may share a SQL job with a Function pinned
to a class; the job uses that class and the largest required GPU count.
Configure the model's tensor parallelism separately.

Inspect the deployment with `db.list_gpu_classes()` or `SHOW GPU CLASSES`.
These report the configured model, memory per GPU, and
`max_gpu_count_per_worker`. Limits and available node shapes depend on the
deployment; an unset cap does not imply unlimited hardware. Requests above a
configured cap are rejected. Initialization failures caused by CUDA memory
exhaustion include device memory and advice on GPU sizing when available.

The refresh `total_gpu_count` is an aggregate budget across workers. It must be at
least the Function's per-worker count. For example, a budget of four GPUs can
fit two workers that each require two. Adaptive sizing preserves the declared
GPU count while adjusting CPU, memory, and the number of workers.

## Choose video decoding for the access pattern

GPU decoding is not always faster. Choose the decoder for the frames the
Function actually reads:

| Access pattern | Starting point |
| - | - |
| Sparse frames or keyframes, with repeated seeks | Software decoding; repeated decoder flushes and GPU decoder latency can dominate the work |
| Long sequential decodes, processing many consecutive frames | Benchmark NVDEC against software decoding; sustained work can amortize setup and transfer costs |

Benchmark representative clips with the same codec, resolution, and sampling
pattern as the production workload. Include seeks and transfers in the
measurement. A GPU inference stage can still use software decoding to sample
its input frames.

GPU Functions can use NVIDIA's NVDEC and NVENC driver libraries on deployments
and GPU classes that support video decoding and encoding. `gpu=True` requests
a GPU; it does not select a hardware decoder. Your decoding library must also
support the codec and GPU backend. See
[GPU Function configuration](https://docs.lancedb.com/oss/v0-42-0/curation/create-function.md#gpu).

## Choose FFmpeg dependencies for the decoding library

[PyAV binary wheels bundle FFmpeg](https://pyav.basswood.io/docs/stable/overview/installation.html).
Declare a wheel version in the Function's `pip` dependencies, such as
`pip=["av==18.1.0"]`. Software decoding through that wheel does not require a
system `ffmpeg` installation. Installing PyAV only in the client environment
does not install it on Function workers.

PyAV's bundled libraries do not supply an `ffmpeg` command or the system shared
libraries that another package may load:

| Library or tool | Function dependency |
| - | - |
| PyAV software decoding with a binary wheel | `pip=["av==18.1.0"]` |
| A tool that invokes the `ffmpeg` command | Install the `ffmpeg` system package or a conda package that provides the command |
| A library such as TorchCodec that loads FFmpeg shared libraries | Install a compatible FFmpeg library version through system or conda packages, in addition to the Python package |

With a supporting SDK and Enterprise server, declare Debian packages with
`apt=["ffmpeg"]` on `@function`, or `WITH (apt = 'ffmpeg', ...)` in SQL
[`CREATE FUNCTION`](https://docs.lancedb.com/oss/v0-42-0/sql/ddl/function#create). System packages can accompany
`pip` dependencies. Alternatively, use `conda` and `conda_channels` to provide
FFmpeg and the Python packages in one environment; `pip` and `conda` are mutually
exclusive dependency declarations.

Match the FFmpeg version to the decoding library's requirements. GPU decoding
also needs a decoding library and FFmpeg build with the required hardware
support; installing FFmpeg alone does not enable NVDEC. A PyAV source build,
instead of a binary wheel, needs its own FFmpeg build dependencies.

## Inspect a Function worker's environment

Function workers automatically collect a bounded environment report before
loading your Function or delivering its bound Secrets. Inspect a finished SQL
or refresh job, including a failed job; no probe Function or image rebuild is
needed:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
DESCRIBE JOB '<job_id>';
DESCRIBE JOB '<job_id>' FORMAT JSON;
```

Both SQL formats return one UTF-8 `description` document; TEXT is the default.
With `FORMAT JSON`, parse that column to read the full reports, library paths,
and worker, executor-slot, and Function-version mappings in
`function_environments` when recorded. TEXT renders the same fields as labeled
metadata.

The separate `job.stats()` report and the console's Stats tab group identical
environments under **Function environments**. Differences in GPU hardware,
drivers, libraries, or packages appear as separate environments. Collection
timestamps and Function code versions do not split an otherwise identical
environment. Environment details are not repeated in `SHOW JOB EVENTS`.

Reports remain available after initialization fails. A warm worker's retained
environment is included when it serves another job.

The report includes:

* OS, architecture, Python version, and the immutable Function version.
* Library search directories and up to four matching paths for each of CUDA,
  NVML, NVDEC, NVENC, cuDNN, CUDA runtime, FFmpeg codec, and FFmpeg utility libraries.
* Installed versions of common GPU and video Python packages, read from package
  metadata without importing PyTorch, PyAV, or TorchCodec.
* Availability of `nvidia-smi` and `ldconfig` on the Function's command path.
* NVIDIA driver version, the maximum CUDA API version supported by that driver,
  and CUDA-visible GPU models and total memory, when the driver can be queried.

GPU discovery uses the driver libraries directly, so it can work even when
`nvidia-smi` is absent. It runs in a separate process with a two-second deadline;
a missing driver, tool, or failed query is diagnostic information and does not
fail the Function. The CUDA API version describes driver compatibility, not an
installed toolkit version. Library paths establish file presence, not that the
library and all its dependencies can be loaded. The report uses a bounded set
of common directories; an empty list does not prove a library is absent from
every possible location. It does not dump environment variables or credentials.

The standard Function base is Ubuntu 24.04 with Python and dependencies installed
for each Function. GPU driver interfaces come from the worker's allocated GPUs;
CUDA runtime and cuDNN packages come from the Function's dependencies. FFmpeg is
not installed by default: declare the system or conda packages your decoding
library needs, as described above. Custom images can provide a different base
and additional native libraries. Reports require a server release that supports
these diagnostics; older jobs do not acquire reports retroactively.

## Default execution budgets

`total_cpu_millis`, `total_memory_bytes`, and
`total_gpu_count` supply execution-wide defaults. CPU is in millicores
(1000 = one core), memory is in bytes, and GPU count is a total across workers.
Each resource resolves independently in this order:

1. The refresh's `total_*` value.
2. The column or materialized view's `total_*` value.
3. The registered Function's `total_*` value.
4. The deployment default.

For a materialized view using multiple Functions, the third layer adds each
resource across distinct pinned Function versions. Calling the same version
more than once counts it once. Column and view defaults also apply when the
service schedules a refresh automatically. Integer overflow or a budget that
cannot fit a required worker is rejected.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
@function(
    gpu=True,
    gpu_class="h100",
    gpu_count=2,
    total_cpu_millis=8000,
    total_memory_bytes=16 * 1024**3,
    total_gpu_count=4,
)
def embed(text: str) -> list[float]: ...

version = db.create_function(embed)
table.add_columns(
    {"embedding": version(text=col("text"))},
    total_gpu_count=8,
)
job = table.refresh_column_async("embedding", total_gpu_count=4)
job.wait()

db.create_materialized_view(
    "embeddings", query="SELECT embed(text) AS embedding FROM documents",
    total_cpu_millis=16000,
    total_gpu_count=8,
)
```

`gpu_count=2` still allocates two devices together to every Function worker.
The `total_*` and `total_*` values are ceilings for the whole worker
fleet. CPU and memory can limit the fleet before it reaches its GPU ceiling.


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