ClickHouse/docs/en/sql-reference/aggregate-functions/reference/first_value.md

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

81 lines
1.8 KiB
Markdown
Raw Normal View History

2023-02-16 08:58:46 +00:00
---
slug: /en/sql-reference/aggregate-functions/reference/first_value
sidebar_position: 7
---
# first_value
Selects the first encountered value, similar to `any`, but could accept NULL.
2023-06-04 20:38:38 +00:00
Mostly it should be used with [Window Functions](../../window-functions/index.md).
2023-06-04 20:31:12 +00:00
Without Window Functions the result will be random if the source stream is not ordered.
2023-02-16 08:58:46 +00:00
## examples
2023-04-19 11:22:36 +00:00
```sql
2023-06-04 20:31:12 +00:00
CREATE TABLE test_data
(
a Int64,
b Nullable(Int64)
)
ENGINE = Memory;
2023-06-04 20:34:46 +00:00
INSERT INTO test_data (a, b) Values (1,null), (2,3), (4, 5), (6,null);
2023-02-16 08:58:46 +00:00
```
### example1
The NULL value is ignored at default.
```sql
2023-06-04 20:31:12 +00:00
select first_value(b) from test_data;
2023-02-16 08:58:46 +00:00
```
```text
┌─first_value_ignore_nulls(b)─┐
│ 3 │
└─────────────────────────────┘
2023-02-16 08:58:46 +00:00
```
### example2
The NULL value is ignored.
```sql
select first_value(b) ignore nulls from test_data
2023-02-16 08:58:46 +00:00
```
```text
┌─first_value_ignore_nulls(b)─┐
│ 3 │
└─────────────────────────────┘
2023-02-16 08:58:46 +00:00
```
### example3
The NULL value is accepted.
```sql
select first_value(b) respect nulls from test_data
2023-02-16 08:58:46 +00:00
```
```text
┌─first_value_respect_nulls(b)─┐
│ ᴺᵁᴸᴸ │
└──────────────────────────────┘
2023-02-16 08:58:46 +00:00
```
2023-06-04 20:31:12 +00:00
### example4
Stabilized result using the sub-query with `ORDER BY`.
```sql
SELECT
first_value_respect_nulls(b),
first_value(b)
FROM
(
SELECT *
FROM test_data
ORDER BY a ASC
)
```
```text
┌─first_value_respect_nulls(b)─┬─first_value(b)─┐
│ ᴺᵁᴸᴸ │ 3 │
└──────────────────────────────┴────────────────┘
```
2023-02-16 08:58:46 +00:00