Full answer
Think of a phone book sorted by surname. Finding everyone whose name starts with "Ma" is quick: jump to the first Ma and read until the names stop starting with Ma. Finding everyone whose name ends in "son" means reading the whole book.
A B-tree index is the phone book. LIKE 'Ma%' can be turned into the range >= 'Ma' AND < 'Mb', which the index can seek to. LIKE '%son' and LIKE '%ar%' have no fixed start, so the database scans.
SQLite adds a twist. Its LIKE is case-insensitive for ASCII, but a normal index is case-sensitive, so the two orders do not agree and SQLite will not use the index for LIKE:
CREATE TABLE people (id INTEGER PRIMARY KEY, surname TEXT);
CREATE INDEX idx_people_surname ON people(surname);
EXPLAIN QUERY PLAN SELECT id FROM people WHERE surname LIKE 'Ma%';QUERY PLAN
SCAN peopleDeclare the column (or the index) with COLLATE NOCASE, and the prefix search becomes an index search:
CREATE TABLE people2 (id INTEGER PRIMARY KEY, surname TEXT COLLATE NOCASE);
CREATE INDEX idx_people2_surname ON people2(surname);
EXPLAIN QUERY PLAN SELECT id FROM people2 WHERE surname LIKE 'Ma%';QUERY PLAN
SEARCH people2 USING COVERING INDEX idx_people2_surname (surname>? AND surname<?)The %son search still scans, even with the right collation:
EXPLAIN QUERY PLAN SELECT id FROM people2 WHERE surname LIKE '%son';QUERY PLAN
SCAN people2PostgreSQL has its own rule: a plain B-tree index helps LIKE prefix searches only with the C collation or an index built with text_pattern_ops. For "contains" or "ends with" searches, PostgreSQL offers trigram indexes (the pg_trgm extension), and both engines offer full-text search for word matching. Those PostgreSQL details come from its documentation and were not run here.
A trick for "ends with" searches is to store the reversed string and index that, so '%son' becomes a prefix search for 'nos%'.
CREATE TABLE people (id INTEGER PRIMARY KEY, surname TEXT);
CREATE INDEX idx_people_surname ON people(surname);
EXPLAIN QUERY PLAN SELECT id FROM people WHERE surname LIKE 'Ma%';
CREATE TABLE people2 (id INTEGER PRIMARY KEY, surname TEXT COLLATE NOCASE);
CREATE INDEX idx_people2_surname ON people2(surname);
EXPLAIN QUERY PLAN SELECT id FROM people2 WHERE surname LIKE 'Ma%';
EXPLAIN QUERY PLAN SELECT id FROM people2 WHERE surname LIKE '%son';Checked on SQLite 3.46.1, run twice with identical output.
Key points
- A fixed prefix turns LIKE into an index range scan
- A leading % forces a scan
- SQLite needs NOCASE collation (or case_sensitive_like) for LIKE to use an index
- PostgreSQL uses text_pattern_ops for prefix LIKE, pg_trgm for contains
Common mistakes
- Adding an index and assuming LIKE '%term%' will use it
- Ignoring collation when checking why SQLite does not use the index
Follow-ups
- How would you speed up a search box that matches anywhere in a product name?
- What is a trigram index?
Tips
- Use the phone book picture; it explains the rule in one sentence
- Check the plan with EXPLAIN instead of guessing