问:如何将 ClickHouse 配置为 return NULL 而不是 0?

Q: How to configure ClickHouse to return NULL instead of 0?

假设我创建了一个没有任何记录的 table:

    create table metric (date Int32) Engine=MergeTree ORDER BY (date);

如果我运行这个查询

    select max(date) from metric;

ClickHouse returns

+-----------+
| max(date) |
+-----------+
|         0 |
+-----------+
1 row in set (0.02 sec)

而不是

+-----------+
| max(date) |
+-----------+
|      NULL |
+-----------+
1 row in set (0.02 sec)

可以将 ClickHouse 配置为 return NULL 而不必像这样编写查询:

select max(toNullable(date)) from metric;

使用设置 aggregate_functions_null_for_empty:

SELECT max(date)
FROM metric
SETTINGS aggregate_functions_null_for_empty = 1

/*
┌─maxOrNull(date)─┐
│            ᴺᵁᴸᴸ │
└─────────────────┘
*/

或考虑使用 OrNull-组合器:

SELECT maxOrNull(date)
FROM metric

/*
┌─maxOrNull(date)─┐
│            ᴺᵁᴸᴸ │
└─────────────────┘
*/