// conditional reference

SQL LIKE ESCAPE clause

Declares the one-character escape that turns LIKE wildcards into literals.

カテゴリ
条件付き
Returns
boolean
In this category
26 of 43

構文

col LIKE '100\%' ESCAPE '\' | col LIKE '100!%' ESCAPE '!'

エンジンサポート

エンジンSupportメモ
SQL Server はい Supported under this name.
PostgreSQL はい Supported under this name.
MySQL はい Supported under this name.
SQLite はい Supported under this name.
Oracle はい Supported under this name.

例

Any engine

SELECT * FROM t WHERE note LIKE '100!%' ESCAPE '!';

Any engine

SELECT * FROM t WHERE code LIKE 'a!_b' ESCAPE '!';

知っておくと便利なこと

  • You choose the escape character after ESCAPE; pick something the user will never type, like !, and escape only % and _ in their input.
  • The escape character must be exactly one character, and a pattern cannot end with a lone escape character.
  • Bracket character classes [0-9], [^a-z] are a T-SQL extension; PostgreSQL, MySQL, Oracle and SQLite treat brackets literally in LIKE.

Questions about ESCAPE

Is backslash the default escape?

In PostgreSQL and MySQL, yes: 'a_b' LIKE 'a\_b' is true there. SQL Server, Oracle and SQLite have no default escape character, so the same pattern looks for a literal backslash. Declare ESCAPE explicitly for portable code.

How do I sanitize user input for LIKE?

Escape the wildcards in their input: REPLACE(input, '!', '!!') then REPLACE(..., '%', '!%') and same for _, then append ESCAPE '!'.

Do [0-9] classes work in LIKE?

Only in SQL Server (T-SQL); the other engines match the brackets literally.

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: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.