MySQL: delete all rows containing string “foo” in sample table “bar”?

MySQLMySQLi Database

To delete all rows containing string “foo” in table “bar”, you need to use LIKE operator.

To understand the above syntax, let us create a sample table with name “bar”. The query to create a table is as follows. We will always insert records with string “foo” using INSERT command after creating the below table −

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

Now you can insert some records in the table using insert command. The string “foo” is also added while inserting records. The query is as follows −

mysql> insert into bar(Words) values('Javafoo');
Query OK, 1 row affected (0.14 sec)
mysql> insert into bar(Words) values('fooMySQL');
Query OK, 1 row affected (0.19 sec)
mysql> insert into bar(Words) values('Introductiontofoo C and C++');
Query OK, 1 row affected (0.22 sec)
mysql> insert into bar(Words) values('Introduction to Node.js');
Query OK, 1 row affected (0.19 sec)
mysql> insert into bar(Words) values('Introduction to Hibernate framework');
Query OK, 1 row affected (0.17 sec)

Here is the query to display all records from the table using select statement. The query is as follows −

mysql> select *from bar;

The following is the output −

+----+-------------------------------------+
| Id | Words                               |
+----+-------------------------------------+
|  1 | Javafoo                             |
|  2 | fooMySQL                            |
|  3 | Introductiontofoo C and C++         |
|  4 | Introduction to Node.js             |
|  5 | Introduction to Hibernate framework |
+----+-------------------------------------+
5 rows in set (0.00 sec)

Here is the query to delete all rows containing string “foo” from table “bar” −

mysql> delete from bar where Words like '%foo'
   -> or Words like '%foo%'
   -> or Words like 'foo%';
Query OK, 3 rows affected (0.20 sec)

Now check the table record once again. The query is as follows −

mysql> select *from bar;

The following is the output −

+----+-------------------------------------+
| Id | Words                               |
+----+-------------------------------------+
|  4 | Introduction to Node.js             |
|  5 | Introduction to Hibernate framework |
+----+-------------------------------------+
2 rows in set (0.00 sec)

Now look at the above sample output, all the records containing string “foo” have been deleted from table “bar”.

raja
Published on 26-Feb-2019 12:18:20
Advertisements