4

I have a table that contains a text field (summary). I recently received a request to query that field for any occurrences of a long list of strings. For example, I'd like to search the "summary" field for any occurrences of these strings:

  • apple
  • banana
  • carrot
  • dog
  • elephant
  • ... x 50 more items
  • zebra

Is there a simple query I can write that would return the IDs of the rows that contain any of these values?

3 Answers 3

12

You could put them in one giant regular expression:

select t.*
from t
where summary similar to '%((apple)|(banana)|(carrot)|(dog)| . . .|(zebra))%';

An alternative, if you want more flexibility and care even less about performances:

with tosearch as (
      select '%apple%' as pattern union all
      . . .
      select '%zebra%'
     )
select t.*
from t join
     tosearch
     on t.summary like tosearch.pattern;
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you -- adding "similar to" to my tool belt!
It is better to use ~ operator instead of similar to for proper regexps, not SQL standard regexps.
is the bracket for each keyword necessary? it should work without bracket also, like select t.* from t where summary similar to '%(apple|banana|carrot|dog| . . .|zebra)%';
Found an updated answers that explains some interesting facts about similar to. Namely that it has to convert to a regex first. In my own testing I saw negligible performance changes, but could be a good resource. dba.stackexchange.com/questions/10694/…
8

The simplest way that comes in my mind is something like this:

SELECT "ID" FROM table WHERE "summary" IN ('apple', 'banana', 'carrot', 'dog', ....)

Try this out.

EDIT AFTER COMMENT: use the similar to operator:

select "ID" from table where upper("summary") similar to upper('%((apple)|(banana)|...|(zebra))%')

3 Comments

I think the OP wants to find the terms in the column text, not that the column text is one of the terms.
Ah I didn't understand well, sorry
how can I add up the option for example apple and banana NOT apple or banana
7

Use regex:

select * from mytable
where summary similar to '%(apple|banana|carrot|dog)%'

See SQLFiddle of this working

Comments

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.