← Back to PostgreSQL, page 1

postgresql-0014 · Easy fresher

Use ILIKE and LIKE patterns, and explain when a pattern search can use an index.

LIKE matches patterns with % for any run of characters and _ for one character; ILIKE is the case-insensitive version. A prefix pattern such as 'abc%' can use a B-tree index built with text_pattern_ops (or in the C collation), but a leading wildcard such as '%abc%' needs a trigram GIN index from pg_trgm.

Full answer

Schema and sample rows:

sql
CREATE TABLE products (id int, name text);
INSERT INTO products VALUES (1, 'Blue Pen'), (2, 'blue ink'), (3, 'Notebook'), (4, 'Pen_Stand');
CREATE INDEX products_name_prefix ON products (name text_pattern_ops);
sql
SELECT name FROM products WHERE name LIKE 'Blue%' ORDER BY id;

PostgreSQL returns:

text
   name
----------
 Blue Pen
(1 row)
sql
SELECT name FROM products WHERE name ILIKE 'blue%' ORDER BY id;

Result on PostgreSQL 17:

text
   name
----------
 Blue Pen
 blue ink
(2 rows)
sql
SELECT name FROM products WHERE name LIKE '%\_%' ORDER BY id;

Result:

text
    name
-----------
 Pen_Stand
(1 row)
sql
SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT name FROM products WHERE name LIKE 'Note%';

Output:

text
Index Only Scan using products_name_prefix on products
  Index Cond: ((name ~>=~ 'Note'::text) AND (name ~<~ 'Notf'::text))
  Filter: (name ~~ 'Note%'::text)

LIKE is case-sensitive, so only 'Blue Pen' matches the first query, while ILIKE also matches 'blue ink'. An underscore is itself a wildcard, so searching for a literal underscore needs the escape _, which finds only 'Pen_Stand'. The plan shows the prefix search using the text_pattern_ops index as a range condition (name >= 'Note' and name < 'Notf'); sequential scans were disabled only so the tiny table shows the index path. For ILIKE or infix searches, CREATE EXTENSION pg_trgm and a GIN index with gin_trgm_ops is the usual answer.

sql
CREATE TABLE products (id int, name text);
INSERT INTO products VALUES (1, 'Blue Pen'), (2, 'blue ink'), (3, 'Notebook'), (4, 'Pen_Stand');
CREATE INDEX products_name_prefix ON products (name text_pattern_ops);

SELECT name FROM products WHERE name LIKE 'Blue%' ORDER BY id;

SELECT name FROM products WHERE name ILIKE 'blue%' ORDER BY id;

SELECT name FROM products WHERE name LIKE '%\_%' ORDER BY id;

SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT name FROM products WHERE name LIKE 'Note%';

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • % and _ are wildcards
  • ILIKE ignores case
  • Escape literal underscores
  • Prefix searches can use text_pattern_ops
  • pg_trgm for infix and ILIKE

Common mistakes

  • Expecting '%term%' to use a B-tree index
  • Forgetting that _ is a wildcard

Follow-ups

  • How does pg_trgm similarity work?
  • When is full-text search better than LIKE?

Tips

  • Show the plan