MySQL search if more than one string contains special characters?n



To search if strings contain special characters, you can use REGEXP. Following is the syntax −

select * from yourTableName
where yourColumnName REGEXP '[^a-zA-Z0-9]';

Let us first create a table −

mysql> create table specialCharactersDemo
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert records in the table using insert command. Following is the query −

mysql> insert into specialCharactersDemo values('STU_1234');
Query OK, 1 row affected (0.15 sec)
mysql> insert into specialCharactersDemo values('STU567');
Query OK, 1 row affected (0.14 sec)
mysql> insert into specialCharactersDemo values('STU#1234');
Query OK, 1 row affected (0.13 sec)
mysql> insert into specialCharactersDemo values('STU897$');
Query OK, 1 row affected (0.18 sec)
mysql> insert into specialCharactersDemo values('STU999');
Query OK, 1 row affected (0.43 sec)
mysql> insert into specialCharactersDemo values('STU1010');
Query OK, 1 row affected (0.14 sec

Following is the query to display all records from the table using select statement −

mysql> select *from specialCharactersDemo;

This will produce the following output −

+-----------+
| StudentId |
+-----------+
| STU_1234  |
| STU567    |
| STU#1234  |
| STU897$   |
| STU999    |
| STU1010   |
+-----------+
6 rows in set (0.00 sec)

Here is the query to search if a string contains special characters −

mysql> select *from specialCharactersDemo
   -> where StudentId REGEXP '[^a-zA-Z0-9]';

This will produce the following output −

+-----------+
| StudentId |
+-----------+
| STU_1234  |
| STU#1234  |
| STU897$   |
+-----------+
3 rows in set (0.02 sec)

You can use another syntax for the above result. Following is the query −

mysql> select *from specialCharactersDemo
   -> where StudentId REGEXP'[^[:alnum:]]';

This will produce the following output −

+-----------+
| StudentId |
+-----------+
| STU_1234  |
| STU#1234  |
| STU897$   |
+-----------+
3 rows in set (0.05 sec)

Advertisements