Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a single SQL (or its variations) function to check not equals for multiple columns at once?

Tags:

sql

Just as I can check if a column does not equal one of the strings given in a set.

SELECT * FROM table1 WHERE column1 NOT IN ('string1','string2','string3');

Is there a single function that I can make sure that multiple columns does not equal a single string? Maybe like this.

SELECT * FROM table1 WHERE EACH(column1,column2,column3) <> 'string1';

Such that it gives the same effect as:

SELECT * FROM table1 WHERE column1 <> 'string1' 
                       AND column2 <> 'string1' 
                       AND column3 <> 'string1';

If not, what's the most concise way to do so?

like image 686
Russell Avatar asked Jan 21 '23 07:01

Russell


1 Answers

I believe you can just reverse the columns and constants in your first example:

SELECT * FROM table1 WHERE 'string1' NOT IN (column1, column2, column3);

This assumes you are using SQL Server.

UPDATE:

A few people have pointed out potential null comparison problems (even though your desired query would have the same potential problem). This could be worked around by using COALESCE in the following way:

SELECT * FROM table1 WHERE 'string1' NOT IN (
     COALESCE(column1,'NA'), 
     COALESCE(column2,'NA'), 
     COALESCE(column3,'NA')
);

You should replace 'NA' with a value that will not match whatever 'string1' is. If you do not allow nulls for columns 1,2 and 3 this is not even an issue.

like image 127
Abe Miessler Avatar answered Jan 30 '23 01:01

Abe Miessler