SQL select string that doesn't contain Y but contains X

Katzumi picture Katzumi · Oct 5, 2011 · Viewed 39k times · Source

I'm attempting to select all of the instances where this database field has a string but does not contain a specific value.

Example: I'm trying to select every instance of "red chair" where "red chair" is not proceeded by "big". If I were to run that query in the following table, I'd only get the row with the ID of 2 back:

+----------+--------------+---------+
| ID       |        content         | 
+----------+------------------------+
| 1        | The big red chair      |
| 2        | I have a red chair     |
| 3        | I have a big chair     |
+----------+------------------------+

Thanks in advance!

Answer

kand picture kand · Oct 5, 2011

You can use:

LIKE '%red chair%' AND NOT LIKE '%big%'

edit: Fixed LIKE matching strings