MySQL POSITION() Function
The POSITION()
function in MySQL helps you find where a substring is located within a larger string. It's a handy tool for working with text data and extracting specific parts of strings.
POSITION(): Definition and Usage
POSITION()
searches for a substring within a string and returns its starting position. If the substring is not found, it returns 0. The search is case-insensitive. This function is identical to the `LOCATE()` function.
Syntax
Syntax
POSITION(substring IN string)
Parameter Values
Parameter | Description |
---|---|
substring |
The substring to search for. This is required. |
string |
The string to search within. This is required. |
Examples
Finding the Position of a Substring
This example finds the position of "3" in "W3Schools.com".
Syntax
SELECT POSITION("3" IN "W3Schools.com") AS MatchPosition;
Output
3
Finding the Position of Another Substring
This example searches for "COM" (case-insensitive match).
Syntax
SELECT POSITION("COM" IN "W3Schools.com") AS MatchPosition;
Output
10
Finding the Position of a Substring in a Column
This searches for "a" in the `CustomerName` column of the `Customers` table (assuming a `Customers` table with a `CustomerName` column exists).
Syntax
SELECT POSITION("a" IN CustomerName)
FROM Customers;
Output
(The position of the first 'a' in each CustomerName will be returned. 0 if 'a' is not present.)