What would be faster; searching a sqlite3 database table for a row whose primary key equals a specific string
OR
In Python, I obtain all the primary keys from a sqlite3 database table (using a query) as a Python list and use Pythons in keyword to test whether a specific string occurs within that list.
I guess I am asking does SQLite3 employ a more advanced algorithm to find a specific row with the primary key I am searching for or would it be faster to just get all the primary keys myself & search using python(or employ my own Binary search once I get them all)?
Code to do either way:
import sqlite3
conn = sqlite3.connect("d.db")
cur = conn.cursor()
isPresent = cur.execute( "SELECT target FROM stringList WHERE target='specificString';" ).fetchall()
return isPresent == None
// Alternate
primaryKeyList = cur.execute( "SELECT target FROM stringList;" ).fetchall()
return 'specificString' in primaryKeyList
// Or I can sort the list then use a binary search or other fast algorithm
primaryKeyList = cur.execute( "SELECT target FROM stringList;" ).fetchall()
//..sort primaryKeyList
primaryKeyList = sortList(primaryKeyList)
return binarySearch('specificString') == True
PS: Is there a way to tell SQLite3 in what order I want the rows to be stored in? So I can always have my rows in a table sorted alphabetically (according to their primary key)?
The answer to every “would it be faster?” question is “test it yourself”.
That said, the answer is that SQLite searching on an index is going to be faster than a SQLite table-scan plus an O(N) scan in Python.
As for your “tell SQLite how to store the rows” bit, you don’t want that. You can do an
ORDER BYto retrieve the results in a certain order – the way they’re stored is an implementation detail.