← All notes

PostgreSQL full text search: tsvector, tsquery, ranking

Short answer

Convert documents with to_tsvector, queries with to_tsquery, match with @@, and order with ts_rank. Unlike LIKE, this handles word forms, ranks results and can use an index. [S1][S2]

Example

SELECT title FROM docs
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'cat & rat')
ORDER BY ts_rank(to_tsvector('english', body), to_tsquery('english','cat & rat')) DESC;

For speed, store the tsvector in a column and index it with GIN.

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: PostgreSQL Global Development Group, PostgreSQL: Documentation: 18: 12.1. Introduction, PostgreSQL License; PostgreSQL Global Development Group, PostgreSQL: Documentation: 18: 12.3. Controlling Text Search, PostgreSQL License.

Cite this

Permanent ID: iil:note:nt8jw7ps

iinventedlight. 2026. "PostgreSQL full text search: tsvector, tsquery, ranking." iinventedlight Library, iil:note:nt8jw7ps, version of 2026-11-04. https://iinventedlight.com/library/notes/postgres-full-text-search/. License: CC-BY-4.0.

@misc{iil_note_nt8jw7ps,
  author = {{iinventedlight}},
  title = {{PostgreSQL full text search: tsvector, tsquery, ranking}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-04},
  url = {https://iinventedlight.com/library/notes/postgres-full-text-search/},
  note = {Permanent ID iil:note:nt8jw7ps. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/postgres-full-text-search.md.