Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Columns Where One is Similar to Part of Another

Tags:

sql

sql-server

I'm trying to write a Select statement where I can see if one column is like part of another.

tblNames  ID    FullName                   FirstName 1     Mr. John Doe, CEO          John 2     Mr. Jake Doe, Exec        Jake 3     Mrs. Betty Smith, Chair     Jill 

The query should return:

3 | Mrs.Betty Smith, Chair | Jill 

However mine just returns every row in the table:

SELECT ID, FullName, FirstName FROM tblNames WHERE '%' + FirstName + '%' not like Fullname 

Any ideas?

like image 691
craigmj Avatar asked Jan 15 '11 15:01

craigmj


People also ask

How do I use like between two columns in SQL?

The SQL LIKE OperatorThe LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters.

How do I compare two columns and differences in SQL?

Here's the generic SQL query to two compare columns (column1, column2) in a table (table1). mysql> select * from table1 where column1 not in (select column2 from table1); In the above query, update table1, column1 and column2 as per your requirement.

Can we compare two columns in where clause SQL?

Answer. Yes, within a WHERE clause you can compare the values of two columns. When comparing two columns in a WHERE clause, for each row in the database, it will check the value of each column and compare them.


2 Answers

Reverse the where, to something like this:

Fullname not like '%' + FirstName + '%'  
like image 180
jzd Avatar answered Sep 21 '22 19:09

jzd


Try this:

SELECT * FROM tblNames WHERE  ISNULL( CHARINDEX (FirstName , FullName),0) = 0 

The CHARINDEX will be faster (more performant) than a LIKE clause, as it doesn't have to take wildcards into account. The sample data above with small numbers of rows won't show a performance benefit, but when in the millions of rows, CHARINDEX would perform better.

like image 31
p.campbell Avatar answered Sep 17 '22 19:09

p.campbell