Computer >> Computer tutorials >  >> Programming >> MySQL

MySQL command-line tool: How to find out number of rows affected by a DELETE?


You can use row_count() at the end for this. Let us first create a table −

mysql> create table rowAfftectedByDeleteDemo
   -> (
   -> CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> CustomerName varchar(20)
   -> );
Query OK, 0 rows affected (0.86 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Carol');
Query OK, 1 row affected (0.10 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Bob');
Query OK, 1 row affected (0.09 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Sam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('David');
Query OK, 1 row affected (0.08 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Maxwell');
Query OK, 1 row affected (0.09 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Ramit');
Query OK, 1 row affected (0.08 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('James');
Query OK, 1 row affected (0.10 sec)

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

mysql> select *from rowAfftectedByDeleteDemo;

Here is the output −

+------------+--------------+
| CustomerId | CustomerName |
+------------+--------------+
| 1          | John         |
| 2          | Carol        |
| 3          | Bob          |
| 4          | Sam          |
| 5          | David        |
| 6          | Maxwell      |
| 7          | Ramit        |
| 8          | James        |
+------------+--------------+
8 rows in set (0.00 sec)

Before deleting rows from the table, the value of row_count() is as follows −

mysql> select row_count();

Here is the output −

+-------------+
| row_count() |
+-------------+
| -1          |
+-------------+
1 row in set (0.00 sec)

The following is the query to delete rows from the table −

mysql> delete from rowAfftectedByDeleteDemo where CustomerId =3 || CustomerId =4 || CustomerId =5 || CustomerId =6;
Query OK, 4 rows affected (0.13 sec)

After deleting rows from the table, the value of row_count() is as follows −

mysql> select row_count();

Here is the output −

+-------------+
| row_count() |
+-------------+
| 4           |
+-------------+
1 row in set (0.00 sec)