REVERSE (Transact-SQL)
Returns the reversed character string that is supplied as input.
REVERSE ( string_expression )
Parameters
- string_expression:
- Is a character string or a character data type variable. It can be a constant, variable, or a column that returns a character string. It cannot be a binary data type.
Return Value
Returns Varchar or Nvarchar.
Remarks
The REVERSE function reverses the order of characters in the input string expression. For example, "ABC" becomes "CBA".
The data type of the returned value depends on the data type of the input string_expression.
- If string_expression is a varchar, the return value is varchar.
- If string_expression is a nvarchar, the return value is nvarchar.
- If string_expression is a char, the return value is char.
- If string_expression is a nchar, the return value is nchar.
REVERSE can be useful in various scenarios, such as data validation or manipulating text data.
Examples
Example 1: Reversing a literal string
SELECT REVERSE('SQL Server');
GO
Result:
.revreS LQS
Example 2: Reversing a variable
DECLARE @MyString VARCHAR(50) = 'Transact-SQL';
SELECT REVERSE(@MyString);
GO
Result:
LQS-tca_snarT
Example 3: Reversing a column from a table
Assume a table named Products with a column ProductName.
SELECT ProductName, REVERSE(ProductName) AS ReversedName
FROM Products
WHERE ProductID = 1;
GO
If ProductName for ProductID 1 is 'Chai', the output might look like:
| ProductName | ReversedName |
|---|---|
| Chai | iahC |