Select first element of a commaseparated list in MySQL?

MySQLMySQLi Database

To select first element of a comma-separated list, you can use SUBSTRING_INDEX(). Let us first create a table:

mysql> create table DemoTable
(
   CSV_Value varchar(200)
);
Query OK, 0 rows affected (0.81 sec)

Following is the query to insert some records in the table using insert command. We have inserted records in the form of comma-separated integer list:

mysql> insert into DemoTable values('10,20,50,80');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('100,21,51,43');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('1,56,103,1090');
Query OK, 1 row affected (0.26 sec)

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

mysql> select *from DemoTable;

This will produce the following output:

+---------------+
| CSV_Value     |
+---------------+
| 10,20,50,80   |
| 100,21,51,43  |
| 1,56,103,1090 |
+---------------+
3 rows in set (0.00 sec)

Following is the query to select first element of a comma-separated list:

mysql> select SUBSTRING_INDEX(CSV_Value,',',1) AS FIRST_ELEMENT from DemoTable;

This will produce the following output. First element of every list is displayed here:

+---------------+
| FIRST_ELEMENT |
+---------------+
| 10            |
| 100           |
| 1             |
+---------------+
3 rows in set (0.03 sec)
raja
Published on 29-Apr-2019 08:03:28
Advertisements