Tom Redman
Tom Redman

Reputation: 5650

How can I speed up or optimize this SQLite query for iOS?

I have a pretty simple DB structure. I have 12 columns in a single table, most are varchar(<50), with about 8500 rows.

When I perform the following query on an iPhone 4, I've been averaging 2.5-3 seconds for results:

SELECT * FROM names ORDER BY name COLLATE NOCASE ASC LIMIT 20

Doesn't seem like this sort of thing should be so slow. Interestingly, the same query from the same app running on a 2nd gen iPod is faster by about 1.5 seconds. That part is beyond me.

I have other queries that have the same issue: SELECT * FROM names WHERE SEX = ?1 AND ORIGIN = ?2 ORDER BY name COLLATE NOCASE ASC LIMIT 20

and

SELECT * FROM names WHERE name LIKE ?3 AND SEX = ?1 AND ORIGIN = ?2 ORDER BY name COLLATE NOCASE ASC LIMIT 20

etc.

I've added an index on the SQLite db: CREATE INDEX names_idx ON names (name, origin, sex, meaning) where name, origin, sex and meaning are the columns I tend to query against with WHERE and LIKE operators.

Any thoughts on improving the performance of these searches or is this about as atomic as it gets?

Upvotes: 2

Views: 2346

Answers (2)

Nick Shaw
Nick Shaw

Reputation: 2113

The index CREATE INDEX names_idx ON names (name, origin, sex, meaning) will only be used, I believe, if your query includes ALL those columns. If only some are used in a query, the index can't be used.

Going on your first query: SELECT * FROM names ORDER BY name COLLATE NOCASE ASC LIMIT 20 - I would suggest adding an index on name, just by itself, i.e. CREATE INDEX names_idx1 ON names (name). That should in theory speed up that query.

If you want other indexes with combined columns for other common queries, fair enough, and it may improve query speed, but remember it'll increase your database size.

Upvotes: 3

yoozz
yoozz

Reputation: 249

What is the most used search criteria ? if you search for names for example you could create more tables according to the name initials. A table for names which start with "A" etc. The same for genre. This would improve your search performance in some cases.

Upvotes: 1

Related Questions