MySQL query to extract last word from a field?

MySQLMySQLi Database

To extract last word from a field, use in-built SUBSTRING_INDEX() function. The syntax is as follows −

SELECT SUBSTRING_INDEX(yourColumnName,’ ‘,-1) as anyVariableName from yourTableName;

To understand the above concept, let us create a table. The following is the query to create a table −

mysql> create table FirstWordDemo
   −> (
   −> AllWords longtext
   −> );
Query OK, 0 rows affected (0.83 sec)

Now insert some words in the table using insert command. The query is as follows −

mysql> insert into FirstWordDemo values('This is the first MySQL Query');
Query OK, 1 row affected (0.11 sec)

mysql> insert into FirstWordDemo values('MySQL is a Relational Database');
Query OK, 1 row affected (0.17 sec)

mysql> insert into FirstWordDemo values('FirstWord is not correct');
Query OK, 1 row affected (0.21 sec)

Now display all records from the table using select statement. The query is as follows −

mysql> select *from FirstWordDemo;

The following is the output −

+--------------------------------+
| AllWords                       |
+--------------------------------+
| This is the first MySQL Query  |
| MySQL is a Relational Database |
| FirstWord is not correct       |
+--------------------------------+
3 rows in set (0.00 sec)

Here is the query to display the last word from a field. We discussed the same syntax in the beginning. The following is the query −

mysql> select SUBSTRING_INDEX(AllWords, ' ', -1) as MyFirstWordResult from FirstWordDemo;

The following is the output −

+-------------------+
| MyFirstWordResult |
+-------------------+
| Query             |
| Database          |
| correct           |
+-------------------+
3 rows in set (0.00 sec)
raja
Published on 11-Jan-2019 13:48:49
Advertisements