15

How do I count the number of distinct elements in an array object, created by ARRAY_AGG() in PostgresQL? Here's a toy example for discussion purposes:

SELECT ARRAY_AGG (first_name || ' ' || last_name) actors
FROM film

I have tried ARRAY_LENGTH(), LENGTH(), etc., like so:

SELECT ARRAY_LENGTH(a.actors)
FROM (SELECT ARRAY_AGG (first_name || ' ' || last_name) actors
      FROM film) a;

But I get an error:

function array_length(integer[]) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 208

So I tried (2):

SELECT ARRAY_LENGTH( CAST(COALESCE(a.actors, '0') AS integer) )
FROM (SELECT ARRAY_AGG (first_name || ' ' || last_name) actors
      FROM film) a;

but I get the error:

malformed array literal: "0"
  Detail: Array value must start with "{" or dimension information.
  Position: 119
3
  • You could just use a COUNT at the same level as the ARRAY_AGG. Something like: SELECT ARRAY_AGG (first_name || ' ' || last_name) actors, COUNT(*) FROM film
    – jmelesky
    Commented Jul 2, 2019 at 23:15
  • @jmelesky that doesn't work for my actual use case. There are too many other columns that must be grouped by if I use COUNT(*) so the result is just 1 even if there is more than 1 element in the array. Commented Jul 3, 2019 at 0:08
  • Unrelated, but: concat_ws(' ', first_name, last_name) is a bit easier to use and will properly deal with null values and empty strings
    – user330315
    Commented Jul 3, 2019 at 5:13

2 Answers 2

16

the function array_length(anyarray, int) require two elements, array and dimension for example:

Select array_length(array[1,2,3], 1);

Result: 3

7

If you are only dealing with a single dimension array, cardinality() is easier to use:

SELECT cardinality(ARRAY_LENGTH(a.actors))
FROM ( 
  SELECT ARRAY_AGG (first_name || ' ' || last_name) actors
  FROM film
) a;
1
  • This looks great. Did you mean SELECT cardinality(a.actors) instead of SELECT cardinality(ARRAY_LENGTH(a.actors))? (The former worked for me and not the latter.)
    – Jellicle
    Commented Dec 7, 2023 at 0:51

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.