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
Release: 2024-12-25 06:39:09
Original
349 people have browsed it

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
Copy after login

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;
Copy after login

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!

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