Skip to content
Advertisement

How to show only rows where there is no match between strings at all?

I have to compare two columns and be able to extract only rows where there is not even a partial match between strings. For example, I have this table:

Col1 Col2
John Smith John Smith ltd
Pepper Row Whatever Pepper
red Blue

The only row I should be seeing after the filtration is the last one:

Col1 Col2
red Blue

I found an answer here which shows results with partial matches. I tried to modify it to return only 0 matches by using NOT LIKE but it did not work out.

Advertisement

Answer

If you want rows where none of the words overlap, you can use a not exists clause:

select t.*
from t
where not exists (select 1
                  from string_split(t.col1, ' ') s1 join
                       string_split(t.col2, ' ') s2
                       on s1.value = s2.value
                 );

Note: This formulation allows you to return the entire row — that is, other columns that are not included in the comparison.

If you are using an older version of SQL Server that does not support string_split(), I would suggest finding the code for a user-defined function that does the same thing.

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