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

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



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)
Updated on: 2019-07-30T22:30:25+05:30

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements