How to extract part of a URL in MySQL?

MySQLMySQLi Database

You need to use SUBSTRING_INDEX() function from MySQL to extract part of a URL.

 Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   URL text
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(URL) values('https:\\www.example.com\\homepage');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable(URL) values('https:\\www.onlinetest.com\\welcome\\indexpage');
Query OK, 1 row affected (0.12 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output. Here, we can only a slash is visible because internally MySQL removes one slash in result −

+----+---------------------------------------------+
| Id | URL                                         |
+----+---------------------------------------------+
| 1  | https:\www.example.com\homepage             |
| 2  | https:\www.onlinetest.com\welcome\indexpage |
+----+---------------------------------------------+
2 rows in set (0.00 sec)

Following is the query to extract part of a URL in MySQL −

mysql> select substring_index(URL,'\\',-1) from DemoTable;

This will produce the following output −

+------------------------------+
| substring_index(URL,'\\',-1) |
+------------------------------+
| homepage                     |
| indexpage                    |
+------------------------------+
2 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 07:18:33
Advertisements