Search code examples
postgresqltrim

I can't understand the behaviour of btrim()


I'm currently working with postgresql, I learned about this function btrim, I checked many websites for explanation, but I don't really understand.

Here they mention this example:

btrim('xyxtrimyyx', 'xyz')

It gives trim.

When I try this example:

btrim('xyxtrimyyx', 'yzz')

or

btrim('xyxtrimyyx', 'y')

I get this: xyxtrimyyx

I don't understand this. Why didn't it remove the y?


Solution

  • From the docs you point to, the definition says:

    Remove the longest string consisting only of characters in characters (a space by default) from the start and end of string

    The reason your example doesn't work is because the function tries to strip the text from Both sides of the text, consisting only of the characters specified

    Lets take a look at the first example (from the docs):

    btrim('xyxtrimyyx', 'xyz')
    

    This returns trim, because it goes through xyxtrimyyx and gets up to the t and doesn't see that letter in xyz, so that is where the function stops stripping from the front.

    We are now left with trimyyx

    Now we do the same, but from the end of the string. While one of xyz is the last letter, remove that letter. We do this until m, so we are left with trim.

    Note: I have never worked with any form of sql. I could be wrong about the exact way that postgresql does this, But I am fairly certain from the docs that this is how it is done.