// dialect comparison

Pattern matching with LIKE and ESCAPE

% and _ are wildcards until you declare an escape character, and backslash is the worst choice for one.

Filed under Querying

The verdict

LIKE '100!%' ESCAPE '!' runs unchanged on all five engines. The backslash version does not: MySQL's string parser reads ESCAPE '\' as an unterminated literal, and backslash is a silent default escape in MySQL and PostgreSQL but an ordinary character in SQL Server, SQLite and Oracle. Choose a character that never appears in your data, and escape it too when it does.

Where they differ

To match a literal % or _, put an escape character in front of it and name that character with ESCAPE. The clause is standard and works in all five engines. Pick a character other than backslash and the same SQL text runs everywhere.

How each engine writes it

SQL Server

SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';

T-SQL also lets you bracket the wildcard: LIKE '100[%]' matches a literal % without ESCAPE.

PostgreSQL

SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';

Backslash is the default escape even without ESCAPE, so '100\%' works on its own. ILIKE takes the same ESCAPE clause.

MySQL

SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';

Backslash is the default escape. Writing ESCAPE '\' fails here because the string parser treats \' as an escaped quote; ESCAPE '\\' is the working spelling.

SQLite

SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';

No default escape character: without ESCAPE, a pattern cannot match a literal % or _.

Oracle

SELECT * FROM files WHERE name LIKE '100!%' ESCAPE '!';

No default escape character. The same clause covers _, as in 'file!_x'.

Questions that come up

Why doesn't my '100\%' pattern match anything?

In SQL Server, SQLite and Oracle, backslash means nothing in LIKE unless you declare it with ESCAPE, so the pattern looks for a literal backslash. In MySQL the string parser may consume the backslash before LIKE sees it. A declared non-backslash escape character avoids both problems.

Do I need ESCAPE for the underscore too?

Yes. _ matches any single character, so LIKE 'file_x' also matches 'fileAx'. Use LIKE 'file!_x' ESCAPE '!'. Underscores are common in identifiers and file names, so this bites more often than %.

How do I make a LIKE search case-insensitive?

It follows the collation. SQL Server and MySQL default collations already ignore case. PostgreSQL has ILIKE. SQLite's LIKE ignores case for ASCII letters by default (PRAGMA case_sensitive_like turns that off). Oracle is case-sensitive: compare UPPER(name) LIKE UPPER(:pattern).

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.