Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many rows were deleted?

Is it possible to check how many rows were deleted by a query?

queryset = MyModel.object.filter(foo=bar)
queryset.delete()
deleted = ...

Or should I use transactions for that?

@transaction.commit_on_success
def delete_some_rows():
    queryset = MyModel.object.filter(foo=bar)
    deleted = queryset.count()
    queryset.delete()

PHP + MySQL example:

mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
like image 246
Tomasz Wysocki Avatar asked Jul 27 '10 09:07

Tomasz Wysocki


People also ask

How can I get the number of rows deleted in SQL Server?

Usage. SQL Server @@ROWCOUNT is a system variable that is used to return the number of rows that are affected by the last executed statement in the batch.

What is delete row?

Deleting a row is the third way to modify a ResultSet object, and it is the simplest. All you do is move the cursor to the row you want to delete and then call the method deleteRow . For example, if you want to delete the fourth row in the ResultSet uprs , your code will look like this: uprs. absolute(4); uprs.

What is @@ rowcount?

Data manipulation language (DML) statements set the @@ROWCOUNT value to the number of rows affected by the query and return that value to the client. The DML statements may not send any rows to the client.

How do I see how many rows affected in SQL?

In SQL Server, you can use the @@ROWCOUNT system function to return the number of rows affected by the last T-SQL statement. For example, if a query returns 4 rows, @@ROWCOUNT will return 4.


1 Answers

There are many situations where you want to know how many rows were deleted, for example if you do something based on how many rows were deleted. Checking it by performing a COUNT creates extra database load and is not atomic.

The queryset.delete() method immediately deletes the object and returns the number of objects deleted and a dictionary with the number of deletions per object type. Check the docs for more details: https://docs.djangoproject.com/en/stable/topics/db/queries/#deleting-objects

like image 133
Michaël de Groot Avatar answered Sep 26 '22 00:09

Michaël de Groot