Using LTRIM() in PostgreSQL

In PostgreSQL, the ltrim() function trims the left side of a string. We can trim blank spaces or we can specify certain characters to trim.

It removes the longest string containing only characters from the ones we specify. If we don’t specify any characters, then it removes blank spaces.

Trimming Blank Space

Here’s a quick example to demonstrate how to trim blank space from the left side of a string:

SELECT ltrim('     Dog     ');

Result:

  ltrim   
----------
Dog

I didn’t specify any characters to trim and so the string had its white space trimmed from the left side.

Trimming Other Characters

We can trim other characters from the string by including them as a second argument:

SELECT ltrim('pad-Dog-pad', '-pad');

Result:

  ltrim  
---------
Dog-pad

It doesn’t require that all specified characters are in the string, just that one of them is at the start of the string at any point in the trim operation.

Therefore, we’ll still get the same result if we change the order of the characters in the second argument, and even if we add more characters:

SELECT ltrim('pad-Dog-pad', '-dapzy');

Result:

  ltrim  
---------
Dog-pad

Let’s remove the a character from our list:

SELECT ltrim('pad-Dog-pad', '-dpzy');

Result:

   ltrim    
------------
ad-Dog-pad

This time it stopped trimming as soon as it got to the a character, because that wasn’t in the list of characters to trim.

Here’s another example:

SELECT ltrim('pap-Dog', '-dp');

Result:

 ltrim  
--------
ap-Dog

This time the first p was trimmed but not the second one. That’s because it stopped trimming as soon as it got to the a (which isn’t in the list of characters to trim).

We can include the blank space in our list of characters to trim if required:

SELECT ltrim('pap Dog', ' pa');

Result:

 ltrim 
-------
Dog

In fact, if we don’t do this, and there are any blank spaces at the start of the string, then nothing would get trimmed.

Here’s an example of what I mean:

SELECT ltrim(' pap Dog', 'pa');

Result:

  ltrim   
----------
pap Dog

The string is returned untrimmed. That’s because I removed the blank space from the list of characters to trim. Given there was white space at the start of the string, nothing was trimmed.

Passing Null Arguments

If any of the arguments are null, then null is returned:

SELECT 
    ltrim(null, ' pa') AS "1",
    ltrim(' Dog', null) AS "2";

Result:

  1   |  2   
------+------
null | null