MySQL query to delete table rows if string in cell is matched

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100)
);
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('John Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name) values('Carol Taylor');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name) values('John Doe');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Name) values('Chris Brown');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name) values('John Brown');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------------+
| Id | Name         |
+----+--------------+
|  1 | John Smith   |
|  2 | Carol Taylor |
|  3 | John Doe     |
|  4 | Chris Brown  |
|  5 | John Brown   |
+----+--------------+
5 rows in set (0.00 sec)

Following is the query to delete table rows if the string in a cell is matched −

mysql> delete from DemoTable where Name like '%ohn%';
Query OK, 3 rows affected (0.16 sec)

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------------+
| Id | Name         |
+----+--------------+
|  2 | Carol Taylor |
|  4 | Chris Brown  |
+----+--------------+
2 rows in set (0.00 sec)
raja
Published on 25-Sep-2019 12:26:41
Advertisements