MySQL String Last Index Of in a URL?


To get the last index, use the SUBSTRING_INDEX() function from MySQL. The syntax is as follows −

SELECT yourColumnName1,...N,SUBSTRING_INDEX(yourColumnName,’yourDelimiter’,-1)as anyVariableName from yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table LastIndexString
   -> (
   -> Id int,
   -> yourURL text
   -> );
Query OK, 0 rows affected (0.89 sec)

Insert some records in the table using INSERT command. The query is as follows −

mysql> insert into LastIndexString values(1,'https −//www.example.com/home.html');
Query OK, 1 row affected (0.26 sec)

mysql> insert into LastIndexString values(2,'https −//exampledemo.example.com/index.jsp');
Query OK, 1 row affected (0.18 sec)

mysql> insert into LastIndexString values(3,'https −//www.example.com/question/LastString');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using SELECT statement. The query is as follows −

mysql> select *from LastIndexString;

The following is the output displaying URL string −

+------+---------------------------------------------+
| Id   | yourURL                                     |
+------+---------------------------------------------+
| 1    | https −//www.example.com/home.html          |
| 2    | https −//exampledemo.example.com/index.jsp  |
| 3    | https −//www.example.com/question/LastString|
+------+---------------------------------------------+
3 rows in set (0.00 sec)

Here is the query to get the last index string from a URL string −

mysql> select Id, substring_index(yourURL,'/',-1) as LastStringFromURL from LastIndexString;

The following is the output displaying the part of the URL −

+------+-------------------+
| Id   | LastStringFromURL |
+------+-------------------+
|    1 | home.html         |
|    2 | index.jsp         |
|    3 | LastString        |
+------+-------------------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements