How to escape underscores in Postgresql

Just ran into the same issue and the single backslash wasn't working as well. I found this documentation on the PostgreSQL community and it worked:

The correct way is to escape the underscore with a backslash. You actually have to write two backslashes in your query:

select * from foo where bar like '%\\_baz'

The first backslash quotes the second one for the query parser, so that what ends up inside the system is %\_baz, and then the LIKE function knows what to do with that.

Therefore use something like this:

SELECT table_name, column_name FROM information_schema.columns
WHERE column_name LIKE '%\\_by'

Source Documentation: https://www.postgresql.org/message-id/10965.962991238%40sss.pgh.pa.us


You need to use a backslash to escape the underscore. Change the example query to the following:

SELECT table_name, column_name FROM information_schema.columns
WHERE column_name LIKE '%\_by'