- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select first element of a commaseparated list in MySQL?
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)
Advertisements