Tuesday, 30 July 2019

How the RIGHT() Function Works in MySQL

In MySQL, the RIGHT() function returns the rightmost characters from a string. The number of characters returned is determined by the second argument.

Syntax

The syntax goes like this:
RIGHT(str,len)
Where str is the string that contains the substring you need to return, and len is the number of characters from the right you want returned.

Example 1 – Basic Usage

Here’s an example where I select the last 2 characters from a string:
SELECT RIGHT('Forest', 2) AS Result;
Result:
+--------+
| Result |
+--------+
| st     |
+--------+

Example 2 – Spaces

The function returns any spaces within the string (and includes them in its calculation). For example, if I add a trailing space to the previous example, here’s the result:
SELECT RIGHT('Forest ', 2) AS Result;
Result:
+--------+
| Result |
+--------+
| t      |
+--------+
If this is problematic for you, you can always use the TRIM() function to remove the space.
SELECT RIGHT(TRIM('Forest '), 2) AS Result;
Result:
+--------+
| Result |
+--------+
| st     |
+--------+

Example 3 – Database Query

Here’s an example of how this function might look within a database query:
USE Music;
SELECT 
    ArtistName AS Original, 
    RIGHT(ArtistName, 3) AS Modified
FROM Artists
LIMIT 5;
Result:
+------------------+----------+
| Original         | Modified |
+------------------+----------+
| Iron Maiden      | den      |
| AC/DC            | /DC      |
| Allan Holdsworth | rth      |
| Buddy Rich       | ich      |
| Devin Townsend   | end      |
+------------------+----------+
In this example, we get the last 3 characters from the ArtistName column and compare it to the original string.

Example 4 – NULL Arguments

The function returns NULL if any of the arguments is NULL. Here’s an example where the first argument is NULL:
SELECT RIGHT(NULL, 5) AS Result;
Result:
+--------+
| Result |
+--------+
| NULL   |
+--------+
And here’s an example where the second argument is NULL:
SELECT RIGHT('Forest', NULL) AS Result;
Result:
+--------+
| Result |
+--------+
| NULL   |
+--------+

0 comments:

Post a Comment