MySQL query to get a substring from a string except the last three characters?


For this, you can use SUBSTR along with length().

Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20)
   );
Query OK, 0 rows affected (1.31 sec)

Following is the query to insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Carol');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.17 sec)

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

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1  | John      |
| 2  | Carol     |
| 3  | Robert    |
| 4  | Chris     |
| 5  | David     |
+----+-----------+
5 rows in set (0.00 sec)

Following is the query to get a substring removing the last 3 characters −

mysql> select substr(FirstName,1,length(FirstName)-3) from DemoTable;

This will produce the following output −

+-----------------------------------------+
| substr(FirstName,1,length(FirstName)-3) |
+-----------------------------------------+
| J                                       |
| Ca                                      |
| Rob                                     |
| Ch                                      |
| Da                                      |
+-----------------------------------------+
5 rows in set (0.00 sec)

To get same output, you can use following alternate query −

mysql> select left(FirstName,length(FirstName)-3) from DemoTable;

This will produce the following output −

+-------------------------------------+
| left(FirstName,length(FirstName)-3) |
+-------------------------------------+
| J                                   |
| Ca                                  |
| Rob                                 |
| Ch                                  |
| Da                                  |
+-------------------------------------+
5 rows in set (0.00 sec)

To get last three characters, you can use the following query −

mysql> select substr(FirstName,-3) from DemoTable;

This will produce the following output −

+----------------------+
| substr(FirstName,-3) |
+----------------------+
| ohn                  |
| rol                  |
| ert                  |
| ris                  |
| vid                  |
+----------------------+
5 rows in set (0.00 sec)

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

500 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements