0

For example, I'm using SQL to filter out all descriptions containing the fruit 'Plum'. Unfortunately, using this code yields all sorts of irrelevant words (e.g. 'Plump', 'Plumeria') while excluding anything with a comma or full stop right after it (e.g. 'plum,' and 'plum.')

SELECT winery FROM winemag_p1
WHERE description LIKE '%plum%' OR

Is there a better way to do this? Thanks. I'm using SQL Server but curious how to make this work for MySQL and PostgreSQL too

Stu
  • 30,392
  • 6
  • 14
  • 33
yudontfly
  • 21
  • 3

3 Answers3

0

Solution (I wasn't able to try on SQL Server, but it should work):

SELECT winery FROM winemag_p1
WHERE description LIKE '% plum[ \.\,]%'

In MySQL you can use the REGEXP_LIKE command (works on 8.0.19) (docs):

SELECT winery FROM winemag_p1
WHERE REGEXP_LIKE(description, '% plum[ .,]%');
Dale K
  • 25,246
  • 15
  • 42
  • 71
kaffarell
  • 639
  • 5
  • 16
0

Try the following method, using translate* to handle edge-case characters, search for the keyword including spaces and concat spaces to the source:

with plums as (
  select 'this has a plum in it' p union all
    select 'plum crazy' union all
    select 'plume of smoke' union all
    select 'a plump turkey' union all
    select 'I like plums.' union all
    select 'pick a plum, eat a plum' 
)
select * 
from plums
where Concat(' ',Translate(p,',.s','   '), ' ') like '% plum %'

* assuming you're using the latest version of SQL Server, if not will need nested replace()

Stu
  • 30,392
  • 6
  • 14
  • 33
0

Tried with sql server 2014 with this sql:

select * from winemag_p1
 where description like '%plum%'
 and not description like '%plum[a-zA-Z0-9]%'
 and not description like '%[a-zA-Z0-9]plum%'

with table content

a plum
b plumable
c plum.
d plum,blum e aplum
f bplummer

it outputs

a           plum      
c           plum.     
d           plum,blum 
AIMIN PAN
  • 1,563
  • 1
  • 9
  • 13