Search for text between delimiters in MySQL?

MySQLMySQLi Database

You need to use LOCATE() along with SUBSTR(). The below syntax will find the word after delimiter. Here, delimiter is colon(:), you can use another i.e. it is up to you. The syntax is as follows −

SELECT
   SUBSTR(yourColumnName,
      LOCATE(':',yourColumnName)+1,
         (CHAR_LENGTH(yourColumnName) - LOCATE(':',REVERSE(yourColumnName)) - LOCATE(':',yourColumnName))) AS anyAliasName
FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table SearchTextBetweenDelimitersDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Words longtext,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.67 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into SearchTextBetweenDelimitersDemo(Words) values('Object:Oriented:Programming');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SearchTextBetweenDelimitersDemo(Words) values('C++:Java:C#');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SearchTextBetweenDelimitersDemo(Words) values('SQLServer:MySQL:Oracle');
Query OK, 1 row affected (0.17 sec)
mysql> insert into SearchTextBetweenDelimitersDemo(Words) values('SQL SQLServer:MySQL:Oracle');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from SearchTextBetweenDelimitersDemo;

The following is the output −

+----+-----------------------------+
| Id | Words                       |
+----+-----------------------------+
|  1 | Object:Oriented:Programming |
|  2 | C++:Java:C#                 |
|  3 | SQLServer:MySQL:Oracle      |
|  4 | SQL SQLServer:MySQL:Oracle  |
+----+-----------------------------+
4 rows in set (0.00 sec)

Here is the query to search and show words between delimiters −

mysql> SELECT
   -> SUBSTR(Words,
   -> LOCATE(':',Words)+1,
   -> (CHAR_LENGTH(Words) - LOCATE(':',REVERSE(Words)) - LOCATE(':',Words))) AS Text
   -> FROM SearchTextBetweenDelimitersDemo;

The following is the output −

+----------+
| Text     |
+----------+
| Oriented |
| Java     |
| MySQL    |
| MySQL    |
+----------+
4 rows in set (0.00 sec)
raja
Published on 26-Feb-2019 15:26:12
Advertisements