How to get substring results from a table with file location recordsi in MySQL?

MySQLMySQLi Database

To fetch sub strings, use the substr() method in MySQL as in the below syntax −

select substr(yourColumnName,startIndex,endIndex) from yourTableName limit anyValue;

select substr(yourColumnName,startIndex+endIndex) from yourTableName limit anyValue;

Let us create a table −

mysql> create table demo11
−> (
−> id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
−> fileLocation text
−> );
Query OK, 0 rows affected (2.60 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo11(fileLocation) values('E:/users/program/sample.sql');
Query OK, 1 row affected (0.15 sec)

mysql> insert into demo11(fileLocation) values('E:/users/data/db.sql');
Query OK, 1 row affected (0.32 sec)

mysql> insert into demo11(fileLocation) values('C:/users/data/sample2.sql');
Query OK, 1 row affected (0.13 sec)

Display records from the table using select statement −

mysql> select *from demo11;

This will produce the following output −

+----+-----------------------------+
| id | fileLocation                |
+----+-----------------------------+
|  1 | E:/users/program/sample.sql |
|  2 | E:/users/data/db.sql        |
|  3 | C:/users/data/sample2.sql   |
+----+-----------------------------+
3 rows in set (0.00 sec)s

Here is the query to get sub string result in multiple lines.

The first part query is as follows −

mysql> select substr(fileLocation,1,15) from demo11 limit 1,2;

This will produce the following output −

+---------------------------+
| substr(fileLocation,1,15) |
+---------------------------+
| E:/users/data/d           |
| C:/users/data/s           |
+---------------------------+
2 rows in set (0.00 sec)

The second part is as follows −

mysql> select substr(fileLocation,16) from demo11 limit 1,2;

This will produce the following output −

+-------------------------+
| substr(fileLocation,16) |
+-------------------------+
| b.sql                   |
| ample2.sql              |
+-------------------------+
2 rows in set (0.00 sec)
raja
Published on 19-Nov-2020 11:10:19
Advertisements