How to use the BTRIM() function in SQL
Overview
The BTRIM() function is used to trim all the specified characters in the string_trim argument from the beginning and the end of the given string.
Syntax
STRPOS(string,string_trim)
Note: If the
string_trimargument is not specified, the leading and trailing space is removed.
Parameter
string: This represents the string to be searched.string_trim: This represents the characters to be removed.
Example
Let’s assume we have a dataset called Writer, and it contains information about several writers’ names, genders, and the states in which they were born.
However, when we fetch the data from the database, we notice that a string back and kacb has been added to the writers’ names.
How do we solve this problem?
Well, we can solve this problem using the BTRIM function.
The following code shows how we can do this:
CREATE TABLE Writer (id int,name varchar(50),gender varchar(10),state varchar(15));-- Insert dataINSERT INTO WriterVALUES (01,'backSharon Pellerkacb','Female','Kogi');INSERT INTO WriterVALUES (02,'backPaul Donskacb','Male','Lagos');INSERT INTO WriterVALUES (03,'backAmeera Abedayokacb','Female','Imo');INSERT INTO WriterVALUES (04,'backMaria Elijahkacb','Female','Lagos');INSERT INTO WriterVALUES (05,'backDavid Hassankacb','Male','Abuja');INSERT INTO WriterVALUES (06,'backNiniola Disukacb','Female','Lagos');INSERT INTO WriterVALUES (08,'backJoe Smithkacb','Male','Lagos');-- QuerySELECT id, name, BTRIM(name, 'back') AS new_name, genderFROM Writer;
Explanation
In the code above:
- Lines 1–7: We create a table called
Writerwith the columnsid,name,gender, andstate. - Lines 11–21: We insert data into the
Writertable. - Lines 24–26: We remove the string appended to each name in the
namecolumn using theBTRIM()function. Finally, we display the result.