TRIM

TRIM ( [ [ LEADING | TRAILING | BOTH ] [ characters ] FROM ] input_string )

Description

Removes leading and/or trailing characters from a string.

The TRIM function allows you to specify whether to remove characters from the start (LEADING), the end (TRAILING), or both sides (BOTH) of the input string. You can also specify which characters to remove. If no characters are specified, TRIM removes spaces.

Syntax

TRIM ( [ LEADING [ characters ] FROM ] input_string )
TRIM ( [ TRAILING [ characters ] FROM ] input_string )
TRIM ( [ BOTH [ characters ] FROM ] input_string )
TRIM ( input_string )

Parameters

Parameter Description
input_string The string from which to remove characters. This can be of type char, varchar, nchar, nvarchar, text, ntext, or a literal string.
LEADING Specifies that characters should be removed from the beginning of the string.
TRAILING Specifies that characters should be removed from the end of the string.
BOTH Specifies that characters should be removed from both the beginning and the end of the string. This is the default behavior if neither LEADING nor TRAILING is specified.
characters A string literal containing the characters to be removed. If omitted, spaces are removed.

Return Type

Returns the character string after removing specified characters from the specified positions.

Examples

Example 1: Removing Leading and Trailing Spaces

This example shows how to remove leading and trailing spaces from a string.

SELECT TRIM('   Hello World   ');
Hello World

Example 2: Removing Specific Leading Characters

This example removes the characters '-' and ' ' from the beginning of the string.

SELECT TRIM(LEADING '- ' FROM '--   SQL Server is great!');
SQL Server is great!

Example 3: Removing Specific Trailing Characters

This example removes the character '.' from the end of the string.

SELECT TRIM(TRAILING '.' FROM 'This is a sentence....');
This is a sentence

Example 4: Removing Specific Characters from Both Sides

This example removes '*' and '+' characters from both the leading and trailing parts of the string.

SELECT TRIM(BOTH '*+' FROM '**+++Awesome+++**');
Awesome

Example 5: Using TRIM with a Table Column

Assume you have a table named Products with a column ProductName that might have extra spaces.

-- Sample table structure:
-- CREATE TABLE Products (
--     ProductID INT PRIMARY KEY,
--     ProductName VARCHAR(100)
-- );
-- INSERT INTO Products (ProductID, ProductName) VALUES
-- (1, '  Laptop '),
-- (2, 'Keyboard  '),
-- (3, '   Mouse');

SELECT ProductName, TRIM(ProductName) AS CleanedProductName
FROM Products;

ProductName | CleanedProductName

Laptop | Laptop

Keyboard | Keyboard

Mouse | Mouse

Note: The TRIM function in SQL Server is similar to the LTRIM and RTRIM functions. LTRIM removes leading spaces, RTRIM removes trailing spaces, and TRIM can do both or remove specific characters.