Getting last value in MySQL group concat?

MySQLMySQLi Database

To get last value in group concat, use SUBSTRING_INDEX(). Let us first create a table −

mysql> create table DemoTable1525
   -> (
   -> ListOfSubjects text
   -> );
Query OK, 0 rows affected (1.13 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1525 values('MongoDB,C');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1525 values('Java,C++,MySQL');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable1525 values('Python,C++,C,Java');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1525;

This will produce the following output −

+-------------------+
| ListOfSubjects    |
+-------------------+
| MongoDB,C         |
| Java,C++,MySQL    |
| Python,C++,C,Java |
+-------------------+
3 rows in set (0.00 sec)

Here is the query to get last value in group_concat() −

mysql> select substring_index(ListOfSubjects,',',-1) as LastValue from DemoTable1525;

This will produce the following output −

+-----------+
| LastValue |
+-----------+
| C         |
| MySQL     |
| Java      |
+-----------+
3 rows in set (0.00 sec)
raja
Published on 11-Dec-2019 06:38:06
Advertisements