// strings reference

SQL WORD_SIMILARITY function

Scores the best similarity between a search term and any part of a longer text string.

Categoria
Strings
Returns
real
In this category
121 of 172

Sintaxe

word_similarity(term, text)
strict_word_similarity(term, text)

Each block is a separate form. The support table and the examples show which engine takes which.

Suporte a mecanismos

MotorSupportNotas
SQL Server Not built in Full-text search covers word lookup, not trigram scores.
PostgreSQL Sim Requires the pg_trgm extension.
MySQL Not built in FULLTEXT search is the word-based route.
SQLite Not built in No built-in equivalent.
Oracle Not built in Oracle Text's CONTAINS with the FUZZY operator.

Exemplos

PostgreSQL

SELECT word_similarity('smith', 'john smith jr') AS score;  -- 1

PostgreSQL

SELECT * FROM companies
WHERE 'acme' <<% name  -- fuzzy word match, index-friendly
ORDER BY word_similarity('acme', name) DESC;

Bom saber

  • similarity compares whole strings; word_similarity asks how well the first argument matches the best stretch of the second, which suits searching names inside longer text.
  • strict_word_similarity only scores stretches that line up with word boundaries: word_similarity('smith', 'smithereens') is about 0.83, strict_word_similarity about 0.38.
  • 'term' <<% col is true when word_similarity('term', col) exceeds pg_trgm.word_similarity_threshold (default 0.6); col %>> 'term' is the same test written the other way round. Both can use a GIN or GiST trigram index.

Questions about WORD_SIMILARITY

When do I use word_similarity instead of similarity?

When the search term should match one word inside longer text, like 'nike' in 'Nike Sportswear Inc'. Plain similarity dilutes the score across the whole string.

What does strict_word_similarity add?

Word-boundary alignment: the matched stretch must start and end at word boundaries, so a term inside a longer word scores lower.

Can word_similarity use an index?

The operators can: a GIN or GiST index with gin_trgm_ops or gist_trgm_ops supports <<% and %>>. The function call alone does not use the index.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.