Text search basics

Draft

Text search starts with patterns. LIKE and ILIKE are simple tools for prefix, suffix, and contains-style matching.

Prefix search

LIKE uses % as a wildcard. This pattern matches titles starting with SQL.

SELECT title
FROM articles
WHERE title LIKE 'SQL%';
title
SQL join guide
Seq Scan on articles  (cost=0.00..20.62 rows=4 width=32)
  Filter: (title ~~ 'SQL%'::text)

Case-insensitive search

ILIKE works like LIKE, but ignores letter case.

SELECT title
FROM articles
WHERE title ILIKE '%postgres%';
title
PostgreSQL indexing guide
JSON in Postgres
Seq Scan on articles  (cost=0.00..20.62 rows=1 width=32)
  Filter: (title ~~* '%postgres%'::text)

LOWER can make a regular LIKE comparison case-insensitive.

SELECT title
FROM articles
WHERE LOWER(body) LIKE '%search%';
title
Vector search notes
Seq Scan on articles  (cost=0.00..22.75 rows=1 width=32)
  Filter: (lower(body) ~~ '%search%'::text)

Beyond patterns

Patterns need the exact characters. For word forms, see full-text search; for typos, fuzzy search; for meaning, vectors. Text search in Postgres compares them all.

Try Yourself

Loaded Database:text-search-basics.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Find articles whose title mentions Postgres.
2.Find articles whose title ends with guide.

What We Learned

  • LIKEmatches text with wildcard patterns.
  • ILIKEmatches text while ignoring case.
  • %matches any sequence of characters in a pattern.
  • LOWERnormalizes text before comparison.