Postgres - 如何检查空数组

Ror*_*ory 56 sql arrays postgresql

我正在使用Postgres,我正在尝试编写这样的查询:

select count(*) from table where datasets = ARRAY[]
Run Code Online (Sandbox Code Playgroud)

即我想知道有多少行有某个列的空数组,但postgres不喜欢这样:

select count(*) from super_eds where datasets = ARRAY[];
ERROR:  syntax error at or near "]"
LINE 1: select count(*) from super_eds where datasets = ARRAY[];
                                                             ^
Run Code Online (Sandbox Code Playgroud)

Tom*_*m H 81

语法应该是:

SELECT
     COUNT(*)
FROM
     table
WHERE
     datasets = '{}'
Run Code Online (Sandbox Code Playgroud)

您可以使用引号和花括号来显示数组文字.

  • 我正在运行 PostgreSQL 9.6.9,虽然“{}”没有错误也没有结果,但我用“[]”得到了正确的结果。谢谢! (3认同)

小智 16

您可以使用array_upper和array_lower函数在空数组上返回null的事实,因此您可以:

select count(*) from table where array_upper(datasets, 1) is null;
Run Code Online (Sandbox Code Playgroud)


Ale*_*hin 7

如果你像我一样在 2020 年发现这个问题,正确答案是

select count(*) from table where cardinality(datasets) = 0
Run Code Online (Sandbox Code Playgroud)

cardinality 在 PostgreSQL 9.4 中添加,即 ~2015

https://www.postgresql.org/docs/9.4/functions-array.html


Wor*_*Bee 5

解决方案查询:
select id, name, employee_id from table where array_column = ARRAY[NULL]::array_datatype;
Run Code Online (Sandbox Code Playgroud)
例子:

表_雇员:

id (int)| name (character varying) | (employee_id) (uuid[])
1       | john doe                 | {4f1fabcd-aaaa-bbbb-cccc-f701cebfabcd, 2345a3e3-xxxx-yyyy-zzzz-f69d6e2edddd }
2       | jane doe                 | {NULL}


select id, name, employee_id from tab_emp where employee_id = ARRAY[NULL]::uuid[];

    -------
2       | jane doe                 | {NULL}
Run Code Online (Sandbox Code Playgroud)