Home > sql > sql like – How to use like

sql like – How to use like

Hi Guys,

I was facing one sql related problem,

I have following entries in database table >> field_name, values stored in DB as comma separated.

1) xyz,itoutsourcing,outsourcing,abc
2) outsourcing,xyz
3) xyz,outsourcing
4) outsourcing
5) xyz,abc,itoutsourcing

Observe 1st and 5th  row it contains domains itoutsourcing
If I want to fetch row which contains only outsourcing then how to fetch ?

I tried following query

“select * from table_name where field_name like ‘%outsourcing%’” ;
but this query will fetch all rows because itoutsourcing also have string ‘outsourcing’ in it.

So what can I do now …. I want only first four rows to be fetched, I have tried many combination e.g like ‘%outsourcing’, like ‘outsourcing%’ but no use , No expected results.

Then I have tried best combination

” select * from table_name where  field_name like ‘%,outsourcing,%’ OR field_name like ‘%,outsourcing’ OR field_name like ‘outsourcing,%’ OR field_name like ‘outsourcing’”

It works,

1) %,outsourcing,% – fetched 1st row

2) ‘%,outsourcing – fetched 1st and 3rd row

3) outsourcing,% – fetch 1st and 2nd row

4) outsourcing – fetch 4th row.

If you are saving data as comma separated strings and you are facing same problem that I have faced then use this combination , Definitely It works , If you have better solution than this then please share with me.

Thank you,

Advertisement
Categories: sql
  1. Ujjaval
    November 14, 2008 at 5:09 am | #1

    Hi Prasad.

    Try using this one.

    “SELECT {fields} FROM {table}
    WHERE {field} LIKE ‘outsourcing%’
    OR {field} LIKE ‘%,outsourcing%’”

    I think this should get the exact result you want. You want “outsourcing” not be prefixed by any text. i.e, outsourcing should be the first text or prefixed by comma.

    Try it and reply if anything is wrong….

  2. John tricky
    October 7, 2010 at 12:03 pm | #2

    yep, it is ok.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.