MySQL query to display only the records that contains single word?

MySQLMySQLi Database

For this, you can filter records on the basis of LIKE. Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(50)
);
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Adam Smith');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('David Miller');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+
| Name         |
+--------------+
| John Smith   |
| John         |
| Adam Smith   |
| Carol        |
| David Miller |
+--------------+
5 rows in set (0.00 sec)

Following is the query to display records containing a single word. NOT LIKE is used here to exclude records with more than one word i.e. NOT LIKE '% %' −

mysql> select *from DemoTable where Name not like '% %';

This will produce the following output −

+-------+
| Name  |
+-------+
| John  |
| Carol |
+-------+
2 rows in set (0.00 sec)
raja
Published on 04-Oct-2019 10:45:00
Advertisements