// strings reference

SQL SIMILARITY function

Scores how alike two strings are, from 0 (unrelated) to 1 (identical), using shared trigrams.

카테고리
Strings
Returns
real
In this category
120 of 172

구문

similarity(string1, string2)

엔진 지원

엔진Support메모
SQL Server Not built in No trigram similarity built in.
PostgreSQL 예 Requires CREATE EXTENSION pg_trgm.
MySQL Not built in No trigram similarity; FULLTEXT is word-based.
SQLite Not built in No built-in similarity.
Oracle Not built in No trigram function; UTL_MATCH scores 0-100 by edit distance or Jaro-Winkler.

예시

PostgreSQL

SELECT similarity('smith', 'smyth') AS score;  -- 0.33333334

PostgreSQL

CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT * FROM products
WHERE name % 'ipone'  -- fuzzy match, can use a trigram index
ORDER BY similarity(name, 'ipone') DESC;

알아 두면 좋은 정보

  • pg_trgm lowercases the strings, splits them into words, pads each word with spaces and compares the sets of three-character windows. Case does not count, and word order matters little.
  • There is no universal threshold: 0.3 is the % operator's default, but short strings swing widely: similarity('smith', 'smyth') is only 0.33. Tune per dataset.
  • The % operator and ORDER BY name <-> 'term' can use a GIN or GiST index built with gin_trgm_ops or gist_trgm_ops; a bare similarity() call in WHERE cannot.

Questions about SIMILARITY

What is the difference between similarity and Levenshtein?

Levenshtein counts character edits; similarity compares trigram sets. Similarity can use an index and tolerates word swaps, but it says nothing exact about spelling.

What does the % operator do in pg_trgm?

a % b is true when similarity(a, b) is greater than pg_trgm.similarity_threshold, 0.3 by default. Unlike the function, it can use a trigram index.

Why do short strings score strangely?

A short string has few trigrams, so one changed letter removes a large share of them. Use a lower threshold for short names and codes, or switch to levenshtein.

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.