Skip to content
Advertisement

python sqlite3 partial search

I want to do a partial search with python sqlite3. My initial query is:

cur.execute("SELECT * FROM book WHERE title=? OR author=? OR year=? OR isbn=?", (title, author, year, isbn))

Then I tried using the LIKE keyword and string formatting to obtain partial search results for the title, like this:

cur.execute("SELECT * FROM book WHERE title LIKE ? OR author=? OR year=? OR isbn=?", ('%{}%'.format(title), author, year, isbn))

As in https://stackoverflow.com/a/20904256/13290801

This seems to do the trick for title, but now when searching on the other parameters, it’s not working at all although there is no error on the terminal. What am I missing?

EDIT I tried the answer posted by @forpas, but it gives me the same results.

So my new code for my search function is:

def search(title="", author="", year="", isbn=""):
    conn = sqlite3.connect('books.db')
    cur = conn.cursor()
    cur.execute("SELECT * FROM book WHERE title LIKE '%' || ? || '%' OR author=? OR year=? OR isbn=?", (title, author, year, isbn))

It works for title. If I search for “amst”, I get the Amsterdam title: Title partial search works

But if I search by year for 1970 I get all the results: Year search doesn't work

Advertisement

Answer

If you want to do partial search for the title then you must concatenate the '%' wildcard at the start and at the end of the title that you search.
Also you need an additional condition for the case that you pass an empty string for a column and the operator AND instead of OR:

sql = """
SELECT * FROM book 
WHERE (title LIKE '%' || ? || '%' OR LENGTH(?) = 0)
  AND (author = ? OR LENGTH(?) = 0) 
  AND (year = ? OR LENGTH(?) = 0) 
  AND (isbn = ? OR LENGTH(?) = 0)
"""
cur.execute(sql, (title, title, author, author, year, year, isbn, isbn))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement