25

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?

3 Answers 3

28

Use the unnest() function to convert array to set of rows:

SELECT count(distinct id)
FROM (
    SELECT id, unnest(tags) tag
    FROM planet_osm_ways) x
WHERE tag LIKE 'A%'

The count(dictinct id) should count unique entries from planet_osm_ways table, just replace id with 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 with planet_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.

0
4

Here is another way to do it within the WHERE clause:

SELECT COUNT(*)
FROM planet_osm_ways 
WHERE (
  0 < (
    SELECT COUNT(*) 
    FROM unnest(planet_osm_ways) AS planet_osm_way
    WHERE planet_osm_way LIKE 'A%'
  )
);
1
  • This solution is the only one that preserves tags if we need to return it Commented Oct 27, 2020 at 18:12
0

this is how i managed to do it :

select id from products where (exists (select ut from (select unnest(tags) as ut) as tmp1 where ut like '%that%'))

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.