SQL Server String RIGHT() Function
SQL Server RIGHT() Function
The SQL Server RIGHT()
function is used to extract a specified number of characters from the right side of a string. This function is useful for string manipulation tasks, such as extracting the last few characters of a string.
Syntax
SELECT RIGHT(string, number_of_characters);
The RIGHT()
function takes two arguments:
string
: The string from which to extract characters.number_of_characters
: The number of characters to extract from the right side of the string.
Example SQL Server RIGHT() Function Queries
Let's look at some examples of SQL Server RIGHT()
function queries:
1. Basic RIGHT() Example
SELECT RIGHT('Hello World', 5) AS result;
This query extracts the last 5 characters from the string 'Hello World'. The result will be:
result
------
World
2. RIGHT() with a Column
SELECT first_name, RIGHT(first_name, 3) AS short_name
FROM employees;
This query extracts the last 3 characters from the first_name
column for each employee. The result will show the first_name
and the extracted substring as short_name
.
3. RIGHT() with a Variable
DECLARE @myString VARCHAR(50);
SET @myString = 'SQL Server';
SELECT RIGHT(@myString, 6) AS result;
This query uses a variable to store a string and then extracts the last 6 characters from it. The result will be:
result
----------
Server
Full Example
Let's go through a complete example that includes creating a table, inserting data, and using the RIGHT()
function.
Step 1: Creating a Table
This step involves creating a new table named example_table
to store some sample data.
CREATE TABLE example_table (
id INT PRIMARY KEY,
description VARCHAR(50)
);
In this example, we create a table named example_table
with columns for id
and description
.
Step 2: Inserting Data into the Table
This step involves inserting some sample data into the example_table
.
INSERT INTO example_table (id, description) VALUES (1, 'Apple');
INSERT INTO example_table (id, description) VALUES (2, 'Banana');
INSERT INTO example_table (id, description) VALUES (3, 'Cherry');
Here, we insert data into the example_table
.
Step 3: Using the RIGHT() Function
This step involves using the RIGHT()
function to extract characters from the description
column.
SELECT id, description, RIGHT(description, 3) AS short_description
FROM example_table;
This query retrieves the id
, description
, and the last 3 characters of the description
column for each row in the example_table
. The result will be:
id description short_description
--- ------------ -----------------
1 Apple ple
2 Banana ana
3 Cherry rry
Conclusion
The SQL Server RIGHT()
function is a powerful tool for extracting a specified number of characters from the right side of a string. Understanding how to use the RIGHT()
function and its syntax is essential for effective string manipulation and data processing in SQL Server.