Search code examples
sqlpython-3.xsql-like

Why CONTAINS and LIKE are not working in SQL?


I'm trying to extract keywords from the SQL database and CONTAINS and LIKE are not worrking.

import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('sqlite://', echo=False)

df = pd.read_csv('data.csv')
sql = df.to_sql('table1', con=engine,index=True)
q1 = engine.execute('SELECT * FROM table1 WHERE features LIKE "Swimming" ').fetchall()
q2 = engine.execute('SELECT * FROM table1 WHERE CONTAINS(features, "Swimming") ').fetchall()

I've tred both the ways but i'm not getting the answer. And i get this error OperationalError: (sqlite3.OperationalError) no such function: CONTAINS [SQL: 'SELECT * FROM table1 WHERE CONTAINS(features, "Swimming") '] (Background on this error at: http://sqlalche.me/e/e3q8)


Solution

  • You need to use double quote around your SQL statement and single quotes inside that.

    q1 = engine.execute("SELECT * FROM table1 WHERE features LIKE '%Swimming%' ").fetchall()
    

    You might want to change 'Swimming' to '%Swimming%' so that it can be matched to any value that has Swimming in it.