Find rows with a match in a pipe delimited column with MySQL

MySQLMySQLi Database

To find a match, use regular expressions in MySQL. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value varchar(60)
   -> );
Query OK, 0 rows affected (0.48 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('8|56|78|45');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values('9876');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('98|8');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('3|8|9');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('97|94');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('103|104|110|8|97');
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 −

+------------------+
| Value            |
+------------------+
| 8|56|78|45       |
| 9876             |
| 98|8             |
| 3|8|9            |
| 97|94            |
| 103|104|110|8|97 |
+------------------+
6 rows in set (0.00 sec)

Here is the query to find rows with a match in a pipe-delimited column −

mysql> select *from DemoTable
   -> where Value regexp '\\|8\\|';

This will produce the following output −

+------------------+
| Value            |
+------------------+
| 3|8|9            |
| 103|104|110|8|97 |
+------------------+
2 rows in set (0.00 sec)
raja
Updated on 13-Dec-2019 06:14:20

Advertisements