Skip to content
Advertisement

SQL filter out string that matches condition and with specific exception to pass

Sample data

| data_col            | 
| --------------------| 
| Realdata            |
| Firsttest           | 
| testSecond          | 
| onetesttwo          | 
| exceptiontestunique | 
| legitdata           | 

I wanted to filter out all the data that contains test with the exception of one

My expected return result is:

Realdata
exceptiontestunique
legitdata

I can code this in PHP like this.

if (strpos($data, 'test') === false || $data === 'exceptiontestunique') return $data;

Or in JavaScript like this

if (data.indexOf('test') === -1 || data === 'exceptiontestunique') {
  return data;
}

But I need it in SQL

WHERE data_col NOT LIKE '%test%'
???????

const datas = ['realdata', 'Firsttest', 'testSecond', 'onetesttwo', 'exceptiontestunique', 'legitdata'];

const filtered = datas.filter(data => {
  if (data.indexOf('test') === -1 || data === 'exceptiontestunique') {
    return data;
  }
})

console.log(filtered);

Advertisement

Answer

I can see that in your PHP/Js code you’re defining two condition; any value that have ‘test’ in them but not exceptiontestunique. With a specific condition like that, you can achieve with OR. Example:

SELECT * FROM table1
WHERE (data_col NOT LIKE '%test%' 
            OR data_col='exceptiontestunique');

Demo Fiddle

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement