Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Where" statement : contains a certain substring

I am using MySQL.

I have a car table in my database, and there is a name column in that table.

Suppose the name column of the table contain values:

 +----------+
 |   name   |
 +----------+
 | AAA BB   |
  ----------
 | CC D BB  |
  ----------
 | OO kk BB |
  ----------
 | PP B CC  |
  ----------

I would like to search the table where name column value contains "BB" , What is the SQL command to achieve this ?

I tried :

SELECT * FROM car WHERE name LIKE "BB";

But it does not work.

P.S.

The values in name column are random strings.

Please do not ask me to use IN (...) , because the values in that column is unpredictable.

---------Please close this question--------------

Sorry, I think I asked the question wrongly. Actually I am asking for a word match not a substring.

like image 832
Mellon Avatar asked Nov 16 '11 13:11

Mellon


People also ask

Can I use substring in WHERE clause?

The SUBSTRING SQL function is very useful when you want to make sure that the string values returned from a query will be restricted to a certain length. In the following example, using the 'firstname' column, the last two characters are matched with the word 'on' using the SQL SUBSTRING function in the where clause.

How do you check if a string contains a substring in SQL Server?

Method 1 - Using CHARINDEX() function This function is used to search for a specific word or a substring in an overall string and returns its starting position of match. In case no word is found, then it will return 0 (zero). Let us understand this with examples.

Can we use Charindex in WHERE clause?

It is a concept that should be avoided whenever possible, and certainly shouldn't be a part of a design where high performance is required. It is better to use LIKE if you must search on the occurrence of a character in a where clause. The probability of survival is inversely proportional to the angle of arrival.


1 Answers

You need to include the % operator to select records that contain "BB" in the name field, not only the exact value.

SELECT * FROM car WHERE name LIKE '%BB%';
like image 81
Matteo Alessani Avatar answered Oct 12 '22 06:10

Matteo Alessani