I have a table that has a column city[]
, so I have:
1 city [london]
2 city [london,paris]
How can I count the city london
in my table?
I have a table that has a column city[]
, so I have:
1 city [london]
2 city [london,paris]
How can I count the city london
in my table?
To count all the rows in a PostgreSQL table where a certain value appears anywhere in an array, you use the ANY
function:
SELECT COUNT(*) FROM cities WHERE 'london' = ANY( city );
(This is assuming the table is called cities
).
The predicate 'london' = ANY( city )
means "Any element in the array city
is equal to 'london'
". This select the rows that match "london", and then counts them.
If the table is not trivially small you'll want to have a GIN index on the array column. You'll want to use array operators instead of the = ANY ()
construct to actually use this index:
SELECT count(*) FROM cities WHERE '{london}'::text[] <@ city;
Details: