MySQL SUBSTR() Function

The SUBSTR() function in MySQL extracts a portion (substring) of a string, starting at a specified position and continuing for a given length. It's a fundamental tool for working with and manipulating text data.



SUBSTR(): Definition and Usage

SUBSTR() allows you to select specific parts of strings. You specify the starting position and the length of the substring you want to extract. MySQL's SUBSTR() function is equivalent to SUBSTRING() and MID().

Understanding Starting Positions

The starting position is 1-based, meaning the first character is at position 1. You can also use negative numbers to count from the end of the string (-1 is the last character).

Position Character
1S
2Q
3L
4
5T
6u
7t
8o
9r
10i
11a
12l
-12S
-11Q
-10L
-9
-8T
-7u
-6t
-5o
-4r
-3i
-2a
-1l

Syntax

Syntax

SUBSTR(string, start, length)
--or--
SUBSTR(string FROM start FOR length)
      

Parameter Values

Parameter Description
string The string to extract from. This is required.
start The starting position (1-based index, can be positive or negative). This is required.
length (Optional) The number of characters to extract. If omitted, the rest of the string from the start position is returned.

Examples

Extracting a Substring from the Beginning

This extracts three characters starting from position 5 ("Tut").

Syntax

SELECT SUBSTR("SQL Tutorial", 5, 3) AS ExtractString;
      
Output

Tut
      

Extracting a Substring from a Column

Extracting five characters from the 'CustomerName' column, starting at position 2 (assuming a 'Customers' table with a 'CustomerName' column).

Syntax

SELECT SUBSTR(CustomerName, 2, 5) AS ExtractString
FROM Customers;
      
Output

ExtractString
-------------
(A substring from each CustomerName will be displayed here)
      

Extracting a Substring from the End

Extracting five characters from the end of the string.

Syntax

SELECT SUBSTR("SQL Tutorial", -5, 5) AS ExtractString;
      
Output

orial
      

**Note:** The output for the second example will vary depending on the data in your `Customers` table. Each row will display a five-character substring starting from the second character of the `CustomerName` in that row.