Search code examples
pythonsqlstringsql-likessms-2014

Multiple words in Where field LIKE


I have a list of values (words) and I want to check if a column in my table contains a value (any value) from the list.

My list can be very long so I want to create it using a for loop, for example:

words = ( 'one', 'two', 'three' )
whereClause=""
a=""
for word in words:
   temp=" item LIKE '%" +word +  " %' or"
   whereClause=whereClause+temp
whereClause = whereClause[17:]  #delete first "item LIKE"
whereClause = whereClause[:-3] #delete last "or"

Now I want to put it in my sql query:

sql= """select name
from table
where item LIKE ? """

cursor.execute(sql, whereClause)
rows=cursor.fetchall()

It's not working, any suggestions?

Do you think I better get all the values of the column "name" using sql query and only then check if values from the list exists using Python? Thanks!


Solution

  • In case you are still facing issues:

    words = ( 'one', 'two', 'three' )
    whereClause=""
    
    i = 1
    for word in words:
        if i == 1:
            whereClause = " item LIKE '%" +word + "%'"
        else:
            whereClause += " OR item LIKE '%" +word + "%'"
        i += 1
    
    sql= """select name
    from table
    where {0} """.format(whereClause)
    
    cursor.execute(sql)
    rows=cursor.fetchall()