MySQL query to check if a certain row has only two words?

MySQLMySQLi Database

For this, use Regular Expression in MySQL as in the below syntax −

select * from yourTableName where yourColumnName regexp '^[^ ]+[ ]+[^ ]+$';

The above query will work when the two words are separated by a space. Let us first create a −

mysql> create table DemoTable1412
   -> (
   -> Name varchar(40)
   -> );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1412 values('John Adam Carol');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1412 values('Mike Sam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1412 values('Chris James Robert');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select −

mysql> select * from DemoTable1412;

This will produce the following output −

+--------------------+
| Name               |
+--------------------+
| John Adam Carol    |
| Mike Sam           |
| Chris James Robert |
+--------------------+
3 rows in set (0.00 sec)

Here is the query to check if a certain row has two words separated by space −

mysql> select * from DemoTable1412 where Name regexp '^[^ ]+[ ]+[^ ]+$';

This will produce the following output −

+----------+
| Name     |
+----------+
| Mike Sam |
+----------+
1 row in set (0.00 sec)
raja
Published on 12-Nov-2019 05:13:00
Advertisements