I am querying a database in Postgres using psql. I have used the following query to search a field called tags that has an array of text as it’s data type:
select count(*) from planet_osm_ways where 'highway' = ANY(tags);
I now need to create a query that searches the tags fields for any word starting with the letter ‘A’. I tried the following:
select count(*) from planet_osm_ways where 'A%' LIKE ANY(tags);
This gives me a syntax error. Any suggestions on how to use LIKE with an array of text?
Use the
unnest()function to convert array to set of rows:The
count(dictinct id)should count unique entries fromplanet_osm_waystable, just replaceidwith your primary key’s name.That being said, you should really think about storing tags in a separate table, with many-to-one relationship with
planet_osm_ways, or create a separate table for tags that will have many-to-many relationship withplanet_osm_ways. The way you store tags now makes it impossible to use indexes while searching for tags, which means that each search performs a full table scan.