How to escape underscores in Postgresql

落爺英雄遲暮 提交于 2019-12-12 09:29:18

问题


When searching for underscores in Postgresql, literal use of the character _ doesn't work. For example, if you wanted to search all your tables for any columns that ended in _by, for something like change log or activity information, e.g. updated_by, reviewed_by, etc., the following query almost works:

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

It basically ignores the underscore completely and returns as if you'd searched for LIKE '%by'. This may not be a problem in all cases, but it has the potential to be one. How to search for underscores?


回答1:


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'



回答2:


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



来源:https://stackoverflow.com/questions/38084864/how-to-escape-underscores-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!