Home > Database > Mysql Tutorial > How Can I Extract the Last Element from a Slash-Separated String in SQL?

How Can I Extract the Last Element from a Slash-Separated String in SQL?

Susan Sarandon
Release: 2025-01-05 22:13:43
Original
771 people have browsed it

How Can I Extract the Last Element from a Slash-Separated String in SQL?

Retrieving Last Element from a String

In a scenario where a table contains values separated by slashes, it becomes necessary to extract the last element of each string. To accomplish this, we delve into the realm of SQL.

For this particular task, we introduce a powerful function: SUBSTRING. This function allows us to extract a portion of a string based on the specified starting position and length.

The key here lies in determining the starting position of the last element. We leverage the CHARINDEX function to find the position of the last slash in the reverse of the string. Subtracting this position from the length of the string gives us the starting point.

Putting it all together, we construct the following SQL query:

SELECT SUBSTRING(string, LEN(string) - CHARINDEX('/', REVERSE(string)) + 2, LEN(string))
FROM SAMPLE;
Copy after login

This query effectively extracts the substring starting from the position after the last slash and ending at the end of the string. The end result is a table containing the desired last elements:

Diet.aspx
MeettheFoodieandtheMD.aspx
OurMenu.aspx
Copy after login

To demonstrate this functionality, we provide an interactive JSFiddle at http://sqlfiddle.com/#!3/41ead/11.

The above is the detailed content of How Can I Extract the Last Element from a Slash-Separated String in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template