Re: Escape string for LIKE op - Mailing list pgsql-general

From Jeff Janes
Subject Re: Escape string for LIKE op
Date
Msg-id CAMkU=1ygdQ=p2SjwM4UCjcMyVPxiW65Md-SbCWjHyjipeLnGtQ@mail.gmail.com
Whole thread Raw
In response to Escape string for LIKE op  (Robert James <srobertjames@gmail.com>)
Responses Re: Escape string for LIKE op  (Robert James <srobertjames@gmail.com>)
List pgsql-general
On Thu, Aug 15, 2013 at 1:16 PM, Robert James <srobertjames@gmail.com> wrote:
> How can I escape a string for LIKE operations?
>
> I want to do:
>
> SELECT * FROM t WHERE a LIKE b || '%'
>
> But I want be to interpreted literally.  If b is 'The 7% Solution', I
> don't want that '%' to be wildcard.  I can't find an appropriate
> function to escape it and any other potential wildcards for LIKE
> clauses.

You could use the replace function.

select 'The 7% Solution is a good book' like replace('The 7%
Solution', '%', '\%')||'%';
true

select 'The 7pt Solution is a good book' like replace('The 7%
Solution', '%', '\%')||'%';
false

If you need to worry about underscores as well, you could chain two
replace functions together.

Cheers,

Jeff


pgsql-general by date:

Previous
From: Andrew Berman
Date:
Subject: Re: Streaming Replication Randomly Locking Up
Next
From: "Janek Sendrowski"
Date:
Subject: devide and summarize sql result