Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LIKE in SQL with multiple search terms

I'm doing a basic SQL course and learning the basics currently and having issue with filtering:

Task: list all the rows from TableName where the columnName field content does not contain any of the following words: 'stack' or 'overflow' or 'exampleword'.

SELECT columnName 
FROM TableName 
WHERE columnName NOT LIKE '%stack%' 

-> I get it to work properly with just a single value, but when I try adding more words as values it no longer works ->

SELECT columnName 
FROM TableName 
WHERE columnName NOT LIKE '%stack%' OR columnName NOT LIKE '%overflow%'  

What's the correct syntax for having multiple search terms?

Apparently I'm also not supposed to be using CONTAINS here or it would've been too easy.

like image 512
Prestige Avatar asked Feb 19 '20 21:02

Prestige


1 Answers

You want AND, not OR:

SELECT columnName 
FROM TableName 
WHERE columnName NOT LIKE '%stack%' AND columnName NOT LIKE '%overflow%'

You can expand the WHERE clause with more conditions as needed.

Side note: if you know in advance in which sequence the words appear in the string, you can also do:

SELECT columnName 
FROM TableName 
WHERE columnName NOT LIKE '%stack%overflow%'
like image 118
GMB Avatar answered Oct 11 '22 07:10

GMB