w3resource

PostgreSQL TRIM() function

TRIM() function

The PostgreSQL trim function is used to remove spaces or set of characters from the leading or trailing or both side from a string.

Syntax:

trim([leading|trailing|both] <removing_string> from <main_string>)

Parameters:

Parameters Description
leading | trailing | both The position of the main_string from where the removing_string will be removed.
removing_string String which will be removed. It is optional.
main_string The main string.

PostgreSQL Version: 9.3

Pictorial Presentation of PostgreSQL TRIM() function

Pictorial presentation of postgresql trim function

Example: PostgreSQL TRIM() function:

In the example below, the leading and trailing spaces have removed from the given string and gets the result 'w3resource'. Notice that, here we have not mentioned the removing position and removing string, so by default trim function removes white spaces from both the side of the string.

Code:

SELECT trim(from '   w3resource   ');

Sample Output:

   btrim
------------
 w3resource
(1 row)

Here is another example:

In the example below shows that, the trailing characters 'st' have removed from the given string.

Code:

SELECT trim(trailing 'st' from 'tetew3resourcestst');

Sample Output:

     rtrim
----------------
 tetew3resource
(1 row)

PostgreSQL TRIM() function using Column:

Sample Table: employees.


If we want to display the employee_id, first name, and the first_name after trim trailing string for those employees who belongs to the department which department_id is 100 from employees table , the following SQL can be executed:

Code:

SELECT employee_id,first_name,
trim(trailing 'el' from first_name) "Remove trailing string"
FROM employees
WHERE department_id=100;

Sample Output:

 employee_id | first_name  | Remove trailing string
-------------+-------------+------------------------
         108 | Nancy       | Nancy
         109 | Daniel      | Dani
         110 | John        | John
         111 | Ismael      | Isma
         112 | Jose Manuel | Jose Manu
         113 | Luis        | Luis
(6 rows)

In the above example shows that the trailing string 'el' have been removed from the first_name indicated by the blue color.

Previous: SUBSTRING function
Next: UPPER function



Follow us on Facebook and Twitter for latest update.