Search code examples
mysqlsqlstringcontains

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


Solution

  • 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