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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 06:39:09356browse

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

Partitioning Strings to Acquire Terminal Elements

Question:

In a data table containing strings such as:

Articles/Search/ArtMID/2681/ArticleID/2218/Diet.aspx
OurStory/MeettheFoodieandtheMD.aspx
TheFood/OurMenu.aspx

How can we isolate and extract the final element (e.g., "Diet.aspx", "MeettheFoodieandtheMD.aspx", "OurMenu.aspx") from each string?

Answer:

In SQL, this can be achieved using the following syntax:

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

Explanation:

  • LEN(string): Determines the length of the input string.
  • REVERSE(string): Reverses the string to make it easier to locate the last occurrence of the forward slash (/).
  • CHARINDEX('/', REVERSE(string)): Finds the position of the last forward slash in the reversed string.
  • LEN(string) - CHARINDEX('/', REVERSE(string)) 2: Calculates the starting position of the substring, excluding the forward slash.
  • SUBSTRING(string, starting position, length): Extracts the desired substring from the input string.

Here's a JSFiddle for reference: http://sqlfiddle.com/#!3/41ead/11

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

Statement:
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