In MySQL, you can use the SUBSTRING
and LOCATE
functions to retrieve a specific string from a column in a table.
Here’s how you can use SUBSTRING
and LOCATE
in a SELECT statement:
//syntax
SELECT SUBSTRING(column_name_or_string, LOCATE('string_to_find', column_name_or_string) + LENGTH('string_to_find'), LENGTH(column_name))
FROM table_name
//example
SELECT SUBSTRING('Prefix:31/12/2022 Saturday Suffix:08/01/2023 Sunday', LOCATE('Suffix:', 'Prefix:31/12/2022 Saturday Suffix:08/01/2023 Sunday') + LENGTH('Suffix') + 1) AS Suffix
//output
08/01/2023 Sunday
In this example, column_name_or_string
is the name of the column you want to search, string_to_find
is the string you’re looking for, table_name
is the name of the table, and LENGTH
is a built-in MySQL function that returns the
Use of LOCATE() function on MySql:-
The LOCATE
function in MySQL is used to search for a specified string within a column in a table and returns its position within the column. If the specified string is not found, LOCATE
returns 0.
The basic syntax of the LOCATE
function is as follows:
LOCATE(string_to_find, column_name)
Here, string_to_find
is the string you’re looking for, and column_name
is the name of the column you want to search.
You can use the LOCATE
function in a SELECT
statement to retrieve only the rows where the specified string is found:
SELECT * FROM table_name
WHERE LOCATE('string_to_find', column_name) > 0;
SELECT LOCATE('to', 'string_to_find')
output
8
You can also use LOCATE
in combination with other functions, such as SUBSTRING
, to extract a specific portion of a string based on the position of a substring.