SQL SIMILAR TO operator
SIMILAR TO is the SQL standard's regex-flavoured LIKE: % and _ still work, and |, *, +, {n} and [...] are added.
- Категория
- Условные конструкции
- Returns
boolean- In this category
- 40 of 43
Синтаксис
string SIMILAR TO pattern [ESCAPE char]
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Different name or syntax | no SIMILAR TO; REGEXP_LIKE on 2025, LIKE with [ ] classes before |
| PostgreSQL | Да | Supported under this name. |
| MySQL | Not built in | no SIMILAR TO; REGEXP or REGEXP_LIKE |
| SQLite | Not built in | no SIMILAR TO; GLOB, or REGEXP where a regexp function is loaded |
| Oracle | Different name or syntax | no SIMILAR TO; REGEXP_LIKE |
Примеры
PostgreSQL
SELECT 'abc' SIMILAR TO 'a(b|x)c' AS alt, 'abc' SIMILAR TO 'b' AS partial, 'abc' SIMILAR TO '%b%' AS wildcard; -- t, f, t
PostgreSQL
SELECT code FROM (VALUES ('AB-12'), ('ab-12'), ('AB-1x')) AS t(code)
WHERE code SIMILAR TO '[A-Z]{2}-[0-9]{2}'; -- AB-12
MySQL
SELECT 'ab-12' REGEXP '^[A-Z]{2}-[0-9]{2}$' AS ci, REGEXP_LIKE('ab-12', '^[A-Z]{2}-[0-9]{2}$', 'c') AS cs; -- 1, 0
Полезно знать
- The pattern must match the whole string, as with LIKE: 'abc' SIMILAR TO 'b' is false and '%b%' is true.
- A dot is a literal dot, not 'any character': 'abc' SIMILAR TO 'a.c' is false. Use _ for one character.
- PostgreSQL turns SIMILAR TO into a POSIX regular expression internally. Beyond simple alternation, the ~ operator with a real regex is easier to read.
Questions about SIMILAR TO
SIMILAR TO or ~?
Use ~ for anything non-trivial: it is a full POSIX regex and does not need to match the whole string. SIMILAR TO only helps when you want LIKE semantics plus alternation.
Why does the MySQL REGEXP match lower-case letters?
MySQL regex matching follows the collation, and the default utf8mb4 collation ignores case, so [A-Z] matches 'a'. Pass 'c' as the match type, as in the example, for a case-sensitive match.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, Oracle.
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.