How to get left substring in MySQL from a column with file path? Display the entire file path string excluding the file name?

MySQLMySQLi Database

To get the left substring, use LEFT() along with substring_index(). For example, let’s say the file path is −

“/MyFile/JavaProgram/Hello.java “

Here, we will see how to display the entire file path except for the file name i.e. −

/MyFile/JavaProgram/

Let us first create a table −

mysql> create table DemoTable
(
   FileLocation text
);
Query OK, 0 rows affected (0.57 sec

Insert some records in the table using insert command −

mysql> insert into DemoTable values('/MyFile/JavaProgram/Hello.java');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable values('/C/AllPrograms/animation.gif');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('/E/FavFile/ChatProgram.java');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------------------------+
| FileLocation                   |
+--------------------------------+
| /MyFile/JavaProgram/Hello.java |
| /C/AllPrograms/animation.gif   |
| /E/FavFile/ChatProgram.java    |
+--------------------------------+
3 rows in set (0.00 sec)

Following is the query to get left substring in MySQL −

mysql> select left(FileLocation,char_length(FileLocation)-char_length(substring_index(FileLocation,'/',-1))) from DemoTable;

This will produce the following output −

+------------------------------------------------------------------------------------------------+
| left(FileLocation,char_length(FileLocation)-char_length(substring_index(FileLocation,'/',-1))) |
+------------------------------------------------------------------------------------------------+
| /MyFile/JavaProgram/                                                                           |
| /C/AllPrograms/                                                                                |
| /E/FavFile/                                                                                    |
+------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 30-Sep-2019 07:39:04
Advertisements