Sub topic 1
Why LIKE is not enough for text search
Prerequisites
This chapter assumes you can:
- Write
SELECT,WHERE,ORDER BYandJOINqueries. - Create tables and indexes in PostgreSQL.
- Run queries in
psqlor another SQL client.
You don't need any full-text search knowledge. This chapter shows where LIKE breaks down, so the rest of the tutorial has a reason to exist.
What LIKE actually does
LIKE compares a string against a pattern. % matches any run of characters and _ matches exactly one. ILIKE is the PostgreSQL extension that ignores case. Both work on characters. They know nothing about words, grammar, or relevance.
That is fine for questions like "does this code start with INV-?" It is a poor fit for natural-language questions like "which articles are about running a database?"
A small test table
Create a table you can experiment with:
CREATE TABLE notes (
id bigserial PRIMARY KEY,
body text NOT NULL
);
INSERT INTO notes (body) VALUES
('The quick brown foxes jumped over the lazy dogs'),
('A fox is jumping over a fence'),
('Categories of dogs'),
('The cat sat on the mat'),
('She runs every morning and he likes running');The sections below use this table to show five separate problems.
Problem 1: no word boundaries
You want notes about cats:
SELECT id, body FROM notes WHERE body ILIKE '%cat%';This returns rows 3 and 4. Row 4 is correct. Row 3, "Categories of dogs", matches only because the letters cat appear inside the word "Categories". LIKE cannot tell a word from a fragment of a word.
You can add spaces to the pattern ('% cat %'), but then you miss cat at the start or end of the text and next to punctuation. Fixing this properly needs regular expressions, which are slower and harder to write.
Problem 2: no word forms
You search for jumps:
SELECT id, body FROM notes WHERE body ILIKE '%jumps%';This returns no rows, although rows 1 and 2 contain "jumped" and "jumping". A reader treats these as forms of the same verb. LIKE treats them as different strings.
Full-text search handles this by stemming, which reduces words to a common root. Compare:
SELECT id, body
FROM notes
WHERE to_tsvector('english', body) @@ plainto_tsquery('english', 'jumps');This returns rows 1 and 2. PostgreSQL reduced "jumped", "jumping" and "jumps" to the same root, jump. The next chapters explain to_tsvector, plainto_tsquery and @@. For now, notice that the same query, written with these tools, gives the better result.
The same tools also fix problem 1. Stemming turns "Categories" into categori, which differs from cat, so only row 4 matches a search for cat.
Problem 3: multi-word searches depend on exact text
A user types lazy dogs:
SELECT id FROM notes WHERE body ILIKE '%lazy dogs%';This works, but only because the words are adjacent and in that order. A user who types dogs lazy gets nothing. To match both words anywhere, you must write one condition per word:
SELECT id FROM notes
WHERE body ILIKE '%dogs%'
AND body ILIKE '%lazy%';Your application must split the input, escape any % and _ the user typed, and build the AND chain. Full-text search does this in one step: plainto_tsquery('english', 'dogs lazy') produces a query that requires both words in any order.
Problem 4: no ranking
LIKE returns a yes or no for each row. If 500 rows match, you have no way to say which are the best. A document that mentions the term once in a footnote looks the same as one about nothing else.
Full-text search can score a match. It counts how often the terms occur and, as you will see later, lets you give a title more weight than a body. This is what makes a result list useful.
Problem 5: poor performance on large tables
A B-tree index on a text column helps when the pattern is anchored at the start, such as LIKE 'abc%'. This also depends on the database collation or an operator class suited to pattern matching. A pattern that begins with % cannot use that index, because the match could start anywhere in the string.
Check this yourself on a large table:
CREATE INDEX notes_body_idx ON notes (body);
EXPLAIN SELECT id FROM notes WHERE body ILIKE '%fox%';On a table with many rows, the plan shows a Seq Scan. PostgreSQL reads every row and runs the pattern match on every body. The cost grows linearly with table size and with document length. On a tiny table like notes, the planner may choose a sequential scan regardless, so this effect only shows at scale.
Full-text search avoids this by splitting each document into words once, at write time, and storing them in a form an index can look up. A search then goes to the index instead of reading text. The chapter on GIN indexes covers this.
Where each approach fits
The diagram shows the difference in how the two approaches process the same search.
| Need | LIKE / ILIKE | Full-text search |
|---|---|---|
| Match a fixed prefix or suffix, such as a code | Good fit | Not designed for it |
| Match word forms (jump, jumps, jumped) | No | Yes, through stemming |
| Ignore filler words such as "the" | No | Yes, through stop words |
| Rank by relevance | No | Yes |
| Highlight matches in a snippet | No | Yes |
| Fast on large tables | Only for anchored patterns | Yes, with an index |
| Arbitrary substring, such as `%ob%` | Works, slow without help | Not designed for it |
What comes next
The next chapters build the full-text search tools in this order:
- Text search configurations, which decide how a language is normalized.
tsvector, the stored form of a document.tsquery, the form of a search.- The
@@operator, which tests a document against a query.
By the end you will have a weighted, ranked, indexed search over a real table.
Exercise
A table of 2 million support tickets has a column subject. A developer writes WHERE subject ILIKE '%refund%' and the query takes several seconds. Give two reasons it is slow or returns poor results, and name a feature of full-text search that addresses each.
Show answer
First, the pattern starts with %, so a B-tree index cannot be used and PostgreSQL scans every row, running the match on each subject. Full-text search addresses this by splitting each document into words at write time and storing them in an index (GIN), so a search is an index lookup. Second, the search is a substring match with no word awareness, so it misses "refunded" or "refunds" in some forms and cannot rank tickets. Stemming makes the forms of the word match each other, and ts_rank orders the results by relevance. Another valid answer: the pattern would also match "nonrefundable", and word-based matching avoids matching fragments inside other words.
Exercise
Using the notes table from this chapter, what does SELECT id FROM notes WHERE body ILIKE '%running%' return, and why might a user searching for "run" be disappointed with the results from ILIKE '%run%'?
Show answer
The first query returns only row 5, which contains the literal text "running". A search for "run" with ILIKE '%run%' also returns row 5, because "runs" and "running" both contain the characters "run". But it would also match any word that merely contains those letters, such as "prune" or "truncate", and it cannot rank the results. Stemming reduces "runs" and "running" to the same root, so a full-text search finds the right word forms without matching unrelated words that happen to contain the same letters.