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?

5
  • Do you want to count how many rows contain "london" or how many times "london" appears in one row? Commented Apr 5, 2015 at 7:02
  • thank you @RealSkeptic, i want to now how many times "london" appears in all rows Commented Apr 5, 2015 at 7:04
  • And is it possible that it appears more than once in a single row? Commented Apr 5, 2015 at 7:06
  • no it is not possible Commented Apr 5, 2015 at 7:14
  • And how do you implement this constraint? stackoverflow.com/questions/8016776/… Commented Apr 5, 2015 at 8:16

2 Answers 2

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.

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

Comments

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:

2 Comments

it gives me array value must start with "{" or dimension information
@MostafaJamareh: Sorry, syntax error; fixed. <@ expects an array on both sides.

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.