Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Query to find if a string contains part of the value in Column

I am trying to write a Query to find if a string contains part of the value in Column (Not to confuse with the query to find if a column contains part of a string).

Say for example I have a column in a table with values

ABC,XYZ

If I give search string

ABCDEFG

then I want the row with ABC to be displayed.

If my search string is XYZDSDS then the row with value XYZ should be displayed

like image 211
user2354254 Avatar asked Apr 01 '15 11:04

user2354254


People also ask

How do you check if a column contains a substring in SQL?

SQL Server CHARINDEX() Function The CHARINDEX() function searches for a substring in a string, and returns the position. If the substring is not found, this function returns 0. Note: This function performs a case-insensitive search.

How do you get a specific part of a string in SQL?

The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.

How do you check if a string contains a specific word in SQL?

To check if string contains specific word in SQL Server we can use CHARINDEX function. This function is used to search for specific word or substring in overall string and returns its starting position of match. In case if no word found then it will return 0 (zero).


3 Answers

The answer would be "use LIKE".

See the documentation: https://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html

You can do WHERE 'string' LIKE CONCAT(column , '%')

Thus the query becomes:

select * from t1 where 'ABCDEFG' LIKE CONCAT(column1,'%');

If you need to match anywhere in the string:

select * from t1 where 'ABCDEFG' LIKE CONCAT('%',column1,'%');

Here you can see it working in a fiddle: http://sqlfiddle.com/#!9/d1596/4

like image 198
Turophile Avatar answered Oct 13 '22 03:10

Turophile


Select * from table where @param like '%' + col + '%'
like image 41
Aheho Avatar answered Oct 13 '22 04:10

Aheho


First, you appear to be storing lists of things in a column. This is the wrong approach to storing values in the database. You should have a junction table, with one row per entity and value -- that is, a separate row for ABC and XYZ in your example. SQL has a great data structure for storing lists. It is called a "table", not a "string".

If you are stuck with such a format and using MySQL, there is a function that can help:

where find_in_set('ABC', col)

MySQL treats a comma delimited string as a "set" and offers this function. However, this function cannot use indexes, so it is not particularly efficient. Did I mention that you should use a junction table instead?

like image 3
Gordon Linoff Avatar answered Oct 13 '22 04:10

Gordon Linoff