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.

SELECT RIGHT('first 5 characters from the right', 5) outputstring;
/* Answer */
SELECT RIGHT('first 5 characters from the right', 5) outputstring;

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.

SELECT RIGHT(LastName, 5) LastName FROM Person.Person
/* Answer */
SELECT RIGHT(LastName, 5)  LastName 
FROM Person.Person

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.

SELECT RIGHT(ShoppingCartID, 6) ShoppingCartID, SUM (Quantity) TotalProductQuantity FROM Sales.ShoppingCartItem GROUP BY RIGHT(ShoppingCartID, 6) ORDER BY TotalProductQuantity asc;
/* Answer */
SELECT   RIGHT(ShoppingCartID, 6) ShoppingCartID,
         SUM (Quantity)  TotalProductQuantity
FROM     Sales.ShoppingCartItem
GROUP BY RIGHT(ShoppingCartID, 6)
ORDER BY TotalProductQuantity asc;

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.

Next Steps

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Are YOU READY TO START LEARNING SQL SERVER, BUT DON'T KNOW WHERE TO START?

Nothing is worse than, being excited to learn a new tool but not knowing where to start, wasting time learning the wrong features, and being overwhelmed .

But it doesn't have to be this way.

I'm Putting together a free email course to help you get started learning SQL Server.

Name*
Email*
>