0

Is there a way to use position or another function to find strings in a field but not have it be part of another word? For example if I am looking for the word "bench" with position I would do something like this

 POSITION('bench' IN products)

The products column would look something like this

 **Products**
 tool bench
 benchpress
 park bench
 benchmark
 bench heater
 utility bench tool

I only want to match the rows where bench is NOT part of another word (don't want to match benchpress or benchmark). Thank you

2
  • Trim the column to avoid before and after spaces . then write a case if there is a space then only check for existence (charindex function) else ignore. Commented May 13, 2020 at 6:56
  • Please use CTE (with clause) for next time to make responders concentrate on answer rather than formatting sample input. Thanks. Commented May 13, 2020 at 7:40

2 Answers 2

2

Use \y regex expression (word boundary matcher):

with t(word) as (values
  ('tool bench'),
  ('benchpress'),
  ('park bench'),
  ('benchmark'),
  ('bench heater'),
  ('utility bench tool')
)
select *
from t
where word ~ '\ybench\y'

Dbfiddle here.

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

Comments

0

Using the with clause from Tomáš Záluský you can simple use a like condition searching for is there a space before and after it, is there a space after it or is there a space before

with t(word) as (values
  ('tool bench'),
  ('benchpress'),
  ('park bench'),
  ('benchmark'),
  ('bench heater'),
  ('utility bench tool')
)
select *
from t
where word  like '% bench %' or word like 'bench %'  or word like  '% bench'

or you can split your string to an array, using space as delimiter and look, if there is a fitting element.

 with t(word) as (values
      ('tool bench'),
      ('benchpress'),
      ('park bench'),
      ('benchmark'),
      ('bench heater'),
      ('utility bench tool')
    )
    select * from t 
where string_to_array(word, ' ') @> array[ 'bench' ]

or you also can use postgres and its textsearch

with t(word) as (values
  ('tool bench'),
  ('benchpress'),
  ('park bench'),
  ('benchmark'),
  ('bench heater'),
  ('utility bench tool')
)
SELECT 
* from t 
where to_tsvector('english', word) @@ to_tsquery('english', 'bench')

So choose the right for your task, which fits best and is the fastest.

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.