Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

SQL SELECT WHERE field contains words

I need a selection that would return results like this:

SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3'


Furthermore, I need all outcomes, for example, this incorporates strings with 'word2 word3 word1' or 'word1 word3 word2' or some other mix of the three.

All words should be in the outcome.
by

2 Answers

espadacoder11
Rather slow, but working method to include any of words:

SELECT FROM mytable
WHERE column1 LIKE '%word1%'
OR column1 LIKE '%word2%'
OR column1 LIKE '%word3%'

If you need all words to be present, use this:

SELECT
FROM mytable
WHERE column1 LIKE '%word1%'
AND column1 LIKE '%word2%'
AND column1 LIKE '%word3%'

If you want something faster, you need to look into full text search, and this is very specific for each database type.
RoliMishra
If your SQL supports CHARINDEX, it's a lot easier to use it:

SELECT * FROM MyTable
WHERE CHARINDEX('word1', Column1) > 0
AND CHARINDEX('word2', Column1) > 0
AND CHARINDEX('word3', Column1) > 0


Also, please keep in mind that this and the method in the accepted answer only cover substring matching rather than word matching. So, for example, the string 'word1word2word3' would still match.

Login / Signup to Answer the Question.