【问题标题】:How is a null value/array handled in postgres?postgres 中如何处理空值/数组?
【发布时间】:2020-01-15 20:39:36
【问题描述】:

假设我有以下字段和值:

ArrayField
[1,2,3]
[3,4,5]
[null,2,3,4]
null
[]
[null]

postgres 会按原样保存所有这些值。或者这些值中的任何一个是否无效或转换为其他值 - 例如将null 作为字段值(是否转换为[])?

【问题讨论】:

  • jsonbinteger[]?
  • []............
  • null 和一个空数组 [] 是两个不同的东西

标签: sql arrays postgresql sql-null


【解决方案1】:

在 Postgres 中,除了最后一个表达式:'{null,}',您的所有表达式都是有效的,这会引发错误:

格式错误的数组字面量:“{null,}”

还值得注意的是null(和未定义的值)和{}(空数组)之间存在差异。假设您要写入具有not null 约束的列,null 将失败,而{} 将被允许。

Demo on DB Fiddle

-- 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
数组字段 |数组长度 :----------- | ------------: {1,2,3} | 3 {3,4,5} | 3 {NULL,2,3,4} | 4 | {} |

【讨论】:

  • 谢谢,我更新了语法。一个问题——[] 在实际使用中与null 不同的例子是什么(不仅仅是在存储价值方面)?
  • @David542:欢迎。好吧,您可以在我的回答中看到针对不可为空列的插入查询的示例。
【解决方案2】:

PostgreSQL 不会默默地修改你的数组。如果你存储了[NULL],它就不会变成[]。您的最后一个示例 ([NULL,]) 在语法上不正确。

【讨论】:

    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 2015-10-27
    • 2020-12-27
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2010-10-18
    • 2022-08-03
    相关资源
    最近更新 更多