PostgreSQL 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.
trim([leading|trailing|both] <removing_string> from <main_string>)
|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
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.
SELECT trim(from ' w3resource ');
btrim ------------ w3resource (1 row)
Here is another example:
In the example below shows that, the trailing characters 'st' have removed from the given string.
SELECT trim(trailing 'st' from 'tetew3resourcestst');
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:
SELECT employee_id,first_name, trim(trailing 'el' from first_name) "Remove trailing string" FROM employees WHERE department_id=100;
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.
Many of our valued users post comments along with piece of code. Disqus may, false positively, consider those piece of code as Bad or Starnge syntax and send those comments to spam automatically. Even if that happens, we will make sure those useful comments are taken out of spam and approved. It may take a couple of days for that though, but any useful comment will be brought to public view for sure. We regret if that happend to any user. You may write us directly regarding this to - w3resource[at]yahoo[dot]com.