Select first word in a MySQL query?


To select first word in MySQL query, you can use SUBSTRING_INDEX().

 Following is the syntax −

select substring_index(yourColumnName,' ',1) as anyAliasName from yourTableName;

Let us first create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFullName varchar(40)
);
Query OK, 0 rows affected (0.61 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable(StudentFullName) values('John Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentFullName) values('Carol Taylor');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentFullName) values('Bob Williams');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentFullName) values('David Miller');
Query OK, 1 row affected (0.16 sec)

Display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-----------------+
| StudentId | StudentFullName |
+-----------+-----------------+
| 1         | John Smith      |
| 2         | Carol Taylor    |
| 3         | Bob Williams    |
| 4         | David Miller    |
+-----------+-----------------+
4 rows in set (0.00 sec)

Following is the query to select first word in MySQL query −

mysql> select substring_index(StudentFullName,' ',1) as FirstWord from DemoTable;

This will produce the following output displaying the first word −

+-----------+
| FirstWord |
+-----------+
| John      |
| Carol     |
| Bob       |
| David     |
+-----------+
4 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements