---
title: lag analytic window function
description: Learn the syntax of the lag function of the SQL language in Databricks SQL and Databricks Runtime.
canonical_url: https://docs.databricks.com/aws/en/sql/language-manual/functions/lag
---

# `lag` analytic window function

**Applies to:** ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks SQL ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks Runtime

Returns the value of `expr` from a preceding row within the partition.

## Syntax

```
lag( expr [, offset [, default] ] ) [ IGNORE NULLS | RESPECT NULLS ] OVER clause
```

## Arguments

* `expr`: An expression of any type.
* `offset`: An optional `INTEGER` literal specifying the offset.
* `default`: An expression of the same type as `expr`.
* `IGNORE NULLS` or `RESPECT NULLS`: When `IGNORE NULLS` is specified, any `expr` value that is `NULL` is ignored. The default is `RESPECT NULLS`.
* [OVER clause](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-window-functions.md): The clause describing the windowing. See: [Window functions](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-window-functions.md).

## Returns

The result type matches `expr`.

If `offset` is positive the value originates from the row preceding the current row by `offset` specified the ORDER BY in the OVER clause.
An offset of 0 uses the current row's value.
A negative offset uses the value from a row following the current row.
If you do not specify `offset` it defaults to 1, the immediately preceding row.

If there is no row at the specified offset within the partition, the specified `default` is used.
The `default` default is `NULL`.
You must provide an [ORDER BY clause](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-qry-select-orderby.md).

This function is a synonym to `lead(expr, -offset, default)`.

## Examples

```sql
> SELECT a, b, lag(b) OVER (PARTITION BY a ORDER BY b)
    FROM VALUES ('A1', 2), ('A1', 1), ('A2', 3), ('A1', 1) tab(a, b);
 A1 1   NULL
 A1 1   1
 A1 2   1
 A2 3   NULL
```

## Related functions

* [`lead` analytic window function](https://docs.databricks.com/aws/en/sql/language-manual/functions/lead.md)
* [`last` aggregate function](https://docs.databricks.com/aws/en/sql/language-manual/functions/last.md)
* [`last_value` aggregate function](https://docs.databricks.com/aws/en/sql/language-manual/functions/last_value.md)
* [`first_value` aggregate function](https://docs.databricks.com/aws/en/sql/language-manual/functions/first_value.md)
* [Window functions](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-window-functions.md)
