Home >Database >Mysql Tutorial >How to Extract the Last Element from a Forward-Slash Separated String in SQL?
Extracting Last Element from Split String in Database
In a table consisting of strings containing multiple elements separated by forward slashes (/), the objective is to extract the last element from each string. For instance, given the following strings:
Articles/Search/ArtMID/2681/ArticleID/2218/Diet.aspx OurStory/MeettheFoodieandtheMD.aspx TheFood/OurMenu.aspx
The desired output should be:
Diet.aspx MeettheFoodieandtheMD.aspx OurMenu.aspx
SQL Approach
To achieve this in SQL, the following query can be employed:
SELECT SUBSTRING( string , LEN(string) - CHARINDEX('/',REVERSE(string)) + 2 , LEN(string) ) FROM SAMPLE;
This query works by:
This approach effectively extracts the last element from each string by reversing the string, locating the last /, and then using these findings to determine the starting point for the substring extraction.
The above is the detailed content of How to Extract the Last Element from a Forward-Slash Separated String in SQL?. For more information, please follow other related articles on the PHP Chinese website!