> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-8c05c8a2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Selects the last encountered value, similar to `anyLast`, but could accept NULL.

# last_value

Selects the last encountered value, similar to `anyLast`, but could accept NULL.
Mostly it should be used with [Window Functions](/reference/functions/window-functions/index).
Without Window Functions the result will be random if the source stream is not ordered.

<h2 id="examples">
  examples
</h2>

```sql theme={null}
CREATE TABLE test_data
(
    a Int64,
    b Nullable(Int64)
)
ENGINE = Memory;

INSERT INTO test_data (a, b) VALUES (1,null), (2,3), (4, 5), (6,null)
```

<h3 id="example1">
  Example 1
</h3>

The NULL value is ignored at default.

```sql theme={null}
SELECT last_value(b) FROM test_data
```

```text theme={null}
┌─last_value_ignore_nulls(b)─┐
│                          5 │
└────────────────────────────┘
```

<h3 id="example2">
  Example 2
</h3>

The NULL value is ignored.

```sql theme={null}
SELECT last_value(b) ignore nulls FROM test_data
```

```text theme={null}
┌─last_value_ignore_nulls(b)─┐
│                          5 │
└────────────────────────────┘
```

<h3 id="example3">
  Example 3
</h3>

The NULL value is accepted.

```sql theme={null}
SELECT last_value(b) respect nulls FROM test_data
```

```text theme={null}
┌─last_value_respect_nulls(b)─┐
│                        ᴺᵁᴸᴸ │
└─────────────────────────────┘
```

<h3 id="example4">
  Example 4
</h3>

Stabilized result using the sub-query with `ORDER BY`.

```sql theme={null}
SELECT
    last_value_respect_nulls(b),
    last_value(b)
FROM
(
    SELECT *
    FROM test_data
    ORDER BY a ASC
)
```

```text theme={null}
┌─last_value_respect_nulls(b)─┬─last_value(b)─┐
│                        ᴺᵁᴸᴸ │             5 │
└─────────────────────────────┴───────────────┘
```
