Escaping LIKE wildcards

You want a wildcard match with LIKE but need to match a literal underscore or percentage sign.

Solution

Escape the wildcard character with a backslash - remember you will need two backslashes to get one through the string processorref.

Discussion

If you want to match "20% increase..." but not "200 increase..." you will need something like:

SELECT * FROM FOO WHERE a LIKE '20\\% increase%';
   

The above is when typed from psql, and you need two backslashes because Postgres' string processor boils two backslashes down into one. If you were building a query string in (say) PHP you would need four - PHP will reduce this to two in the variable and Postgres to one by the time it reaches the LIKE

$sql = "SELECT * FROM FOO WHERE a LIKE '20\\\\% increase%'";
   

If you are worried about a world backslash shortage you can use the ESCAPE qualifier to use a different character instead of backslash:

SELECT * FROM FOO WHERE a LIKE '20X% increase%' ESCAPE 'X';
   

You'll need to make sure you double X characters where they occur if you use this. Oh - and other people's string quoting functions won't be expecting this, so be careful.