如何在 postgres 中处理 null value/array?
How is a null value/array handled in postgres?
假设我有以下字段和值:
ArrayField
[1,2,3]
[3,4,5]
[null,2,3,4]
null
[]
[null]
postgres 会按原样保存所有这些值吗?或者这些值中的任何一个是否无效或转换为其他值——例如将 null
作为字段值(是否转换为 []
)?
PostgreSQL 不会静默修改您的数组。如果您存储 [NULL]
,它不会变成 []
。您的最后一个示例 ([NULL,]
) 在语法上不正确。
在 Postgres 中,除了最后一个表达式之外的所有表达式都是有效的:'{null,}'
,这会引发错误:
malformed array literal: "{null,}"
还值得注意的是,null
(和未定义的值)和 {}
(空数组)之间存在差异。假设您要写入具有 not null
约束的列,null
将失败,而 {}
将被允许。
-- create the table
create table t (array_field int[])
-- insert values
insert into t values
('{1,2,3}'),
('{3,4,5}'),
('{null,2,3,4}'),
(null),
('{}')
;
-- 5 rows affected
-- won't work
insert into t values ('{null,}');
-- ERROR: malformed array literal: "{null,}"
-- LINE 1: insert into t values ('{null,}')
-- ^
-- DETAIL: Unexpected "}" character.
-- check the results
select array_field, array_length(array_field, 1) from t
array_field | array_length
:----------- | -----------:
{1,2,3} | 3
{3,4,5} | 3
{NULL,2,3,4} | 4
null | null
{} | null
假设我有以下字段和值:
ArrayField
[1,2,3]
[3,4,5]
[null,2,3,4]
null
[]
[null]
postgres 会按原样保存所有这些值吗?或者这些值中的任何一个是否无效或转换为其他值——例如将 null
作为字段值(是否转换为 []
)?
PostgreSQL 不会静默修改您的数组。如果您存储 [NULL]
,它不会变成 []
。您的最后一个示例 ([NULL,]
) 在语法上不正确。
在 Postgres 中,除了最后一个表达式之外的所有表达式都是有效的:'{null,}'
,这会引发错误:
malformed array literal: "{null,}"
还值得注意的是,null
(和未定义的值)和 {}
(空数组)之间存在差异。假设您要写入具有 not null
约束的列,null
将失败,而 {}
将被允许。
-- create the table
create table t (array_field int[])
-- insert values
insert into t values
('{1,2,3}'),
('{3,4,5}'),
('{null,2,3,4}'),
(null),
('{}')
;
-- 5 rows affected
-- won't work
insert into t values ('{null,}');
-- ERROR: malformed array literal: "{null,}"
-- LINE 1: insert into t values ('{null,}')
-- ^
-- DETAIL: Unexpected "}" character.
-- check the results
select array_field, array_length(array_field, 1) from t
array_field | array_length :----------- | -----------: {1,2,3} | 3 {3,4,5} | 3 {NULL,2,3,4} | 4 null | null {} | null