Array integer[]: how to get all distinct values in a table and count them?

You can use UNNEST.

select unnest(ports) as port, count(*) from foo group by port;

Using more than one UNNEST in the same query (or the same select list, anyway) is confusing and is probably best avoided.


It's cleaner to use set returning functions in the FROM clause where possible. The SQL standard does not allow them in the SELECT list. And it's almost always possible since we have LATERAL joins.

SELECT port, count(*) AS ct
FROM   tbl t, unnest(t.ports) AS port  -- implicit LATERAL join
GROUP  BY port;
  • What is the difference between LATERAL and a subquery in PostgreSQL?

But I have to concede that the "quick-and-dirty" variant @Jeff provided is typically faster.