MySQL query to get substrings (only the last three characters) from strings?

MySQLMySQLi Database

For this, you can use SUBSTR() method. 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 the last three characters from every string:

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)
raja
Published on 29-Apr-2019 08:43:20
Advertisements