Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL reverse LIKE

I have a table holding a list of countries. Say one of these countries is 'Macedonia'

What SQL query would return the 'Macedonia' record if a search is made for 'Republic of Macedonia'?

I believe that in linq it would be something like

var countryToSearch = "Republic of Macedonia";

var result =  from c in Countries
              where countryToSearch.Contains(c.cName) 
              select c;

Now what would the SQL equivalent for the query above be?

Had it been the other way round (i.e. the database has the long version of the country name stored) the below query should work:

Select * from country
where country.Name LIKE (*Macedonia*)

but I do not see how I can reverse it.

Side note: the country names in the table will always be the short version of country names

like image 667
jaja Avatar asked May 11 '12 10:05

jaja


People also ask

What is the opposite of like in SQL?

The NOT LIKE operator in SQL is used on a column which is of type varchar . Usually, it is used with % which is used to represent any string value, including the null character \0 .

What is the opposite of like in MySQL?

In MySQL, you can use NOT LIKE to perform a negation of the LIKE operator. In other words, NOT LIKE returns the opposite result to LIKE .

How do you reverse data in SQL?

SQL Server REVERSE() Function The REVERSE() function reverses a string and returns the result.

What does like %% mean in SQL?

The 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. The underscore sign (_) represents one, single character.


3 Answers

Just reverse the operator (and fix the syntax)

Select * from country
where 'Republic of Macedonia' LIKE CONCAT('%',country.Name,'%')
like image 137
Eugen Rieck Avatar answered Oct 02 '22 20:10

Eugen Rieck


You can use CHARINDEX for this.

Select * from country
where CHARINDEX(country.Name, 'Republic of Macedonia') > 0
like image 21
Oded Avatar answered Oct 02 '22 19:10

Oded


For SQLite, a substring (mysubstring column) in a table (mytable) can be compared against an arbitrary larger test string:

select * from mytable where instr('Somewhere substring is here', mytable.mySubstring) > 0

like image 28
Mark Warburton Avatar answered Oct 02 '22 19:10

Mark Warburton