85

I'm using Postgres and I'm trying to write a query like this:

select count(*) from table where datasets = ARRAY[]

i.e. I want to know how many rows have an empty array for a certain column, but postgres doesn't like that:

select count(*) from super_eds where datasets = ARRAY[];
ERROR:  syntax error at or near "]"
LINE 1: select count(*) from super_eds where datasets = ARRAY[];
                                                             ^
1
  • ... if datasets=NULL represents ARRAY[], the answers are OK... About about "ARRAY[]", it is a syntax error (!): as depesz answered, an empty array also need datatype, Rory's SQL script need correction, is "ARRAY[]::integer". Commented May 12, 2012 at 23:23

5 Answers 5

118

The syntax should be:

SELECT
     COUNT(*)
FROM
     table
WHERE
     datasets = '{}'

You use quotes plus curly braces to show array literals.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm running PostgreSQL 9.6.9 and while there's no error and no results with '{}', I get the correct results with '[]'. Thanks!
27

If you find this question in 2020, like I did, the correct answer is

select count(*) from table where cardinality(datasets) = 0

cardinality was added in PostgreSQL 9.4, which is ~2015

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

1 Comment

This is the answer. To be clear, cardinality "returns the total number of elements in the array, or 0 if the array is empty", which is what you would expect of array_length, but the later returns NULL when length is zero.
21

You can use the fact that array_upper and array_lower functions, on empty arrays return null , so you can:

select count(*) from table where array_upper(datasets, 1) is null;

3 Comments

... ok if datasets=NULL represents ARRAY[], but and about "ARRAY[]", it is a syntax error (!). How to create a empty array??
it's error only because it can't tell what datatype it's array off. add cast: select ARRAY[]::int4[];
Thank you, I don't understand why the top answer doesn't work for me. But your answer worked perfectly.
5
Solution Query:
select id, name, employee_id from table where array_column = ARRAY[NULL]::array_datatype;
Example:

table_emp:

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}

Comments

1
SELECT  COUNT(*)
FROM    table
WHERE   datasets = ARRAY(SELECT 1 WHERE FALSE)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.