Description
The SQL RIGHT function returns the specified number of rightmost characters of a given character expression. The rightmost characters are those at the “end” of the string.
SQL RIGHT Usage Notes
- The character expression as the first argument of the RIGHT function can be a constant string, a variable string, or a database column.
- Length as the second argument of the SQL RIGHT function, is a positive integer value. If the value is negative, an error returns.
- If the data type of character expression value is non-Unicode, the RIGHT function returns a varchar data type value. In the case of Unicode data type, it returns nvarchar data type value.
Syntax
RIGHT(character_expression, length)
SQL RIGHT Examples
We will use the AdventureWorks2019 database for all the examples.
The following example returns the given number of characters starting from the right side of the input character string.
The query returns ‘right’ as the rightmost five characters in the literal string.
In the second example, we pass the LastName column of the Person table as our first argument. The SQL RIGHT function returns the rightmost five characters of each LastName column value.
Next, let’s use SQL RIGHT with a group by clause. We select the rightmost characters of a shopping cart ID. We group these values and order by the total quantity of products against each group of shopping cart ID.
The query returns shopping cart Id values grouped by the rightmost six characters. Notice, that we repeat the RIGHT function in the SELECT and GROUP BY.
The order by clause shows the total product quantity against each group of shopping cart Ids.