How to Use the RIGHT() Function in MySQL
![](https://plantpot.works/wp-content/uploads/2021/08/9150.png)
Contents
In this article, you will learn how to use the RIGHT() function in MySQL.
Using the RIGHT() function in MySQL
In MySQL, the RIGHT() function is used to extract a specified number of characters from the end of a string.
Syntax
RIGHT(str, length);
Examples
Here are some examples of using the RIGHT() function in MySQL:
Extracting the last N characters of a string
To extract the last N characters of a string, you can use the RIGHT() function.
Syntax
SELECT RIGHT(str, length);
Example
SELECT RIGHT('Hello World', 5);
Output:
+------------------------+
| RIGHT('Hello World', 5)|
+------------------------+
| World |
+------------------------+
In this example, the RIGHT() function returns the last 5 characters of the string ‘Hello World’, which are ‘World’.
Extracting the last N characters of a column value
You can also use the RIGHT() function to extract the last N characters of a column value.
Syntax
SELECT RIGHT(column_name, length) FROM table_name;
Example
SELECT RIGHT(name, 3) FROM employees;
Output:
+--------------+
| RIGHT(name, 3)|
+--------------+
| ohn |
| nn |
| ich |
| ara |
+--------------+
In this example, the RIGHT() function returns the last 3 characters of the name column in the employees table.
Using the last N characters of a string in a WHERE clause
You can use the RIGHT() function in a WHERE clause to filter records based on the last N characters of a string.
Syntax
SELECT * FROM table_name WHERE RIGHT(column_name, length) = string_value;
Example
SELECT * FROM employees WHERE RIGHT(name, 3) = 'ohn';
Output:
+----+------+--------+------------+
| id | name | salary | hire_date |
+----+------+--------+------------+
| 1 | John | 50000 | 2020-01-01 |
+----+------+--------+------------+
In this example, the SELECT statement returns all the records from the employees table where the last 3 characters of the name column are equal to ‘ohn’.