Find rows where column value ends with a specific substring in MySQL?


To find rows and update with new value where column value ends with specific substring you need to use LIKE operator.

The syntax is as follows:

UPDATE yourTableName
SET yourColumnName=’yourValue’
WHERE yourColumnName LIKE ‘%.yourString’;

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

mysql> create table RowEndsWithSpecificString
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> FileName varchar(30),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.50 sec)

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

mysql> insert into RowEndsWithSpecificString(FileName) values('MergeSort.c');
Query OK, 1 row affected (0.11 sec)
mysql> insert into RowEndsWithSpecificString(FileName) values('BubbleSortIntroduction.pdf');
Query OK, 1 row affected (0.25 sec)
mysql> insert into RowEndsWithSpecificString(FileName) values('AllMySQLQuery.docx');
Query OK, 1 row affected (0.18 sec)
mysql> insert into RowEndsWithSpecificString(FileName) values('JavaCollections.pdf');
Query OK, 1 row affected (0.16 sec)
mysql> insert into RowEndsWithSpecificString(FileName) values('JavaServlet.pdf');
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 RowEndsWithSpecificString;

The following is the output:

+----+----------------------------+
| Id | FileName                   |
+----+----------------------------+
|  1 | MergeSort.c                |
|  2 | BubbleSortIntroduction.pdf |
|  3 | AllMySQLQuery.docx         |
|  4 | JavaCollections.pdf        |
|  5 | JavaServlet.pdf            |
+----+----------------------------+
5 rows in set (0.00 sec)

Here is the query to find and update where column value ends with specific substring. The following query finds a substring that ends with ‘.docx’ and updates with a new substring which is ‘.pdf’. The query is as follows:

mysql> update RowEndsWithSpecificString
   -> set FileName='IntroductionToCoreJava.pdf'
   -> where FileName LIKE '%.docx';
Query OK, 1 row affected (0.14 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Now check the table records once again. The query is as follows:

mysql> select *from RowEndsWithSpecificString;

The following is the output:

+----+----------------------------+
| Id | FileName                   |
+----+----------------------------+
|  1 | IntroductionToCoreJava.pdf |
|  2 | BubbleSortIntroduction.pdf |
|  3 | IntroductionToCoreJava.pdf |
|  4 | JavaCollections.pdf        |
|  5 | JavaServlet.pdf            |
+----+----------------------------+
5 rows in set (0.00 sec)

Updated on: 30-Jul-2019

899 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements