1

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?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Mostafa Jamareh
  • 1,389
  • 4
  • 22
  • 54

2 Answers2

2

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.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
2

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:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228