SQL RIGHT()

The SQL RIGHT() function extracts a specified number of characters from the right side of a given string. This function is useful when you need to retrieve trailing characters from a text field, such as file extensions, codes, or the last few digits of an ID.

The RIGHT() function is widely supported in SQL databases, including SQL Server, MySQL, and PostgreSQL.

In this tutorial, we will go through SQL RIGHT() String function, its syntax, and how to use this function in SQL statements for string operations, with the help of well detailed examples.


Syntax of SQL RIGHT() Function

The basic syntax of the SQL RIGHT() function is:

</>
Copy
RIGHT(string, number_of_characters);

Each part of this syntax has a specific purpose:

  • string: The string from which you want to extract characters.
  • number_of_characters: The number of characters to extract from the right side of the string.

The RIGHT() function returns the specified number of characters from the end of the string.


Setup for Examples: Creating the Database and Table

We’ll create a single files table with fields file_name, user_id, and email to demonstrate the RIGHT() function examples.

1. First, create a new database called company_data:

</>
Copy
CREATE DATABASE company_data;

2. Select the company_data database to work with:

</>
Copy
USE company_data;

3. Create a table named files with the fields file_id, file_name, user_id, and email:

</>
Copy
CREATE TABLE files (
    file_id INT PRIMARY KEY AUTO_INCREMENT,
    file_name VARCHAR(100),
    user_id VARCHAR(10),
    email VARCHAR(100)
);

4. Insert sample data into the files table:

</>
Copy
INSERT INTO files (file_name, user_id, email)
VALUES 
('report.pdf', '101', '[email protected]'),
('invoice.docx', '10234', '[email protected]'),
('summary.txt', '987654', '[email protected]');