sql like – How to use like

Posted: November 13, 2008 in sql

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,

Comments
  1. Ujjaval says:

    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 says:

    yep, it is ok.

Leave a comment