SQL SUBSTRING()

The SQL SUBSTRING() function extracts a portion of a string, starting from a specified position for a specified length.

The SUBSTRING() function is useful for retrieving parts of text fields, such as splitting codes, extracting specific words, or manipulating substrings within data.

The SUBSTRING() function is supported by SQL Server, MySQL, PostgreSQL, and other major SQL databases.

In this tutorial, we will go through SQL SUBSTRING() 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 SUBSTRING() Function

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

</>
Copy
SUBSTRING(string, start, length);

Each part of this syntax has a specific purpose:

  • string: The original string from which you want to extract a substring.
  • start: The starting position (1-based) for extracting the substring.
  • length: The number of characters to extract from the starting position.

The SUBSTRING() function returns the specified portion of the string based on the start and length values.


Examples: Using SUBSTRING() in SQL Queries

We’ll go through examples demonstrating the SUBSTRING() function in SQL. These examples show how to extract specific parts of strings without using any additional functions.


1 Extracting Specific Characters from an Email Address

To extract the first five characters from an email address:

</>
Copy
SELECT SUBSTRING('[email protected]', 1, 5) AS first_part;

This query returns “user@” as it extracts the first five characters of the email address.