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 |
---|---|
1 | S |
2 | Q |
3 | L |
4 | |
5 | T |
6 | u |
7 | t |
8 | o |
9 | r |
10 | i |
11 | a |
12 | l |
-12 | S |
-11 | Q |
-10 | L |
-9 | |
-8 | T |
-7 | u |
-6 | t |
-5 | o |
-4 | r |
-3 | i |
-2 | a |
-1 | l |
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