- Trending Categories
- 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
MySQL query to extract first word from a field?
To extract first word from a field, use in-built SUBSTRING_INDEX() function. The syntax is as follows −
SELECT SUBSTRING_INDEX(yourColumnName,’ ‘,1) as anyVariableName from yourTableName;
In the above query, if you use -1 in place of 1 then you will get the last word. 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 get first 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 | +-------------------+ | This | | MySQL | | FirstWord | +-------------------+ 3 rows in set (0.00 sec)
Advertisements